<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ statistics - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ statistics - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 25 May 2026 22:37:33 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/statistics/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Data Science Insights: Why the Mean Lies When Handling Messy Retail Data ]]>
                </title>
                <description>
                    <![CDATA[ In our daily life, we use the word "average" all the time: average salary, average marks, average age, and so on. Let's take the case of a retail shop. If we're looking at the average order value to u ]]>
                </description>
                <link>https://www.freecodecamp.org/news/data-science-insights-why-the-mean-lies-when-handling-messy-retail-data/</link>
                <guid isPermaLink="false">69fa21e5a386d7f121b5fe8c</guid>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MathJax ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Rakshath Naik ]]>
                </dc:creator>
                <pubDate>Tue, 05 May 2026 16:59:17 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/4441dcfc-d100-4613-9937-9c62449c6780.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In our daily life, we use the word "average" all the time: average salary, average marks, average age, and so on.</p>
<p>Let's take the case of a retail shop. If we're looking at the average order value to understand customer spending, we'd load the data, run the code, and get a result of $20 per order.</p>
<p>Done.</p>
<p>Except something looks odd.</p>
<p>When we take a closer look, we see that most customers are buying items worth \(8 - \)15. So where's $20 coming from?</p>
<p>In that case, the problem isn’t data – it’s the average. This is a clean textbook trap where everything works perfectly in the textbook, but real-world data doesn’t behave nicely.</p>
<p>Some customers buy in bulk (very large orders), some return orders (negative quantities), and a few anomalies distort the entire picture.</p>
<p>In this article, we'll use the Online Retail Dataset to answer a simple but tricky question: What does “average” really mean in the real world?</p>
<h2 id="heading-table-of-contents">Table Of Contents</h2>
<ul>
<li><p><a href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#heading-the-dataset">The Dataset</a></p>
</li>
<li><p><a href="#heading-mean-the-sensitive-giant">Mean: The Sensitive Giant</a></p>
</li>
<li><p><a href="#heading-median-the-robust-middle">Median: The Robust Middle</a></p>
</li>
<li><p><a href="#heading-beyond-averages-understanding-spread-with-quartiles">Beyond Averages: Understanding Spread with Quartiles</a></p>
</li>
<li><p><a href="#heading-applying-iqr-to-our-dataset">Applying IQR to Our Dataset</a></p>
</li>
<li><p><a href="#heading-final-comparison-and-insights">Final Comparison and Insights</a></p>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
<li><p><a href="#heading-connect-with-me">Connect with me</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along here, you'll need:</p>
<p><strong>Basic Python knowledge:</strong> Understanding of variables and functions.</p>
<p><strong>The Pandas library:</strong> Familiarity with loading data and basic DataFrame operations.</p>
<p><strong>A development environment:</strong> Access to a tool like Jupyter Notebook, VS Code, or Google Colab.</p>
<p><strong>A Dataset:</strong> For this analysis, I used the Online Retail Dataset, which is available for download <a href="https://archive.ics.uci.edu/dataset/352/online+retail">here</a>.</p>
<h2 id="heading-the-dataset"><strong>The Dataset</strong></h2>
<p>We'll work with the Online Retail Dataset, a real-world transactional dataset containing purchase records from a UK-based online retail store.</p>
<ol>
<li><p><strong>Source:</strong> UCI Machine Learning Repository</p>
</li>
<li><p><strong>Collected by:</strong> UK-based online retail company (2010–2011)</p>
</li>
<li><p><strong>Size:</strong> 541,909 transactions</p>
</li>
<li><p><strong>Features:</strong> 8 attributes (InvoiceNo, StockCode, Description, Quantity, InvoiceDate, UnitPrice, CustomerID, Country)</p>
</li>
<li><p><strong>Ownership:</strong> Public dataset hosted by UCI</p>
</li>
<li><p><strong>License:</strong> Open for research and educational use</p>
</li>
</ol>
<h2 id="heading-mean-the-sensitive-giant">Mean: The Sensitive Giant</h2>
<p>In statistics and data analysis, the terms "<strong>average</strong>" and "<strong>arithmetic mean</strong>" are often used interchangeably. We aim to find the mean total price in our dataset. Mean in the context of the Online Retail Dataset is given as:</p>
<p>$$\text{Average Order Value} = \frac{\text{Sum of all TotalPrice values}}{\text{Number of transactions}}$$</p>
<p>In our dataset, the mean is calculated by summing all transaction values (including bulk purchases and returns) and dividing by the total number of transactions. This means every value, irrespective of unusually high or any negative values, directly influences the final average.</p>
<pre><code class="language-python"># Load the dataset
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00352/Online%20Retail.xlsx"
df = pd.read_excel(url, engine='openpyxl')

# Clean and Feature Engineering
df = df.dropna(subset=['CustomerID'])
df['TotalPrice'] = df['Quantity'] * df['UnitPrice']

# Calculate the Mean (Average Order Value)
mean_value = df['TotalPrice'].mean()
print(f"Average Order Value (Mean): {mean_value:.2f}")
</code></pre>
<p>The results are as follows:</p>
<pre><code class="language-python">Average Order Value (Mean): 20.40
</code></pre>
<p>At first glance, the results may look promising: every transaction contributes equally. But that’s where the problem lies. Sometimes a few transactions, which are extremely high or low, affect the mean for all customers who lie in the closer range.</p>
<p>Take a look at the graph for the mean below.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6942c2903c5d674e359eaf1e/583bebff-0e5e-44b8-80cb-48e4662b9abf.png" alt="The graph shows the calculated mean for the Online Retail Dataset, where we get a mean of 20.40" style="display:block;margin:0 auto" width="876" height="547" loading="lazy">

<p>The graph shows the mean Total Price for the Online Retail Dataset. We get a mean of 20.42. (Image by Author)</p>
<p>The graph shows <strong>a right-skewed distribution</strong> where the calculated mean of 20.40 is actually a textbook trap. The tallest bar clearly shows that the majority of transactions lie in the range of \(8 - \)15 range, but the <strong>red line</strong> is being dragged to the right by the <strong>long tail</strong> of high-value bulk orders by some customers.</p>
<p>In this scenario, the average price is well above what a typical customer actually spends because it's highly sensitive to outliers – and in reality, the bulk of the data lives in the lower price range.</p>
<p>In simple words, the mean is being pulled by some extreme values to the right, especially by some lying in the range of 200–300, which is noticeable in the graph.</p>
<h2 id="heading-median-the-robust-middle">Median: The Robust Middle</h2>
<p>When the mean is distorted by extreme values, we need a metric that remains unaffected by such outliers. This is where the median comes into play.</p>
<p>Median is defined as the <strong>middle value after sorting the data.</strong></p>
<p>In our dataset, we sort all the transactions and pick the middle one.</p>
<p>The formula for calculating the median is:</p>
<p>$$\text{Median} = \begin{cases} X_{\left[ \frac{n+1}{2} \right]} &amp; \text{if } n \text{ is odd} \ \frac{X_{\left[ \frac{n}{2} \right]} + X_{\left[ \frac{n}{2} + 1 \right]}}{2} &amp; \text{if } n \text{ is even} \end{cases}$$</p>
<p>Unlike the mean, the median doesn't depend on extreme values, and it cares only about the position of the data, not the magnitude.</p>
<pre><code class="language-python"># Clean and Feature Engineering
df = df.dropna(subset=['CustomerID'])
df['TotalPrice'] = df['Quantity'] * df['UnitPrice']

# Calculate only the Median
median_value = df['TotalPrice'].median()
print(f"Typical Order Value (Median): {median_value:.2f}")
</code></pre>
<p>The results are as follows:</p>
<pre><code class="language-python">Typical Order Value (Median): 11.10
</code></pre>
<p>Now you'll notice that the result lies in the \(8 — \)15 range, where most of the transactions lie.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6942c2903c5d674e359eaf1e/d89a4912-0e44-485e-8ea0-ff559cea6eba.png" alt="The figure demonstrates the graph for the median, where we get an accurate value of the transactions by the customers." style="display:block;margin:0 auto" width="876" height="547" loading="lazy">

<p>The figure demonstrates the graph for the median, where we get an accurate value of the transactions by the customers. (Image by Author)</p>
<p>In the previous graph, the mean was pulled to the right by large orders, but the median just asks what the middle customer spends. So even if someone spends $300 or some transactions are negative, the median stays stable.</p>
<p>In the above figure <strong>the median graph</strong> accurately highlights the range where most of the customers lie.</p>
<h2 id="heading-beyond-averages-understanding-spread-with-quartiles"><strong>Beyond Averages: Understanding Spread with Quartiles</strong></h2>
<p>So far, we've studied the median, but knowing the center is not enough.</p>
<p>To truly understand how customer spending is, we need to understand how the data is spread, and this is where quartiles come into play.</p>
<p>Quartiles divide the dataset into the following parts:</p>
<ol>
<li><p><strong>Q1(25th percentile):</strong> 25% of transactions are below this.</p>
</li>
<li><p><strong>Q2 (50th percentile):</strong> Median</p>
</li>
<li><p><strong>Q3 (75th percentile):</strong> 75% of transactions are below this.</p>
</li>
</ol>
<p>This is formally expressed as the Interquartile Range (IQR):</p>
<p>$$IQR = Q_3 - Q_1$$</p>
<h3 id="heading-the-iqr-detecting-outliers"><strong>The IQR: Detecting Outliers</strong></h3>
<p>The IQR measures the spread of the middle 50%.</p>
<p>If the IQR is small, then the data is concentrated. If it's large, the data is spread out. The IQR also helps us identify outliers mathematically.</p>
<p>Outlier Rule:</p>
<ol>
<li><p><strong>Lower Bound = Q1 — 1.5 * IQR</strong></p>
</li>
<li><p><strong>Upper Bound = Q3 + 1.5 * IQR</strong></p>
</li>
</ol>
<h4 id="heading-a-simple-example-to-understand-iqr">A Simple Example to Understand IQR</h4>
<p>Consider the following transaction values:</p>
<p>$$\left[ 5, 8, 10, 12, 15, 18, 20 \right]$$</p>
<h4 id="heading-step-1-find-the-median-q2">Step 1: Find the Median (Q2):</h4>
<p>The middle value is:</p>
<p>$$Q_2 = 12$$</p>
<h4 id="heading-step-2-find-q1-lower-quartile">Step 2: Find Q1 (Lower Quartile):</h4>
<p>The lower half is [5, 8, 10]. The median of the lower half is:</p>
<p>$$Q_1 = 8$$</p>
<h4 id="heading-step-3-find-q3-upper-quartile">Step 3: Find Q3 (Upper Quartile):</h4>
<p>The upper half is [15, 18, 20]. The median of the upper half is:</p>
<p>$$Q_3 = 18$$</p>
<h4 id="heading-step-4-calculate-iqr">Step 4: Calculate IQR:</h4>
<p>$$IQR = Q_3 - Q_1 = 18 - 8 = 10$$</p>
<h4 id="heading-step-5-find-outlier-bounds">Step 5: Find Outlier Bounds:</h4>
<p>$$\begin{aligned} \text{Lower Bound} &amp;= Q_1 - 1.5 \times IQR = 8 - 15 = -7 \ \text{Upper Bound} &amp;= Q_3 + 1.5 \times IQR = 18 + 15 = 33 \end{aligned}$$</p>
<p>Any value <strong>below -7 or above 33</strong> is an outlier (but in this demo problem, no outliers exist).</p>
<h2 id="heading-applying-iqr-to-our-dataset"><strong>Applying IQR to Our Dataset</strong></h2>
<p>In our retail dataset, instead of neat values, we have bulk values and even negative returns.</p>
<pre><code class="language-python"># 1. Calculate IQR and Bounds
Q1 = df['TotalPrice'].quantile(0.25)
Q3 = df['TotalPrice'].quantile(0.75)
IQR = Q3 - Q1

lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR
</code></pre>
<p>When we calculate IQR for our dataset, we get:</p>
<pre><code class="language-python">Lower Bound: -18.75
Upper Bound: 42.45
Number of Outliers: 33180
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6942c2903c5d674e359eaf1e/e528db9b-57f9-4ee4-b331-143c2b1947fb.png" alt="The figure demonstrates the outlier range for our dataset" style="display:block;margin:0 auto" width="1036" height="547" loading="lazy">

<p>The graph demonstrates outliers, which are any values falling outside the range of -18.75 to 42.45. (Image by Author)</p>
<p>As the graph shows, the values outside the range -18.75 to 42.45 are considered outliers. These values will be removed.</p>
<h3 id="heading-revisiting-the-mean-after-removing-outliers">Revisiting the Mean After Removing Outliers</h3>
<p>Using the IQR method, we've removed extreme transactions that fell outside the typical spending range.</p>
<pre><code class="language-python"># Clean and Feature Engineering
df = df.dropna(subset=['CustomerID'])
df['TotalPrice'] = df['Quantity'] * df['UnitPrice']

# Original Mean
mean_value = df['TotalPrice'].mean()
print(f"Original Mean: {mean_value:.2f}")

# IQR Calculation
Q1 = df['TotalPrice'].quantile(0.25)
Q3 = df['TotalPrice'].quantile(0.75)
IQR = Q3 - Q1

# Define bounds
lower_bound = Q1 - 1.5 * IQR
upper_bound = Q3 + 1.5 * IQR

print(f"Lower Bound: {lower_bound:.2f}")
print(f"Upper Bound: {upper_bound:.2f}")

# Remove Outliers
df_no_outliers = df[(df['TotalPrice'] &gt;= lower_bound) &amp; (df['TotalPrice'] &lt;= upper_bound)]

# New Mean after removing outliers
new_mean = df_no_outliers['TotalPrice'].mean()
print(f"Mean after removing outliers: {new_mean:.2f}")
</code></pre>
<p>After recomputing, we get:</p>
<pre><code class="language-python">Original Mean: 20.40
Lower Bound: -18.75
Upper Bound: 42.45
Mean after removing outliers: 11.63
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6942c2903c5d674e359eaf1e/17e6c2d0-883f-4e48-b45b-d1bf93164c63.png" alt="The graph demonstrates that the mean improves significantly after all outliers are removed. (Image by Author)" style="display:block;margin:0 auto" width="876" height="547" loading="lazy">

<p>Removing outliers significantly shifts the mean toward the region where most transactions occur. We now have a much better mean of 11.63 as opposed to the right-stretched mean of 20.40 we got with outliers.</p>
<h2 id="heading-final-comparison-and-insights"><strong>Final Comparison and Insights</strong></h2>
<p>Looking at the results from all the graphs, we get a complete understanding of the dataset. The original mean was 20.40, which appeared to be significantly higher than the most transactions that actually occurred. In that case, the mean was pulled upward by some of the high-valued transactions and was distorted by the outliers.</p>
<p>The median, on the other hand, was 11.10, which lies within the range where most transactions are concentrated. This shows that the median is a much better representation of what a typical customer spends, as it's not affected by extreme values.</p>
<p>After removing the outliers using the IQR, the mean dropped to 11.63, bringing it very close to the median. This confirms that the earlier mean was not inherently wrong, but was simply influenced by extreme values in the data. Once those values were handled, the mean became a much more reliable measure of central tendency.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>The results show that the mean can be misleading when data contains outliers. In our dataset, the original mean of 20.40 overstated customer spending, while the median (11.10) gave a more realistic picture. After removing outliers, the mean shifted to 11.63, aligning closely with the median.</p>
<p>This highlights a key lesson: <strong>The mean isn't wrong, but it must be used with an understanding of the data.</strong></p>
<p>Choosing the right measure of average depends on the dataset, and in messy real-world scenarios, the median or a cleaned mean often tells the true story.</p>
<h2 id="heading-connect-with-me"><strong>Connect with me</strong></h2>
<ol>
<li><p><a href="https://medium.com/@rakshathnaik62">Medium</a></p>
</li>
<li><p><a href="https://www.linkedin.com/in/rakshath-/">LinkedIN</a></p>
</li>
</ol>
<p>If you want to dive deeper, you can visit: <a href="https://qubrica.com/mean-median-mode-python-guide/"><strong>Mean vs Median vs Mode: Understanding Central Tendency in Data Analysis</strong></a><strong>.</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Markov Chains? Explained With Python Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ There are various mathematical tools that can be used to predict the near future based on a current state. One of the most widely used are Markov chains. Markov chains allow you to predict the uncertainty of future events under certain conditions. Fo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-a-markov-chain/</link>
                <guid isPermaLink="false">66ba5357cccc49d721b6ea23</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tiago Capelo Monteiro ]]>
                </dc:creator>
                <pubDate>Mon, 08 Jul 2024 12:53:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/miltiadis-fragkidis-2zGTh-S5moM-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There are various mathematical tools that can be used to predict the near future based on a current state. One of the most widely used are Markov chains.</p>
<p>Markov chains allow you to predict the uncertainty of future events under certain conditions. For this reason, it is widely used in science, engineering, economics and many more areas.</p>
<p>However, there are many types of Markov Chains and each have their own applications.</p>
<p>This guide introduces what Markov chains are, different types of Markov chains, including Discrete-Time, Continuous-Time, Reversible, and a code example of Hidden Markov Models (HMMs).</p>
<p>We will see:</p>
<ul>
<li><a class="post-section-overview" href="#analogy">Analogy</a></li>
<li><a class="post-section-overview" href="#heading-markov-chain-explained-in-plain-english">Markov Chain Explained in plain English</a></li>
<li><a class="post-section-overview" href="#heading-applications-of-markov-chains">Applications of Markov Chains</a></li>
<li><a class="post-section-overview" href="#types-of-markov-chains">Types of Markov Chains</a></li>
<li><a class="post-section-overview" href="#hidden-markov-chains-code-example">Hidden Markov Chains Code Example</a></li>
</ul>
<h2 id="heading-analogy"> Analogy </h2>

<p>Imaging that you want to predict the weather tomorrow, and it <strong>only</strong> depends on the weather today. The weather can be either sunny or rainy.</p>
<p>Here are the probabilities:</p>
<ul>
<li>If it's sunny today, there's an 80% chance that it will be sunny again tomorrow, and a 20% chance that it will be rainy.</li>
<li>If it's rainy today, there's a 50% chance that it will be sunny tomorrow, and a 50% chance that it will be rainy.</li>
</ul>
<p>In this scenario, we can predict future states of the weather based on current states using probabilities.</p>
<p>This idea of predicting the future based solely probabilities of the present is called Markov chain.</p>
<p>Here, the states are either sunny or rainy and the probabilities describe the chances of the weather changing based on the current state.</p>
<h2 id="heading-markov-chain-explained-in-plain-english">Markov Chain Explained in Plain English</h2>
<p>A Markov chain describes random processes where systems move between states, and a new state only depends on the current state, not on how it got there.</p>
<p>Mathematically, Markov chains are called stochastic models because they model (simulate) real life events that are random by nature (stochastic).</p>
<p>Markov chains are very easy to implement and efficient at modeling complex systems.</p>
<p>Another key advantage is their "memoryless" property. This makes it faster to run on computers, and powerful to study random processes and make prediction based on current conditions.</p>
<h2 id="heading-applications-of-markov-chains">Applications of Markov Chains</h2>
<p>At some level, almost all real-life events are stochastic. In other words, they involve randomness and uncertainty.</p>
<p>This is exactly why they are so widely used. They can predict the behavior of systems based on current conditions.</p>
<p>In finance, they are used to detect changes in credit ratings for forecasting market regimes.</p>
<p>In genetics, they help understand how proteins change over time. Which is important when studying genetic variations.</p>
<p>In robotics, they assist with decision-making by predicting the robot's next move based on current observation.</p>
<p>There, real life examples show how effective Markov chains can be used to solve real life problems in different fields.</p>
<h2 id="heading-types-of-markov-chains"> Types of Markov Chains </h2>

<p>There are many types of Markov chains. In this section, we'll only discuss the most important variants of Markov chains.</p>
<h3 id="heading-discrete-time-markov-chains-dtmcs">Discrete-Time Markov Chains (DTMCs)</h3>
<p>In DTMCs, the system changes state at specific time steps. They are called discrete because the state transitions occur at distinct, separate time intervals.</p>
<p>They are used in queuing theory (study of the behavior of waiting lines), genetics, and economics because they are simple to analyze.</p>
<h3 id="heading-continuous-time-markov-chains-ctmcs">Continuous-Time Markov Chains (CTMCs)</h3>
<p>CTMCs differ from DTMCs in that state transitions can occur at any continuous time point, not at fixed intervals.</p>
<p>This makes them stochastic models where state changes happen continuously. This is important in chemical reactions and reliability engineering.</p>
<h3 id="heading-reversible-markov-chains">Reversible Markov Chains</h3>
<p>Reversible Markov chains are special. The process of state change is the same whether the direction is forwards or backwards, like rewinding a video and playing it again.</p>
<p>This property makes it easier to know when a system is stable and study how a system behaves over time. They are widely used in statistical physics and economics</p>
<h3 id="heading-doubly-stochastic-markov-chains">Doubly Stochastic Markov Chains</h3>
<p>Doubly stochastic Markov chains are defined by a transition probability matrix. In the matrix, the sum of the probabilities in each row and each column equals 1.</p>
<p>This means each row and each column represent a valid probability distribution. In other words, each row and column represent a list of chances for different outcomes.</p>
<p>This property is crucial in quantum computing and statistical mechanics.</p>
<p>Thanks to Doubly stochastic Markov chains, systems change in a way that preserves probabilities and symmetry, making the modeling and analysis of quantum computing systems far more accurate.</p>
<h2 id="heading-hidden-markov-chains-code-example"> Hidden Markov Chains Code Example </h2>

<p>Before we jump into code examples, lets first understand what Hidden Markov Chains are.</p>
<h3 id="heading-hidden-markov-chains-modeling-unseen-states">Hidden Markov Chains: Modeling Unseen States</h3>
<p>The main idea behind hidden Markov chains is to model systems that have hidden states (states we do not know their values) which can only be discovered through observable events.</p>
<p>In other words, hidden Markov chains allow us to predict the behavior of a system by:</p>
<ul>
<li>Considering the likelihood of moving from one state to another.</li>
<li>Knowing the probability of observing a certain event from each state</li>
</ul>
<p>We can understand this by observing how the states change from an indirect point of view.</p>
<p>We many not know the states original values.</p>
<p>But by knowing the way they change, we can predict what their values will be in the future.</p>
<p>This way, hidden Markov chains are flexible in modeling sequences, capturing both the transitions between hidden states and the observable outcomes.</p>
<p>Because of this, hidden Markov models are used in fields such as engineering, financial modeling, speech recognition, bioinformatics, and many more.</p>
<h3 id="heading-code-example">Code Example</h3>
<p>In this code example, we will see a simple example with synthetic data.</p>
<p>Here is the full code:</p>
<pre><code><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> hmmlearn <span class="hljs-keyword">import</span> hmm

# <span class="hljs-built_in">Set</span> random seed <span class="hljs-keyword">for</span> reproducibility
np.random.seed(<span class="hljs-number">42</span>)

# Define the HMM parameters
n_components = <span class="hljs-number">2</span>  # <span class="hljs-built_in">Number</span> <span class="hljs-keyword">of</span> states
n_features = <span class="hljs-number">1</span>    # <span class="hljs-built_in">Number</span> <span class="hljs-keyword">of</span> observation features

# Create a Gaussian HMM
model = hmm.GaussianHMM(n_components=n_components, covariance_type=<span class="hljs-string">"diag"</span>)

# Define transition matrix (rows must sum to <span class="hljs-number">1</span>)
model.startprob_ = np.array([<span class="hljs-number">0.6</span>, <span class="hljs-number">0.4</span>])
model.transmat_ = np.array([[<span class="hljs-number">0.7</span>, <span class="hljs-number">0.3</span>],
                            [<span class="hljs-number">0.4</span>, <span class="hljs-number">0.6</span>]])

# Define means and covariances <span class="hljs-keyword">for</span> each state
model.means_ = np.array([[<span class="hljs-number">0.0</span>], [<span class="hljs-number">3.0</span>]])
model.covars_ = np.array([[<span class="hljs-number">0.5</span>], [<span class="hljs-number">0.5</span>]])

# Generate synthetic observation data
X, Z = model.sample(<span class="hljs-number">100</span>)  # <span class="hljs-number">100</span> samples

# Create a <span class="hljs-keyword">new</span> HMM instance
new_model = hmm.GaussianHMM(n_components=n_components, covariance_type=<span class="hljs-string">"diag"</span>, n_iter=<span class="hljs-number">100</span>)

# Fit the model to the data
new_model.fit(X)

# Print the learned parameters
print(<span class="hljs-string">"Transition matrix:"</span>)
print(new_model.transmat_)
print(<span class="hljs-string">"Means:"</span>)
print(new_model.means_)
print(<span class="hljs-string">"Covariances:"</span>)
print(new_model.covars_)

# Predict the hidden states <span class="hljs-keyword">for</span> the observed data
hidden_states = new_model.predict(X)

print(<span class="hljs-string">"Hidden states:"</span>)
print(hidden_states)
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2024/06/1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Full code</em></p>
<p>Lets see the code block by block!</p>
<h3 id="heading-import-libraries-and-set-random-seed">Import libraries and set random seed</h3>
<pre><code><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> hmmlearn <span class="hljs-keyword">import</span> hmm

np.random.seed(<span class="hljs-number">42</span>)
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2024/06/2.png" alt="Image" width="600" height="400" loading="lazy">
<em>Import libraries and set random seed</em></p>
<p>In this block of code, we imported two python libraries:</p>
<ul>
<li><a target="_blank" href="https://numpy.org/">NumPy</a>: For numerical operations.</li>
<li><a target="_blank" href="https://hmmlearn.readthedocs.io/en/latest/index.html">hmmlearn</a>: For hidden Markov model implementation.</li>
</ul>
<p>Next we defined with the <code>numpy</code> library a random seed.</p>
<h4 id="heading-what-is-a-random-seed">What is a Random Seed?</h4>
<p>A random seed is a value used to start a pseudorandom number generator.</p>
<p>With a fixed random seed, we ensure that the sequence of pseudorandom numbers generated is always the same.</p>
<p>This allows us to duplicate experiments and verify results.</p>
<p>The specific value of the seed does not matter as long as it remains consistent.</p>
<h3 id="heading-define-the-hmm-parameters-and-create-a-gaussian-hmm">Define the HMM parameters and create a Gaussian HMM</h3>
<pre><code>n_components = <span class="hljs-number">2</span>  # <span class="hljs-built_in">Number</span> <span class="hljs-keyword">of</span> states
n_features = <span class="hljs-number">1</span>    # <span class="hljs-built_in">Number</span> <span class="hljs-keyword">of</span> observation features

model = hmm.GaussianHMM(n_components=n_components, covariance_type=<span class="hljs-string">"diag"</span>)
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2024/06/3.png" alt="Image" width="600" height="400" loading="lazy">
<em>Define the HMM parameters and create a Gaussian HMM</em></p>
<p>In this code block, we created a HMM with two hidden states and a single observed variable.</p>
<p><code>covariance_type "diag"</code> means the matrices that represent covariance–how two variables change together–are diagonal. In other words, each row and column is assumed to be independent of the others.</p>
<p>This implies that the probability distributions of each row and column are independent of each other.</p>
<p>However, there is still something strange when we defined the hidden Markov chain.</p>
<h4 id="heading-what-does-gaussian-mean">What Does "Gaussian" Mean?</h4>
<p>This is a very big topic in statistics, but in a few words, Markov chains can only be created when we specify the transition probabilities—chances of moving from one state to another in a Markov chain—and an initial probability distribution.</p>
<p>A Gaussian HMM assumes events are initially modeled by a Gaussian distribution, also called a normal distribution.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/06/normal-distribution.png" alt="Image" width="600" height="400" loading="lazy">
<em>Normal distribution</em></p>
<p>A normal distribution is like a bell-shaped curve that describes how things are often spread out in nature.</p>
<p>The normal distribution is crucial because it describes many natural occurrences like human heights, measurement errors, how likely a disease might spread and many more.</p>
<p>And while many natural events may not be described by a normal distribution with the <a target="_blank" href="https://www.investopedia.com/terms/c/central_limit_theorem.asp">central limit theorem</a>, they can be approximated to be described by a normal distribution.</p>
<p>This way, many hidden Markov models (HMMs) are defined by a normal distribution, which represents many phenomena in nature and society</p>
<p>In the hmmlearn library, there is also the possibility of creating Markov chains based on Poisson distributions.</p>
<p>In simple words, Poisson distributions model probabilities that describe the occurrence of events over a fixed interval of time or space. This is widely used in telecommunications.</p>
<p>HMMs based on a Poisson distribution would predict events that often happen to be random and independent over a specified interval.</p>
<h3 id="heading-define-transition-matrix-means-and-covariances-for-each-state">Define transition matrix , means and covariances for each state</h3>
<pre><code>model.startprob_ = np.array([<span class="hljs-number">0.6</span>, <span class="hljs-number">0.4</span>])
model.transmat_ = np.array([[<span class="hljs-number">0.7</span>, <span class="hljs-number">0.3</span>],
                            [<span class="hljs-number">0.4</span>, <span class="hljs-number">0.6</span>]])

model.means_ = np.array([[<span class="hljs-number">0.0</span>], [<span class="hljs-number">3.0</span>]])
model.covars_ = np.array([[<span class="hljs-number">0.5</span>], [<span class="hljs-number">0.5</span>]])
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2024/06/4.png" alt="Image" width="600" height="400" loading="lazy">
<em>Define transition matrix , means and covariances for each state</em></p>
<p><strong><code>model.startprob_ = np.array([0.6, 0.4])</code></strong>:</p>
<ul>
<li>This line sets the initial state probabilities for a Hidden Markov Model (HMM). It indicates that there is a 60% probability of starting in state 0 and a 40% probability of starting in state 1.</li>
</ul>
<p><strong><code>model.transmat_ = np.array([[0.7, 0.3], [0.4, 0.6]])</code></strong>:</p>
<ul>
<li>This line sets the state transition probability matrix for the HMM. The matrix specifies the probabilities of moving from one state to another:</li>
<li>From state 0, there is a 70% chance of staying in state 0 and a 30% chance of transitioning to state 1.</li>
<li>From state 1, there is a 40% chance of transitioning to state 0 and a 60% chance of staying in state 1.</li>
</ul>
<p><strong><code>model.means_ = np.array([[0.0], [3.0]])</code></strong>:</p>
<ul>
<li>This line sets the mean values for the observation distributions in each state. It indicates that the observations are normally distributed with a mean of 0.0 in state 0 and a mean of 3.0 in state 1.</li>
</ul>
<p><strong><code>model.covars_ = np.array([[0.5], [0.5]])</code></strong>:</p>
<ul>
<li>This line sets the covariance values for the observation distributions in each state. It specifies that the variance (covariance in this 1-dimensional case) of the observations is 0.5 for both state 0 and state 1.</li>
</ul>
<h3 id="heading-create-data-new-hmm-instance-and-fit-the-model-with-the-data">Create data, new HMM instance and fit the model with the data</h3>
<pre><code>X, Z = model.sample(<span class="hljs-number">100</span>)  # <span class="hljs-number">100</span> samples

new_model = hmm.GaussianHMM(n_components=n_components, covariance_type=<span class="hljs-string">"diag"</span>, n_iter=<span class="hljs-number">100</span>)

new_model.fit(X)

print(<span class="hljs-string">"Transition matrix:"</span>)
print(new_model.transmat_)
print(<span class="hljs-string">"Means:"</span>)
print(new_model.means_)
print(<span class="hljs-string">"Covariances:"</span>)
print(new_model.covars_)
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2024/06/5.png" alt="Image" width="600" height="400" loading="lazy">
<em>Create data, new HMM instance and fit the model with the data</em></p>
<p>In this code, we created a model with 100 samples, iterated it 100 times, and printed the new state transition matrix, means, and covariances.</p>
<p>In other words, we generated 100 samples from the original model, fit a new Hidden Markov Model (HMM) to these samples, and then printed the learned parameters of this new model.</p>
<ul>
<li><strong>X</strong> means the observed data samples generated by the original model.</li>
<li><strong>Z</strong> means the hidden state sequences corresponding to the observed data samples generated by the original model.</li>
</ul>
<p><strong>The transition matrix prints out:</strong></p>
<pre><code>[[<span class="hljs-number">0.8100804</span>  <span class="hljs-number">0.1899196</span> ]
 [<span class="hljs-number">0.49398918</span> <span class="hljs-number">0.50601082</span>]]
</code></pre><p>Which means that the model tends to stay in state 0 and has nearly equal chances of switching or staying when in state 1.</p>
<p><strong>The means print out:</strong></p>
<pre><code>[[<span class="hljs-number">0.01577373</span>]
 [<span class="hljs-number">3.06245496</span>]]
</code></pre><p>Which means that the average observed value is approximately 0.016 in state 0 and 3.062 in state 1.</p>
<p><strong>The covariances print out:</strong></p>
<pre><code>[[[<span class="hljs-number">0.41987084</span>]]
 [[<span class="hljs-number">0.53146802</span>]]]
</code></pre><p>Which means that the observed values varies by about 0.420 in state 0 and 0.531 in state 1.</p>
<p>This way, we may never know exactly the values of the states, but we know:</p>
<ul>
<li>How they tend to change with each other</li>
<li>Their average observed value</li>
<li>How they vary</li>
</ul>
<h3 id="heading-predict-the-hidden-states-for-the-observed-data">Predict the hidden states for the observed data</h3>
<pre><code>hidden_states = new_model.predict(X)

print(<span class="hljs-string">"Hidden states:"</span>)
print(hidden_states)
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2024/06/6.png" alt="Image" width="600" height="400" loading="lazy">
<em>Predict the hidden states for the observed data</em></p>
<p>In this code, based on the X observed data samples, we predicted the new states of the Markov model.</p>
<p>The hidden states print out:</p>
<pre><code>[<span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span>
 <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span>
 <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span>]
</code></pre><p>Which means that the hidden states switch between state 0 and state 1, showing how the system changes states over time.</p>
<h2 id="heading-conclusion-the-future-of-markov-chains">Conclusion: The Future of Markov Chains</h2>
<p>Markov chains are widely used in STEM fields due to their ability to predict the future based on the present.</p>
<p>Markov chains have been integrated more with artificial intelligence, improving automation and predicative analytics of systems.</p>
<p>Additionally, the development of more computationally efficient Markov chains is a big priority, making them more accessible for real-time processing and large-scale simulations.</p>
<p>In summary, Markov chains are a very important tool in science due to their ability to predict the future.</p>
<p>With AI and more computational efficiency, Markov chains can be applied in many other fields and solve many problems.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn Statistics for Data Science, Machine Learning, and AI – Full Handbook ]]>
                </title>
                <description>
                    <![CDATA[ Karl Pearson was a British mathematician who once said "Statistics is the grammar of science". This holds true especially for Computer and Information Sciences, Physical Science, and Biological Science. When you are getting started with your journey ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/statistics-for-data-scientce-machine-learning-and-ai-handbook/</link>
                <guid isPermaLink="false">66d461543dce891ac3a96832</guid>
                
                    <category>
                        <![CDATA[ Artificial Intelligence ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MathJax ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Tatev Aslanyan ]]>
                </dc:creator>
                <pubDate>Fri, 12 Apr 2024 23:08:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/Learn-Statistics-Cover-Version-2--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Karl Pearson was a British mathematician who once said "Statistics is the grammar of science". This holds true especially for Computer and Information Sciences, Physical Science, and Biological Science.</p>
<p>When you are getting started with your journey in Data Science, Data Analytics, Machine Learning, or AI (including Generative AI) having statistical knowledge will help you better leverage data insights and actually understand all the algorithms beyond their implementation approach.</p>
<p>I can't overstate the importance of statistics in data science and Artificial Intelligence. Statistics provides tools and methods to find structure and give deeper data insights. Both Statistics and Mathematics love facts and hate guesses. Knowing the fundamentals of these two important subjects will allow you to think critically, and be creative when using the data to solve business problems and make data-driven decisions.</p>
<h3 id="heading-key-statistical-concepts-for-your-data-science-or-data-analysis-journey-with-python-code">Key statistical concepts for your data science or data analysis journey with Python Code</h3>
<p>In this handbook, I will cover the following Statistics topics for data science, machine learning, and artificial intelligence (including GenAI):</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-random-variables">Random variables</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-mean-variance-standard-deviation">Mean, Variance, Standard Deviation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-covariance">Covariance and Correlation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-probability-distribution-functions">Probability distribution functions (PDFs)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-bayes-theorem">Bayes' Theorem</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-linear-regression">Linear Regression and Ordinary Least Squares (OLS)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-gauss-markov-theorem">Gauss-Markov Theorem</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-parameter-properties">Parameter properties (Bias, Consistency, Efficiency)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-confidence-intervals">Confidence intervals</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-statistical-hypothesis-testing">Hypothesis testing</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-statistical-significance">Statistical significance</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-type-i-and-type-ii-errors">Type I &amp; Type II Error</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-type-i-and-type-ii-errors">Statistical tests (Student's t-test, F-test, 2-Sample T-Test, 2-Sample Z-Test, Chi-Square Test)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-limitation-of-p-values">p-value and its limitations</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-inferential-statistics">Inferential Statistics</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-inferential-statistics">Central Limit Theorem &amp; Law of Large Numbers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-dimensionality-reduction-techniques">Dimensionality reduction techniques (PCA, FA)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-interview-prep-top-7-statistics-questions-with-answers">Interview Prep - Top 7 Statistics Questions with Answers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-about-the-author">About The Author</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-can-you-dive-deeper">How Can You Dive Deeper?</a></p>
</li>
</ul>
<p>If you have no prior Statistical knowledge and you want to identify and learn the essential statistical concepts from the scratch and prepare for your job interviews, then this handbook is for you. It will also be a good read for anyone who wants to refresh their statistical knowledge.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before you start reading this handbook about key concepts in Statistics for Data Science, Machine Learning, and Artificial Intelligence, there are a few prerequisites that will help you make the most out of it.</p>
<p>This list is designed to ensure you are well-prepared and can fully grasp the statistical concepts discussed:</p>
<ol>
<li><p><strong>Basic Mathematical Skills</strong>: Comfort with high school level mathematics, including algebra and basic calculus, is essential. These skills are crucial for understanding statistical formulas and methods.</p>
</li>
<li><p><strong>Logical Thinking</strong>: Ability to think logically and methodically to solve problems will aid in understanding statistical reasoning and applying these concepts to data-driven scenarios.</p>
</li>
<li><p><strong>Computer Literacy</strong>: Basic knowledge of using computers and the internet is necessary since many examples and exercises might require the use of statistical software or coding.</p>
</li>
<li><p>Basic knowledge of Python, such as the creation of variables and working with some basic data structures and coding is also required (if you are not familiar with these concepts, check out my <a target="_blank" href="https://www.youtube.com/watch?v=HXL58Ikh7UM&amp;t=244s"><strong>Python for Data Science 2024 -Full Course for Beginners</strong></a> here).</p>
</li>
<li><p><strong>Curiosity and Willingness to Learn</strong>: A keen interest in learning and exploring data is perhaps the most important prerequisite. The field of data science is constantly evolving, and a proactive approach to learning will be incredibly beneficial.</p>
</li>
</ol>
<p>This handbook assumes no prior knowledge of statistics, making it accessible to beginners. Still, familiarity with the above concepts will greatly enhance your understanding and ability to apply statistical methods effectively in various domains.</p>
<p>If you want to learn Mathematics, Statistics, Machine Learning or AI check out our <a target="_blank" href="https://www.youtube.com/watch?v=TJSfLo49iTM&amp;t=144s"><strong>YouTube Channel</strong></a> and <a target="_blank" href="https://lunartech.ai">LunarTech.ai</a> for free resources.</p>
<h2 id="heading-random-variables">Random Variables</h2>
<p>Random variables form the cornerstone of many statistical concepts. It might be hard to digest the formal mathematical definition of a random variable, but simply put, it's a way to map the outcomes of random processes, such as flipping a coin or rolling a dice, to numbers.</p>
<p>For instance, we can define the random process of flipping a coin by random variable X which takes a value 1 if the outcome is <em>heads</em> and 0 if the outcome is <em>tails.</em></p>
<p>$$X = \begin{cases} 1 &amp; \text{if heads} \\ 0 &amp; \text{if tails} \end{cases}$$</p><p>In this example, we have a random process of flipping a coin where this experiment can produce <strong>two</strong> <strong>possible outcomes</strong>: {0,1}. This set of all possible outcomes is called the <strong>sample space</strong> of the experiment. Each time the random process is repeated, it is referred to as an <strong>event</strong>.</p>
<p>In this example, flipping a coin and getting a tail as an outcome is an event. The chance or the likelihood of this event occurring with a particular outcome is called the <strong>probability</strong> of that event.</p>
<p>A probability of an event is the likelihood that a random variable takes a specific value of x which can be described by P(x). In the example of flipping a coin, the likelihood of getting heads or tails is the same, that is 0.5 or 50%. So we have the following setting:</p>
<p>$$\begin{align} \Pr(X = \text{heads}) = 0.5 \\ \Pr(X = \text{tails}) = 0.5 \end{align}$$</p><p>where the probability of an event, in this example, can only take values in the range [0,1].</p>
<h2 id="heading-mean-variance-standard-deviation">Mean, Variance, Standard Deviation</h2>
<p>To understand the concepts of mean, variance, and many other statistical topics, it is important to learn the concepts of <strong>population</strong> and <strong>sample.</strong></p>
<p>The population is the set of all observations (individuals, objects, events, or procedures) and is usually very large and diverse. On the other hand, a sample is a subset of observations from the population that ideally is a true representation of the population.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-VnNrkwNuW2hBKA8DC84Gdg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Image Source:</em> <a target="_blank" href="LunarTech.ai"><em>LunarTech</em></a></p>
<p>Given that experimenting with an entire population is either impossible or simply too expensive, researchers or analysts use samples rather than the entire population in their experiments or trials.</p>
<p>To make sure that the experimental results are reliable and hold for the entire population, the sample needs to be a true representation of the population. That is, the sample needs to be unbiased.</p>
<p>For this purpose, we can use <a target="_blank" href="https://github.com/TatevKaren/mathematics-statistics-for-data-science/tree/main/Sampling%20Techniques">statistical sampling techniques</a> such as Random Sampling, Systematic Sampling, Clustered Sampling, Weighted Sampling, and Stratified Sampling.</p>
<h3 id="heading-mean">Mean</h3>
<p>The mean, also known as the average, is a central value of a finite set of numbers. Let’s assume a random variable X in the data has the following values:</p>
<p>$$X_1, X_2, X_3, \ldots, X_N$$</p><p>where N is the number of observations or data points in the sample set or simply the data frequency. Then the <strong>sample mean</strong> defined by <strong>μ</strong>, which is very often used to approximate the <strong>population mean</strong>, can be expressed as follows:</p>
<p>$$\mu = \frac{\sum_{i=1}^{N} x_i}{N}$$</p><p>The mean is also referred to as <strong>expectation</strong> which is often defined by <strong>E</strong>() or random variable with a bar on the top. For example, the expectation of random variables X and Y, that is <strong>E</strong>(X) and <strong>E</strong>(Y), respectively, can be expressed as follows:</p>
<p>$$\bar{X} = \frac{\sum_{i=1}^{N} X_i}{N}$$</p><p>$$\bar{Y} = \frac{\sum_{i=1}^{N} Y_i}{N}$$</p><p>Now that we have a solid understanding of the mean as a statistical measure, let's see how we can apply this knowledge practically using Python. Python is a versatile programming language that, with the help of libraries like NumPy, makes it easy to perform complex mathematical operations—including calculating the mean.</p>
<p>In the following code snippet, we demonstrate how to compute the mean of a set of numbers using NumPy. We will start by showing the calculation for a simple array of numbers. Then, we'll address a common scenario encountered in data science: calculating the mean of a dataset that includes undefined or missing values, represented as NaN (Not a Number). NumPy provides a function specifically designed to handle such cases, allowing us to compute the mean while ignoring these NaN values.</p>
<p>Here is how you can perform these operations in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> math
x = np.array([<span class="hljs-number">1</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>])
mean_x = np.mean(x)

<span class="hljs-comment"># in case the data contains Nan values</span>
x_nan = np.array([<span class="hljs-number">1</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>, math.nan])
mean_x_nan = np.nanmean(x_nan)
</code></pre>
<h3 id="heading-variance">Variance</h3>
<p>The variance measures how far the data points are spread out from the average value. It's equal to the sum of the squares of the differences between the data values and the average (the mean).</p>
<p>We can express the <strong>population variance</strong> as follows:</p>
<pre><code class="lang-python">x = np.array([<span class="hljs-number">1</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>])
variance_x = np.var(x)

<span class="hljs-comment"># here you need to specify the degrees of freedom (df) max number of logically independent data points that have freedom to vary</span>
x_nan = np.array([<span class="hljs-number">1</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>, math.nan])
mean_x_nan = np.nanvar(x_nan, ddof = <span class="hljs-number">1</span>)
</code></pre>
<p>For deriving expectations and variances of different popular probability distribution functions, <a target="_blank" href="https://github.com/TatevKaren/mathematics-statistics-for-data-science/tree/main/Deriving%20Expectation%20and%20Variances%20of%20Densities">check out this Github repo</a>.</p>
<h3 id="heading-standard-deviation">Standard Deviation</h3>
<p>The standard deviation is simply the square root of the variance and measures the extent to which data varies from its mean. The standard deviation defined by <strong>sigma</strong> can be expressed as follows:</p>
<p>$$\sigma^2 = \frac{\sum_{i=1}^{N} (x_i - \mu)^2}{N}$$</p><p>Standard deviation is often preferred over the variance because it has the same units as the data points, which means you can interpret it more easily.</p>
<p>To compute the population variance using Python, we utilize the var function from the NumPy library. By default, this function calculates the population variance by setting the ddof (Delta Degrees of Freedom) parameter to 0. However, when dealing with samples and not the entire population, you would typically set ddof to 1 to get the sample variance.</p>
<p>The code snippet provided shows how to calculate the variance for a set of data. Additionally, it shows how to calculate the variance when there are NaN values in the data. NaN values represent missing or undefined data. When calculating the variance, these NaN values must be handled correctly; otherwise, they can result in a variance that is not a number (NaN), which is uninformative.</p>
<p>Here is how you can calculate the population variance in Python, taking into account the potential presence of NaN values:</p>
<pre><code class="lang-python">x = np.array([<span class="hljs-number">1</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>])
variance_x = np.std(x)

x_nan = np.array([<span class="hljs-number">1</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>, math.nan])
mean_x_nan = np.nanstd(x_nan, ddof = <span class="hljs-number">1</span>)
</code></pre>
<h3 id="heading-covariance">Covariance</h3>
<p>The covariance is a measure of the joint variability of two random variables and describes the relationship between these two variables. It is defined as the expected value of the product of the two random variables’ deviations from their means.</p>
<p>The covariance between two random variables X and Z can be described by the following expression, where <strong>E</strong>(X) and <strong>E</strong>(Z) represent the means of X and Z, respectively.</p>
<p>$$\text{Cov}(X, Z) = E\left[(X - E(X))(Z - E(Z))\right]$$</p><p>Covariance can take negative or positive values as well as a value of 0. A positive value of covariance indicates that two random variables tend to vary in the same direction, whereas a negative value suggests that these variables vary in opposite directions. Finally, the value 0 means that they don’t vary together.</p>
<p>To explore the concept of covariance practically, we will use Python with the NumPy library, which provides powerful numerical operations. The np.cov function can be used to calculate the covariance matrix for two or more datasets. In the matrix, the diagonal elements represent the variance of each dataset, and the off-diagonal elements represent the covariance between each pair of datasets.</p>
<p>Let's look at an example of calculating the covariance between two sets of data:</p>
<pre><code class="lang-python">x = np.array([<span class="hljs-number">1</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>])
y = np.array([<span class="hljs-number">-2</span>,<span class="hljs-number">-4</span>,<span class="hljs-number">-5</span>,<span class="hljs-number">-6</span>])

<span class="hljs-comment">#this will return the covariance matrix of x,y containing x_variance, y_variance on diagonal elements and covariance of x,y</span>
cov_xy = np.cov(x,y)
</code></pre>
<h3 id="heading-correlation">Correlation</h3>
<p>The correlation is also a measure of a relationship. It measures both the strength and the direction of the linear relationship between two variables.</p>
<p>If a correlation is detected, then it means that there is a relationship or a pattern between the values of two target variables. Correlation between two random variables X and Z is equal to the covariance between these two variables divided by the product of the standard deviations of these variables. This can be described by the following expression:</p>
<p>$$\rho_{X,Z} = \frac{\text{Cov}(X, Z)}{\sigma_X \sigma_Z}$$</p><p>Correlation coefficients’ values range between -1 and 1. Keep in mind that the correlation of a variable with itself is always 1, that is <strong>Cor(X, X) = 1</strong>.</p>
<p>Another thing to keep in mind when interpreting correlation is to not confuse it with <strong>causation</strong>, given that a correlation is not necessarily a causation. Even if there is a correlation between two variables, you cannot conclude that one variable causes a change in the other. This relationship could be coincidental, or a third factor might be causing both variables to change.</p>
<pre><code class="lang-python">x = np.array([<span class="hljs-number">1</span>,<span class="hljs-number">3</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>])
y = np.array([<span class="hljs-number">-2</span>,<span class="hljs-number">-4</span>,<span class="hljs-number">-5</span>,<span class="hljs-number">-6</span>])

corr = np.corrcoef(x,y)
</code></pre>
<h2 id="heading-probability-distribution-functions">Probability Distribution Functions</h2>
<p>A function that describes all the possible values, the sample space, and the corresponding probabilities that a random variable can take within a given range, bounded between the minimum and maximum possible values, is called <strong>a probability distribution function (pdf)</strong> or probability density.</p>
<p>Every pdf needs to satisfy the following two criteria:</p>
<p>$$0 \leq \Pr(X) \leq 1 \\ \sum p(X) = 1$$</p><p>where the first criterium states that all probabilities should be numbers in the range of [0,1] and the second criterium states that the sum of all possible probabilities should be equal to 1.</p>
<p>Probability functions are usually classified into two categories: <strong>discrete</strong> and <strong>continuous</strong>.</p>
<p>Discrete distribution function describes the random process with <strong>countable</strong> sample space, like in an example of tossing a coin that has only two possible outcomes. Continuous distribution functions describe the random process with a <strong>continuous</strong> sample space.</p>
<p>Examples of discrete distribution functions are <a target="_blank" href="https://en.wikipedia.org/wiki/Bernoulli_distribution">Bernoulli</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Binomial_distribution">Binomial</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Poisson_distribution">Poisson</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Discrete_uniform_distribution">Discrete Uniform</a>. Examples of continuous distribution functions are <a target="_blank" href="https://en.wikipedia.org/wiki/Normal_distribution">Normal</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Continuous_uniform_distribution">Continuous Uniform</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Cauchy_distribution">Cauchy</a>.</p>
<h3 id="heading-binomial-distribution">Binomial Distribution</h3>
<p><a target="_blank" href="https://brilliant.org/wiki/binomial-distribution/">The binomial distribution</a> is the discrete probability distribution of the number of successes in a sequence of <strong>n</strong> independent experiments, each with the boolean-valued outcome: <strong>success</strong> (with probability <strong>p</strong>) or <strong>failure</strong> (with probability <strong>q</strong> = 1 − p).</p>
<p>Let's assume a random variable X follows a Binomial distribution, then the probability of observing <strong>k</strong> successes in n independent trials can be expressed by the following probability density function:</p>
<p>$$\Pr(X = k) = \binom{n}{k} p^k q^{n-k}$$</p><p>The binomial distribution is useful when analyzing the results of repeated independent experiments, especially if you're interested in the probability of meeting a particular threshold given a specific error rate.</p>
<h4 id="heading-binomial-distribution-mean-and-variance">Binomial Distribution Mean and Variance</h4>
<p>The mean of a binomial distribution, denoted as <em>E</em>(<em>X</em>)=<em>np</em>, tells you the average number of successes you can expect if you conduct <em>n</em> independent trials of a binary experiment.</p>
<p>A binary experiment is one where there are only two outcomes: success (with probability <em>p</em>) or failure (with probability <em>q</em>\=1−_p_).</p>
<p>$$E(X) = np \\ \text{Var}(X) = npq$$</p><p>For example, if you were to flip a coin 100 times and you define a success as the coin landing on heads (let's say the probability of heads is 0.5), the binomial distribution would tell you how likely it is to get any number of heads in those 100 flips. The mean <em>E</em>(<em>X</em>) would be 100×0.5=50, indicating that on average, you’d expect to get 50 heads.</p>
<p>The variance Var(X)=npq measures the spread of the distribution, indicating how much the number of successes is likely to deviate from the mean.</p>
<p>Continuing with the coin flip example, the variance would be 100×0.5×0.5=25, which informs you about the variability of the outcomes. A smaller variance would mean the results are more tightly clustered around the mean, whereas a larger variance indicates they’re more spread out.</p>
<p>These concepts are crucial in many fields. For instance:</p>
<ul>
<li><p><strong>Quality Control</strong>: Manufacturers might use the binomial distribution to predict the number of defective items in a batch, helping them understand the quality and consistency of their production process.</p>
</li>
<li><p><strong>Healthcare</strong>: In medicine, it could be used to calculate the probability of a certain number of patients responding to a treatment, based on past success rates.</p>
</li>
<li><p><strong>Finance</strong>: In finance, binomial models are used to evaluate the risk of portfolio or investment strategies by predicting the number of times an asset will reach a certain price point.</p>
</li>
<li><p><strong>Polling and Survey Analysis</strong>: When predicting election results or customer preferences, pollsters might use the binomial distribution to estimate how many people will favor a candidate or a product, given the probability drawn from a sample.</p>
</li>
</ul>
<p>Understanding the mean and variance of the binomial distribution is fundamental to interpreting the results and making informed decisions based on the likelihood of different outcomes.</p>
<p>The figure below visualizes an example of Binomial distribution where the number of independent trials is equal to 8 and the probability of success in each trial is equal to 16%.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-68nMYVFT0e5VsMBf8c226g.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Binomial distribution - showing number of success and probability. Image Source:</em> <a target="_blank" href="https://lunartech.ai"><em>LunarTech</em></a></p>
<p>The Python code below creates a histogram to visualize the distribution of outcomes from 1000 experiments, each consisting of 8 trials with a success probability of 0.16. It uses NumPy to generate the binomial distribution data and Matplotlib to plot the histogram, showing the probability of the number of successes in those trials.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Random Generation of 1000 independent Binomial samples</span>
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt


n = <span class="hljs-number">8</span>
p = <span class="hljs-number">0.16</span>
N = <span class="hljs-number">1000</span>
X = np.random.binomial(n,p,N)
<span class="hljs-comment"># Histogram of Binomial distribution</span>

counts, bins, ignored = plt.hist(X, <span class="hljs-number">20</span>, density = <span class="hljs-literal">True</span>, rwidth = <span class="hljs-number">0.7</span>, color = <span class="hljs-string">'purple'</span>)
plt.title(<span class="hljs-string">"Binomial distribution with p = 0.16 n = 8"</span>)
plt.xlabel(<span class="hljs-string">"Number of successes"</span>)
plt.ylabel(<span class="hljs-string">"Probability"</span>)plt.show()
</code></pre>
<h3 id="heading-poisson-distribution">Poisson Distribution</h3>
<p><a target="_blank" href="https://www.freecodecamp.org/news/poisson-distribution-a-formula-to-calculate-probability-distribution/">The Poisson distribution</a> is the discrete probability distribution of the number of events occurring in a specified time period, given the average number of times the event occurs over that time period.</p>
<p>Let's assume a random variable X follows a Poisson distribution. Then the probability of observing <strong>k</strong> events over a time period can be expressed by the following probability function:</p>
<p>$$\Pr(X = k) = \frac{\lambda^k e^{-\lambda}}{k!}$$</p><p>where <strong>e</strong> is <a target="_blank" href="https://brilliant.org/wiki/eulers-number/"><strong>Euler’s number</strong></a> and <strong>λ</strong> lambda, the <strong>arrival rate parameter</strong>, is the expected value of X. The Poisson distribution function is very popular for its usage in modeling countable events occurring within a given time interval.</p>
<h4 id="heading-poisson-distribution-mean-and-variance">Poisson Distribution Mean and Variance</h4>
<p>The Poisson distribution is particularly useful for modeling the number of times an event occurs within a specified time frame. The mean E(X) and variance Var(X)</p>
<p>Var(X) of a Poisson distribution are both equal to λ, which is the average rate at which events occur (also known as the rate parameter). This makes the Poisson distribution unique, as it is characterized by this single parameter.</p>
<p>The fact that the mean and variance are equal means that as we observe more events, the distribution of the number of occurrences becomes more predictable. It’s used in various fields such as business, engineering, and science for tasks like:</p>
<p>Predicting the number of customer arrivals at a store within an hour. Estimating the number of emails you'd receive in a day. Understanding the number of defects in a batch of materials.</p>
<p>So, the Poisson distribution helps in making probabilistic forecasts about the occurrence of rare or random events over intervals of time or space.</p>
<p>$$E(X) = \lambda \\ \text{Var}(X) = \lambda$$</p><p>For example, Poisson distribution can be used to model the number of customers arriving in the shop between 7 and 10 pm, or the number of patients arriving in an emergency room between 11 and 12 pm.</p>
<p>The figure below visualizes an example of Poisson distribution where we count the number of Web visitors arriving at the website where the arrival rate, lambda, is assumed to be equal to 7 minutes.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-pMhbq88yZEp4gGFYhId82Q.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Randomly generating from Poisson Distribution with lambda = 7. Image Source:</em> <a target="_blank" href="https://lunartech.ai"><em>LunarTech</em></a></p>
<p>In practical data analysis, it is often helpful to simulate the distribution of events. Below is a Python code snippet that demonstrates how to generate a series of data points that follow a Poisson distribution using NumPy. We then create a histogram using Matplotlib to visualize the distribution of the number of visitors (as an example) we might expect to see, based on our average rate λ = 7</p>
<p>This histogram helps in understanding the distribution's shape and variability. The most likely number of visitors is around the mean λ, but the distribution shows the probability of seeing fewer or greater numbers as well.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Random Generation of 1000 independent Poisson samples</span>
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
lambda_ = <span class="hljs-number">7</span>
N = <span class="hljs-number">1000</span>
X = np.random.poisson(lambda_,N)

<span class="hljs-comment"># Histogram of Poisson distribution</span>
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
counts, bins, ignored = plt.hist(X, <span class="hljs-number">50</span>, density = <span class="hljs-literal">True</span>, color = <span class="hljs-string">'purple'</span>)
plt.title(<span class="hljs-string">"Randomly generating from Poisson Distribution with lambda = 7"</span>)
plt.xlabel(<span class="hljs-string">"Number of visitors"</span>)
plt.ylabel(<span class="hljs-string">"Probability"</span>)
plt.show()
</code></pre>
<h3 id="heading-normal-distribution">Normal Distribution</h3>
<p><a target="_blank" href="https://www.freecodecamp.org/news/normal-distribution-explained/">The Normal probability distribution</a> is the continuous probability distribution for a real-valued random variable. Normal distribution, also called <strong>Gaussian distribution</strong> is arguably one of the most popular distribution functions that is commonly used in social and natural sciences for modeling purposes. For example, it is used to model people’s height or test scores.</p>
<p>Let's assume a random variable X follows a Normal distribution. Then its probability density function can be expressed as follows:</p>
<p>$$\Pr(X = k) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{1}{2} \left(\frac{x-\mu}{\sigma}\right)^2}$$</p><p>where the parameter <strong>μ</strong> (mu) is the mean of the distribution also referred to as the <strong>location parameter</strong>, parameter <strong>σ</strong> (sigma) is the standard deviation of the distribution also referred to as the <strong>scale parameter</strong>. The number <a target="_blank" href="https://www.mathsisfun.com/numbers/pi.html"><strong>π</strong></a> (pi) is a mathematical constant approximately equal to 3.14.</p>
<h4 id="heading-normal-distribution-mean-and-variance">Normal Distribution Mean and Variance</h4>
<p>$$E(X) = \mu \\ \text{Var}(X) = \sigma^2$$</p><p>The figure below visualizes an example of Normal distribution with a mean 0 (<strong>μ = 0</strong>) and standard deviation of 1 (<strong>σ = 1</strong>), which is referred to as <strong>Standard Normal</strong> distribution which is symmetric_._</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-T_jAWtNjpf5lx29TbqwigQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Randomly generating 1000 obs from Normal Distribution (mu = 0, sigma = 1). Image Source:</em> <a target="_blank" href="https://lunartech.ai"><em>LunarTech</em></a></p>
<p>The visualization of the standard normal distribution is crucial because this distribution underpins many statistical methods and probability theory. When data is normally distributed with a mean ( μ ) of 0 and standard deviation (σ) of 1, it is referred to as the standard normal distribution. It's symmetric around the mean, with the shape of the curve often called the "bell curve" due to its bell-like shape.</p>
<p>The standard normal distribution is fundamental for the following reasons:</p>
<ul>
<li><p><strong>Central Limit Theorem:</strong> This theorem states that, under certain conditions, the sum of a large number of random variables will be approximately normally distributed. It allows for the use of normal probability theory for sample means and sums, even when the original data is not normally distributed.</p>
</li>
<li><p><strong>Z-Scores:</strong> Values from any normal distribution can be transformed into the standard normal distribution using Z-scores, which indicate how many standard deviations an element is from the mean. This allows for the comparison of scores from different normal distributions.</p>
</li>
<li><p><strong>Statistical Inference and AB Testing:</strong> Many statistical tests, such as t-tests and ANOVAs, assume that the data follows a normal distribution, or they rely on the central limit theorem. Understanding the standard normal distribution helps in the interpretation of these tests' results.</p>
</li>
<li><p><strong>Confidence Intervals and Hypothesis Testing:</strong> The properties of the standard normal distribution are used to construct confidence intervals and to perform hypothesis testing.</p>
</li>
</ul>
<p>All topics which we will cover below!</p>
<p>So, being able to visualize and understand the standard normal distribution is key to applying many statistical techniques accurately.</p>
<p>The Python code below uses NumPy to generate 1000 random samples from a normal distribution with a mean (μ) of 0 and a standard deviation (σ) of 1, which are standard parameters for the standard normal distribution. These generated samples are stored in the variable X.</p>
<p>To visualize the distribution of these samples, the code employs Matplotlib to create a histogram. The plt.hist function is used to plot the histogram of the samples with 30 bins, and the density parameter is set to True to normalize the histogram so that the area under it sums to 1. This effectively turns the histogram into a probability density plot.</p>
<p>Additionally, the SciPy library is used to overlay the probability density function (PDF) of the theoretical normal distribution on the histogram. The norm.pdf function generates the y-values for the PDF given an array of x-values. This theoretical curve is plotted in yellow over the histogram to show how closely the random samples fit the expected distribution.</p>
<p>The resulting graph displays the histogram of the generated samples in purple, with the theoretical normal distribution overlaid in yellow. The x-axis represents the range of values that the samples can take, while the y-axis represents the probability density. This visualization is a powerful tool for comparing the empirical distribution of the data with the theoretical model, allowing us to see whether our samples follow the expected pattern of a normal distribution.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Random Generation of 1000 independent Normal samples</span>
<span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
mu = <span class="hljs-number">0</span>
sigma = <span class="hljs-number">1</span>
N = <span class="hljs-number">1000</span>
X = np.random.normal(mu,sigma,N)

<span class="hljs-comment"># Population distribution</span>
<span class="hljs-keyword">from</span> scipy.stats <span class="hljs-keyword">import</span> norm
x_values = np.arange(<span class="hljs-number">-5</span>,<span class="hljs-number">5</span>,<span class="hljs-number">0.01</span>)
y_values = norm.pdf(x_values)
<span class="hljs-comment">#Sample histogram with Population distribution</span>
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
counts, bins, ignored = plt.hist(X, <span class="hljs-number">30</span>, density = <span class="hljs-literal">True</span>,color = <span class="hljs-string">'purple'</span>,label = <span class="hljs-string">'Sampling Distribution'</span>)
plt.plot(x_values,y_values, color = <span class="hljs-string">'y'</span>,linewidth = <span class="hljs-number">2.5</span>,label = <span class="hljs-string">'Population Distribution'</span>)
plt.title(<span class="hljs-string">"Randomly generating 1000 obs from Normal distribution mu = 0 sigma = 1"</span>)
plt.ylabel(<span class="hljs-string">"Probability"</span>)
plt.legend()
plt.show()
</code></pre>
<h2 id="heading-bayes-theorem">Bayes' Theorem</h2>
<p>The Bayes' Theorem (often called <strong>Bayes' Law</strong>) is arguably the most powerful rule of probability and statistics. It was named after famous English statistician and philosopher, Thomas Bayes.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/0-ypJ6xW1FA_Lh7Faw.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>English mathematician and philosopher Thomas Bayes</em></p>
<p>Bayes' theorem is a powerful probability law that brings the concept of <strong>subjectivity</strong> into the world of Statistics and Mathematics where everything is about facts. It describes the probability of an event, based on the prior information of <strong>conditions</strong> that might be related to that event.</p>
<p>For instance, if the risk of getting Coronavirus or Covid-19 is known to increase with age, then Bayes' Theorem allows the risk to an individual of a known age to be determined more accurately. It does this by conditioning it on the age rather than simply assuming that this individual is common to the population as a whole.</p>
<p>The concept of <strong>conditional probability</strong>, which plays a central role in Bayes' theorem, is a measure of the probability of an event happening, given that another event has already occurred.</p>
<p>Bayes' theorem can be described by the following expression where the X and Y stand for events X and Y, respectively:</p>
<p>$$\Pr(X | Y) = \frac{\Pr(Y | X) \Pr(X)}{\Pr(Y)}$$</p><ul>
<li><p><em>Pr</em> (X|Y): the probability of event X occurring given that event or condition Y has occurred or is true</p>
</li>
<li><p><em>Pr</em> (Y|X): the probability of event Y occurring given that event or condition X has occurred or is true</p>
</li>
<li><p><em>Pr</em> (X) &amp; <em>Pr</em> (Y): the probabilities of observing events X and Y, respectively</p>
</li>
</ul>
<p>In the case of the earlier example, the probability of getting Coronavirus (event X) conditional on being at a certain age is <em>Pr</em> (X|Y). This is equal to the probability of being at a certain age given that the person got a Coronavirus, <em>Pr</em> (Y|X), multiplied with the probability of getting a Coronavirus, <em>Pr</em> (X), divided by the probability of being at a certain age, <em>Pr</em> (Y).</p>
<h2 id="heading-linear-regression">Linear Regression</h2>
<p>Earlier, we introduced the concept of causation between variables, which happens when a variable has a direct impact on another variable.</p>
<p>When the relationship between two variables is linear, then Linear Regression is a statistical method that can help model the impact of a unit change in a variable, <strong>the</strong> <strong>independent variable</strong> on the values of another variable, <strong>the dependent variable</strong>.</p>
<p>Dependent variables are often referred to as <strong>response variables</strong> or <strong>explained variables,</strong> whereas independent variables are often referred to as <strong>regressors</strong> or <strong>explanatory variables</strong>.</p>
<p>When the Linear Regression model is based on a single independent variable, then the model is called <strong>Simple Linear Regression</strong>. When the model is based on multiple independent variables, it’s referred to as <strong>Multiple Linear Regression.</strong></p>
<p>Simple Linear Regression can be described by the following expression:</p>
<p>$$Y_i = \beta_0 + \beta_1X_i + u_i$$</p><p>where <strong>Y</strong> is the dependent variable, <strong>X</strong> is the independent variable which is part of the data, <strong>β0</strong> is the intercept which is unknown and constant, <strong>β1</strong> is the slope coefficient or a parameter corresponding to the variable X which is unknown and constant as well. Finally, <strong>u</strong> is the error term that the model makes when estimating the Y values.</p>
<p>The main idea behind linear regression is to find the best-fitting straight line, <strong>the regression line,</strong> through a set of paired ( X, Y ) data.</p>
<p>One example of the Linear Regression application is modeling the impact of flipper length on penguins’ body mass, which is visualized below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-cS-5_yS2xa--V97U1RoAIQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Image Source:</em> <a target="_blank" href="https://lunartech.ai"><em>LunarTech</em></a></p>
<p>The R code snippet you've shared is for creating a scatter plot with a linear regression line using the <code>ggplot2</code> package in R, which is a powerful and widely-used library for creating graphics and visualizations. The code uses a dataset named <code>penguins</code> from the <code>palmerpenguins</code> package, presumably containing data about penguin species, including measurements like flipper length and body mass.</p>
<pre><code class="lang-python"><span class="hljs-comment"># R code for the graph</span>
install.packages(<span class="hljs-string">"ggplot2"</span>)
install.packages(<span class="hljs-string">"palmerpenguins"</span>)
library(palmerpenguins)
library(ggplot2)
View(data(penguins))
ggplot(data = penguins, aes(x = flipper_length_mm,y = body_mass_g))+
  geom_smooth(method = <span class="hljs-string">"lm"</span>, se = FALSE, color = <span class="hljs-string">'purple'</span>)+
  geom_point()+
  labs(x=<span class="hljs-string">"Flipper Length (mm)"</span>,y=<span class="hljs-string">"Body Mass (g)"</span>)
</code></pre>
<p>Multiple Linear Regression with three independent variables can be described by the following expression:</p>
<p>$$Y_i = \beta_0 + \beta_1X_{1,i} + \beta_2X_{2,i} + \beta_3X_{3,i} + u_i$$</p><h3 id="heading-ordinary-least-squares">Ordinary Least Squares</h3>
<p>The ordinary least squares (OLS) is a method for estimating the unknown parameters such as β0 and β1 in a linear regression model. The model is based on the principle of <strong>least squares</strong>. This minimizes the sum of the squares of the differences between the observed dependent variable and its values that are predicted by the linear function of the independent variable (often referred to as <strong>fitted values</strong>).</p>
<p>This difference between the real and predicted values of dependent variable Y is referred to as <strong>residual</strong>. So OLS minimizes the sum of squared residuals.</p>
<p>This optimization problem results in the following OLS estimates for the unknown parameters β0 and β1 which are also known as <strong>coefficient estimates</strong>:</p>
<p>$$\hat{\beta}1 = \frac{\sum{i=1}^{N} (X_i - \bar{X})(Y_i - \bar{Y})}{\sum_{i=1}^{N} (X_i - \bar{X})^2}$$</p><p>$$\hat{\beta}_0 = \bar{Y} - \hat{\beta}_1\bar{X}$$</p><p>Once these parameters of the Simple Linear Regression model are estimated, the <strong>fitted values</strong> of the response variable can be computed as follows:</p>
<p>$$\hat{Y}_i = \hat{\beta}_0 + \hat{\beta}_1X_i$$</p><h3 id="heading-standard-error">Standard Error</h3>
<p>The <strong>residuals</strong> or the estimated error terms can be determined as follows:</p>
<p>$$\hat{u}_i = Y_i - \hat{Y}_i$$</p><p>It is important to keep in mind the difference between the error terms and residuals. Error terms are never observed, while the residuals are calculated from the data. The OLS estimates the error terms for each observation but not the actual error term. So, the true error variance is still unknown.</p>
<p>Also, these estimates are subject to sampling uncertainty. This means that we will never be able to determine the exact estimate, the true value, of these parameters from sample data in an empirical application. But we can estimate it by calculating the <strong>sample</strong> <strong>residual variance</strong> by using the residuals as follows:</p>
<p>$$\hat{\sigma}^2 = \frac{\sum_{i=1}^{N} \hat{u}_i^2}{N - 2}$$</p><p>This estimate for the variance of sample residuals helps us estimate the variance of the estimated parameters, which is often expressed as follows:</p>
<p>$$\text{Var}(\hat{\beta})$$</p><p>The square root of this variance term is called <strong>the standard error</strong> of the estimate. This is a key component in assessing the accuracy of the parameter estimates. It is used to calculate test statistics and confidence intervals.</p>
<p>The standard error can be expressed as follows:</p>
<p>$$SE(\hat{\beta}) = \sqrt{\text{Var}(\hat{\beta})}$$</p><p>It is important to keep in mind the difference between the error terms and residuals. Error terms are never observed, while the residuals are calculated from the data.</p>
<h4 id="heading-ols-assumptions">OLS Assumptions</h4>
<p>The OLS estimation method makes the following assumptions which need to be satisfied to get reliable prediction results:</p>
<ol>
<li><p>The <strong>Linearity</strong> assumption states that the model is linear in parameters.</p>
</li>
<li><p>The <strong>Random</strong> <strong>Sample</strong> assumption states that all observations in the sample are randomly selected.</p>
</li>
<li><p>The <strong>Exogeneity</strong> assumption states that independent variables are uncorrelated with the error terms.</p>
</li>
<li><p>The <strong>Homoskedasticity</strong> assumption states that the variance of all error terms is constant.</p>
</li>
<li><p>The <strong>No Perfect Multi-Collinearity</strong> assumption states that none of the independent variables is constant and there are no exact linear relationships between the independent variables.</p>
</li>
</ol>
<p>The Python code snippet you've shared performs Ordinary Least Squares (OLS) regression, which is a method used in statistics to estimate the relationship between independent variables and a dependent variable. This process involves calculating the best-fit line through the data points that minimizes the sum of the squared differences between the observed values and the values predicted by the model.</p>
<p>The code defines a function <code>runOLS(Y, X)</code> that takes in a dependent variable <code>Y</code> and an independent variable <code>X</code> and performs the following steps:</p>
<ol>
<li><p>Estimates the OLS coefficients (beta_hat) using the linear algebra solution to the least squares problem.</p>
</li>
<li><p>Makes predictions (<code>Y_hat</code>) using the estimated coefficients and calculates the residuals.</p>
</li>
<li><p>Computes the residual sum of squares (RSS), total sum of squares (TSS), mean squared error (MSE), root mean squared error (RMSE), and R-squared value, which are common metrics used to assess the fit of the model.</p>
</li>
<li><p>Calculates the standard error of the coefficient estimates, t-statistics, p-values, and confidence intervals for the estimated coefficients.</p>
</li>
</ol>
<p>These calculations are standard in regression analysis and are used to interpret and understand the strength and significance of the relationship between the variables. The result of this function includes the estimated coefficients and various statistics that help evaluate the model's performance.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">runOLS</span>(<span class="hljs-params">Y,X</span>):</span>

   <span class="hljs-comment"># OLS esyimation Y = Xb + e --&gt; beta_hat = (X'X)^-1(X'Y)</span>
   beta_hat = np.dot(np.linalg.inv(np.dot(np.transpose(X), X)), np.dot(np.transpose(X), Y))

   <span class="hljs-comment"># OLS prediction</span>
   Y_hat = np.dot(X,beta_hat)
   residuals = Y-Y_hat
   RSS = np.sum(np.square(residuals))
   sigma_squared_hat = RSS/(N<span class="hljs-number">-2</span>)
   TSS = np.sum(np.square(Y-np.repeat(Y.mean(),len(Y))))
   MSE = sigma_squared_hat
   RMSE = np.sqrt(MSE)
   R_squared = (TSS-RSS)/TSS

   <span class="hljs-comment"># Standard error of estimates:square root of estimate's variance</span>
   var_beta_hat = np.linalg.inv(np.dot(np.transpose(X),X))*sigma_squared_hat

   SE = []
   t_stats = []
   p_values = []
   CI_s = []

   <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(beta)):
       <span class="hljs-comment">#standard errors</span>
       SE_i = np.sqrt(var_beta_hat[i,i])
       SE.append(np.round(SE_i,<span class="hljs-number">3</span>))

        <span class="hljs-comment">#t-statistics</span>
        t_stat = np.round(beta_hat[i,<span class="hljs-number">0</span>]/SE_i,<span class="hljs-number">3</span>)
        t_stats.append(t_stat)

        <span class="hljs-comment">#p-value of t-stat p[|t_stat| &gt;= t-treshhold two sided] </span>
        p_value = t.sf(np.abs(t_stat),N<span class="hljs-number">-2</span>) * <span class="hljs-number">2</span>
        p_values.append(np.round(p_value,<span class="hljs-number">3</span>))

        <span class="hljs-comment">#Confidence intervals = beta_hat -+ margin_of_error</span>
        t_critical = t.ppf(q =<span class="hljs-number">1</span><span class="hljs-number">-0.05</span>/<span class="hljs-number">2</span>, df = N<span class="hljs-number">-2</span>)
        margin_of_error = t_critical*SE_i
        CI = [np.round(beta_hat[i,<span class="hljs-number">0</span>]-margin_of_error,<span class="hljs-number">3</span>), np.round(beta_hat[i,<span class="hljs-number">0</span>]+margin_of_error,<span class="hljs-number">3</span>)]
        CI_s.append(CI)
        <span class="hljs-keyword">return</span>(beta_hat, SE, t_stats, p_values,CI_s, 
               MSE, RMSE, R_squared)
</code></pre>
<h2 id="heading-parameter-properties">Parameter Properties</h2>
<p>Under the assumption that the OLS criteria/assumptions we just discussed are satisfied, the OLS estimators of coefficients β0 and β1 are <strong>BLUE</strong> and <strong>Consistent</strong>. So what does this mean?</p>
<h3 id="heading-gauss-markov-theorem">Gauss-Markov Theorem</h3>
<p>This theorem highlights the properties of OLS estimates where the term <strong>BLUE</strong> stands for <strong>Best Linear Unbiased Estimator</strong>. Let's explore what this means in more detail.</p>
<h4 id="heading-bias">Bias</h4>
<p>The <strong>bias</strong> of an estimator is the difference between its expected value and the true value of the parameter being estimated. It can be expressed as follows:</p>
<p>$$\text{Bias}(\beta, \hat{\beta}) = E(\hat{\beta}) - \beta$$</p><p>When we state that the estimator is <strong>unbiased</strong>, we mean that the bias is equal to zero. This implies that the expected value of the estimator is equal to the true parameter value, that is:</p>
<p>$$E(\hat{\beta}) = \beta$$</p><p>Unbiasedness does not guarantee that the obtained estimate with any particular sample is equal or close to β. What it means is that, if we <strong>repeatedly</strong> draw random samples from the population and then computes the estimate each time, then the average of these estimates would be equal or very close to β.</p>
<h4 id="heading-efficiency">Efficiency</h4>
<p>The term <strong>Best</strong> in the Gauss-Markov theorem relates to the variance of the estimator and is referred to as <strong>efficiency*</strong>.* A parameter can have multiple estimators but the one with the lowest variance is called efficient.</p>
<h4 id="heading-consistency">Consistency</h4>
<p>The term consistency goes hand in hand with the terms <strong>sample size</strong> and <strong>convergence</strong>. If the estimator converges to the true parameter as the sample size becomes very large, then this estimator is said to be consistent, that is:</p>
<p>$$N \to \infty \text{ then } \hat{\beta} \to \beta$$</p><p>All these properties hold for OLS estimates as summarized in the Gauss-Markov theorem. In other words, OLS estimates have the smallest variance, they are unbiased, linear in parameters, and are consistent. These properties can be mathematically proven by using the OLS assumptions made earlier.</p>
<h2 id="heading-confidence-intervals">Confidence Intervals</h2>
<p>The Confidence Interval is the range that contains the true population parameter with a certain pre-specified probability. This is referred to as the <strong>confidence level</strong> of the experiment, and it's obtained by using the sample results and the <strong>margin of error</strong>.</p>
<h3 id="heading-margin-of-error">Margin of Error</h3>
<p>The margin of error is the difference between the sample results and based on what the result would have been if you had used the entire population.</p>
<h3 id="heading-confidence-level">Confidence Level</h3>
<p>The Confidence Level describes the level of certainty in the experimental results. For example, a 95% confidence level means that if you were to perform the same experiment repeatedly 100 times, then 95 of those 100 trials would lead to similar results.</p>
<p>Note that the confidence level is defined before the start of the experiment because it will affect how big the margin of error will be at the end of the experiment.</p>
<h3 id="heading-confidence-interval-for-ols-estimates">Confidence Interval for OLS Estimates</h3>
<p>As I mentioned earlier, the OLS estimates of the Simple Linear Regression, the estimates for intercept β0 and slope coefficient β1, are subject to sampling uncertainty. But we can construct Confidence Intervals (CIs) for these parameters which will contain the true value of these parameters in 95% of all samples.</p>
<p>That is, 95% confidence interval for β can be interpreted as follows:</p>
<ul>
<li><p>The confidence interval is the set of values for which a hypothesis test cannot be rejected to the level of 5%.</p>
</li>
<li><p>The confidence interval has a 95% chance to contain the true value of β.</p>
</li>
</ul>
<p>95% confidence interval of OLS estimates can be constructed as follows:</p>
<p>$$CI_{0.95}^{\beta} = \left[\hat{\beta}_i - 1.96 , SE(\hat{\beta}_i), \hat{\beta}_i + 1.96 , SE(\hat{\beta}_i)\right]$$</p><p>This is based on the parameter estimate, the standard error of that estimate, and the value 1.96 representing the margin of error corresponding to the 5% rejection rule.</p>
<p>This value is determined using the <a target="_blank" href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Ffreakonometrics.hypotheses.org%2F9404&amp;psig=AOvVaw2IcJrhGrWbt9504WTCWBwW&amp;ust=1618940099743000&amp;source=images&amp;cd=vfe&amp;ved=0CAIQjRxqFwoTCOjR4v7rivACFQAAAAAdAAAAABAI">Normal Distribution table</a>, which we'll discuss later on in this handbook.</p>
<p>Meanwhile, the following figure illustrates the idea of 95% CI:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-XtBhY43apW_xIyf23eOWow.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Image Source:</em> <a target="_blank" href="https://lunartech.ai"><em>LunarTech</em></a></p>
<p>Note that the confidence interval depends on the sample size as well, given that it is calculated using the standard error which is based on sample size.</p>
<h2 id="heading-statistical-hypothesis-testing">Statistical Hypothesis Testing</h2>
<p>Testing a hypothesis in Statistics is a way to test the results of an experiment or survey to determine how meaningful they the results are.</p>
<p>Basically, you're testing whether the obtained results are valid by figuring out the odds that the results have occurred by chance. If it is the letter, then the results are not reliable and neither is the experiment. Hypothesis Testing is part of the <strong>Statistical Inference</strong>.</p>
<h3 id="heading-null-and-alternative-hypothesis">Null and Alternative Hypothesis</h3>
<p>Firstly, you need to determine the thesis you wish to test. Then you need to formulate the <strong>Null Hypothesis</strong> and the <strong>Alternative Hypothesis.</strong> The test can have two possible outcomes. Based on the statistical results, you can either reject the stated hypothesis or accept it.</p>
<p>As a rule of thumb, statisticians tend to put the version or formulation of the hypothesis under the Null Hypothesis that needs to be rejected_,_ whereas the acceptable and desired version is stated under the Alternative Hypothesis_._</p>
<h3 id="heading-statistical-significance">Statistical Significance</h3>
<p>Let’s look at the earlier mentioned example where we used the Linear Regression model to investigate whether a penguin's Flipper Length, the independent variable, has an impact on Body Mass_,_ the dependent variable.</p>
<p>We can formulate this model with the following statistical expression:</p>
<p>$$Y_{\text{BodyMass}} = \beta_0 + \beta_1X_{\text{FlipperLength}} + u_i$$</p><p>Then, once the OLS estimates of the coefficients are estimated, we can formulate the following Null and Alternative Hypothesis to test whether the Flipper Length has a <strong>statistically significant</strong> impact on the Body Mass:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-DVPqyel26EtGY__fwp_-rA.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>where H0 and H1 represent Null Hypothesis and Alternative Hypothesis, respectively.</p>
<p>Rejecting the Null Hypothesis would mean that a one-unit increase in Flipper Length has a direct impact on the Body Mass (given that the parameter estimate of β1 is describing this impact of the independent variable, Flipper Length, on the dependent variable, Body Mass). We can reformulate this hypothesis as follows:</p>
<p>$$\begin{cases} H_0: \hat{\beta}_1 = 0 \\ H_1: \hat{\beta}_1 \neq 0 \end{cases}$$</p><p>where H0 states that the parameter estimate of β1 is equal to 0, that is Flipper Length effect on Body Mass is <strong>statistically insignificant</strong> whereas H1 states that the parameter estimate of β1 is not equal to 0, suggesting that Flipper Length effect on Body Mass is <strong>statistically significant</strong>.</p>
<h3 id="heading-type-i-and-type-ii-errors">Type I and Type II Errors</h3>
<p>When performing Statistical Hypothesis Testing, you need to consider two conceptual types of errors: Type I error and Type II error.</p>
<p>Type I errors occur when the Null is incorrectly rejected, and Type II errors occur when the Null Hypothesis is incorrectly not rejected. A confusion <a target="_blank" href="https://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/">matrix</a> can help you clearly visualize the severity of these two types of errors.</p>
<p>As a rule of thumb, statisticians tend to put the version of the hypothesis under the Null Hypothesis that that needs to be rejected, whereas the acceptable and desired version is stated under the Alternative Hypothesis.</p>
<h2 id="heading-statistical-tests">Statistical Tests</h2>
<p>Once the you've stataed the Null and the Alternative Hypotheses and defined the test assumptions, the next step is to determine which statistical test is appropriate and to calculate the <strong>test statistic</strong>.</p>
<p>Whether or not to reject or not reject the Null can be determined by comparing the test statistic with the <strong>critical value</strong>. This comparison shows whether or not the observed test statistic is more extreme than the defined critical value.</p>
<p>It can have two possible results:</p>
<ul>
<li><p>The test statistic is more extreme than the critical value → the null hypothesis can be rejected</p>
</li>
<li><p>The test statistic is not as extreme as the critical value → the null hypothesis cannot be rejected</p>
</li>
</ul>
<p>The critical value is based on a pre-specified <strong>significance level α</strong> (usually chosen to be equal to 5%) and the type of probability distribution the test statistic follows.</p>
<p>The critical value divides the area under this probability distribution curve into the <strong>rejection region(s)</strong> and <strong>non-rejection region</strong>. There are numerous statistical tests used to test various hypotheses. Examples of Statistical tests are <a target="_blank" href="https://en.wikipedia.org/wiki/Student%27s_t-test">Student’s t-test</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/F-test">F-test</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Chi-squared_test">Chi-squared test</a>, <a target="_blank" href="https://www.stata.com/support/faqs/statistics/durbin-wu-hausman-test/">Durbin-Hausman-Wu Endogeneity test</a>, W<a target="_blank" href="https://en.wikipedia.org/wiki/White_test#:~:text=In%20statistics%2C%20the%20White%20test,by%20Halbert%20White%20in%201980.">hite Heteroskedasticity test</a>. In this handbook, we will look at two of these statistical tests: the Student's t-test and the F-test.</p>
<h3 id="heading-students-t-test">Student’s t-test</h3>
<p>One of the simplest and most popular statistical tests is the Student’s t-test. You can use it to test various hypotheses, especially when dealing with a hypothesis where the main area of interest is to find evidence for the statistically significant effect of a <strong>single variable</strong>.</p>
<p>The test statistics of the t-test follows <a target="_blank" href="https://en.wikipedia.org/wiki/Student%27s_t-distribution"><strong>Student’s t distribution</strong></a> and can be determined as follows:</p>
<p>$$T_{\text{stat}} = \frac{\hat{\beta}_i - h_0}{SE(\hat{\beta})}$$</p><p>where h0 in the nominator is the value against which the parameter estimate is being tested. So, the t-test statistics are equal to the parameter estimate minus the hypothesized value divided by the standard error of the coefficient estimate.</p>
<p>Let's use this for our earlier hypothesis, where we wanted to test whether Flipper Length has a statistically significant impact on Body Mass or not. This test can be performed using a t-test. The h0 is in that case equal to the 0 since the slope coefficient estimate is tested against a value of 0.</p>
<h4 id="heading-two-sided-vs-one-sided-t-test">Two-sided vs one-sided t-test</h4>
<p>There are two versions of the t-test: a <strong>two-sided t-test</strong> and a <strong>one-sided t-test</strong>. Whether you need the former or the latter version of the test depends entirely on the hypothesis that you want to test.</p>
<p>You can use the two-sided or <strong>two-tailed t-test</strong> when the hypothesis is testing <em>equal</em> versus <em>not equal</em> relationship under the Null and Alternative Hypotheses. It would be similar to the following example:</p>
<p>$$H_{0} = \beta_hat_1 = h_0\ H_{1} = \beta_hat_1 \neq h_0$$</p><p>The two-sided t-test has <strong>two rejection regions</strong> as visualized in the figure below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-otgnlBKy306KgrFUZxk0Og.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>_Image Source: [Hartmann, K., Krois, J., Waske, B. (2018): E-Learning Project SOGA: Statistics and Geospatial Data Analysis. Department of Earth Sciences, Freie Universitaet Berlin](https://www.geo.fu-berlin.de/en/v/soga/Basics-of-statistics/Hypothesis-Tests/Introduction-to-Hypothesis-Testing/Critical-Value-and-the-p-Value-Approach/index.html" data-href="https://www.geo.fu-berlin.de/en/v/soga/Basics-of-statistics/Hypothesis-Tests/Introduction-to-Hypothesis-Testing/Critical-Value-and-the-p-Value-Approach/index.html" class="markup--anchor markup--figure-anchor" rel="noopener" target="<em>blank"&gt;&lt;em class="markup--em markup--figure-em)</em></p>
<p>In this version of the t-test, the Null is rejected if the calculated t-statistics is either too small or too large.</p>
<p>$$T_{\text{stat}} &lt; -t_{\alpha,N} \text{ or } T_{\text{stat}} &gt; t_{\alpha,N}$$</p><p>$$|T_{\text{stat}}| &gt; t_{\alpha,N}$$</p><p>Here, the test statistics are compared to the critical values based on the sample size and the chosen significance level. To determine the exact value of the cutoff point, you can use a <a target="_blank" href="https://www.google.com/search?q=t-table+two+sided&amp;client=safari&amp;rls=en&amp;sxsrf=ALeKk01KSlU3EEtBeMcXPuh13ud42kRCWw:1618592162824&amp;tbm=isch&amp;source=iu&amp;ictx=1&amp;fir=ZGAb8l8KaBNJiM%252CZaqfSsY36WrUvM%252C_&amp;vet=1&amp;usg=AI4_-kSaUb_tv_3EBZQRhYaQVYYaJ1uBHQ&amp;sa=X&amp;ved=2ahUKEwjBtZrXnYPwAhWHgv0HHQPmASUQ9QF6BAgSEAE&amp;biw=1981&amp;bih=1044#imgrc=ZGAb8l8KaBNJiM">two-sided t-distribution table</a>.</p>
<p>On the other hand, you can use the one-sided or <strong>one-tailed t-test</strong> when the hypothesis is testing <em>positive/negative</em> versus <em>negative/positive</em> relationships under the Null and Alternative Hypotheses. It looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-uKChnDWApLtrCf8bq13o4w.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Left-tailed vs right-tailed</em></p>
<p>One-sided t-test has a <strong>single</strong> <strong>rejection region</strong>. Depending on the hypothesis side, the rejection region is either on the left-hand side or the right-hand side as visualized in the figure below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-SVKBOOFtXIvYwL2gC9XEoQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>_Image Source: [Hartmann, K., Krois, J., Waske, B. (2018): E-Learning Project SOGA: Statistics and Geospatial Data Analysis. Department of Earth Sciences, Freie Universitaet Berlin](https://www.geo.fu-berlin.de/en/v/soga/Basics-of-statistics/Hypothesis-Tests/Introduction-to-Hypothesis-Testing/Critical-Value-and-the-p-Value-Approach/index.html" data-href="https://www.geo.fu-berlin.de/en/v/soga/Basics-of-statistics/Hypothesis-Tests/Introduction-to-Hypothesis-Testing/Critical-Value-and-the-p-Value-Approach/index.html" class="markup--anchor markup--figure-anchor" rel="noopener" target="<em>blank"&gt;&lt;em class="markup--em markup--figure-em)</em></p>
<p>In this version of the t-test, the Null is rejected if the calculated t-statistics is smaller/larger than the critical value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-UvLof79AQigLFgxbKAvYgA.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-f-test">F-test</h3>
<p>F-test is another very popular statistical test often used to test hypotheses testing a <strong>joint statistical significance of multiple variables</strong>. This is the case when you want to test whether multiple independent variables have a statistically significant impact on a dependent variable.</p>
<p>Following is an example of a statistical hypothesis that you can test using the F-test:</p>
<p>$$\begin{cases} H_0: \hat{\beta}_1 = \hat{\beta}_2 = \hat{\beta}_3 = 0 \\ H_1: \hat{\beta}_1 \neq \hat{\beta}_2 \neq \hat{\beta}_3 \neq 0 \end{cases}$$</p><p>where the Null states that the three variables corresponding to these coefficients are jointly statistically insignificant, and the Alternative states that these three variables are jointly statistically significant.</p>
<p>The test statistics of the F-test follows <a target="_blank" href="https://en.wikipedia.org/wiki/F-distribution">F distribution</a> and can be determined as follows:</p>
<p>$$F_{\text{stat}} = \frac{(SSR_{\text{restricted}} - SSR_{\text{unrestricted}}) / q}{SSR_{\text{unrestricted}} / (N - k_{\text{unrestricted}} - 1)}$$</p><p>where :</p>
<ul>
<li><p>the SSRrestricted is the sum of squared residuals of the <strong>restricted model</strong>, which is the same model excluding from the data the target variables stated as insignificant under the Null</p>
</li>
<li><p>the SSRunrestricted is the sum of squared residuals of the <strong>unrestricted model</strong>, which is the model that includes all variables</p>
</li>
<li><p>the q represents the number of variables that are being jointly tested for the insignificance under the Null</p>
</li>
<li><p>N is the sample size</p>
</li>
<li><p>and the k is the total number of variables in the unrestricted model.</p>
</li>
</ul>
<p>SSR values are provided next to the parameter estimates after running the OLS regression, and the same holds for the F-statistics as well.</p>
<p>Following is an example of MLR model output where the SSR and F-statistics values are marked.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-5kTyYIc3LztrgM-oLKltwg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>_Image Source:[ Stock and Whatson](https://www.uio.no/studier/emner/sv/oekonomi/ECON4150/v18/lecture7_ols_multiple_regressors_hypothesis_tests.pdf" data-href="https://www.uio.no/studier/emner/sv/oekonomi/ECON4150/v18/lecture7_ols_multiple_regressors_hypothesis_tests.pdf" class="markup--anchor markup--figure-anchor" rel="noopener" target="<em>blank)</em></p>
<p>F-test has <strong>a single rejection region</strong> as visualized below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-U3c2dRBPYCqtDqNGvk1BKA.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>_Image Source: [U of Michigan](https://www.statisticshowto.com/probability-and-statistics/f-statistic-value-test/" data-href="https://www.statisticshowto.com/probability-and-statistics/f-statistic-value-test/" class="markup--anchor markup--figure-anchor" rel="noopener" target="<em>blank"&gt;&lt;em class="markup--em markup--figure-em)</em></p>
<p>If the calculated F-statistics is bigger than the critical value, then the Null can be rejected. This suggests that the independent variables are jointly statistically significant. The rejection rule can be expressed as follows:</p>
<p>$$F_{\text{stat}} &gt; F_{\alpha,q,N}$$</p><h2 id="heading-2-sample-t-test">2-sample T-test</h2>
<p>If you want to test whether there is a statistically significant difference between the control and experimental groups’ metrics that are in the form of averages (for example, average purchase amount), metric follows <em>student-t</em> distribution. When the sample size is smaller than 30, you can use 2-sample T-test to test the following hypothesis:</p>
<p>$$\begin{cases} H_0: \mu_{\text{con}} = \mu_{\text{exp}} \\ H_1: \mu_{\text{con}} \neq \mu_{\text{exp}} \end{cases}$$</p><p>$$\begin{cases} H_0: \mu_{\text{con}} - \mu_{\text{exp}} = 0 \\ H_1: \mu_{\text{con}} - \mu_{\text{exp}} \neq 0 \end{cases}$$</p><p>where the sampling distribution of means of Control group follows Student-t distribution with degrees of freedom N_con-1. Also, the sampling distribution of means of the Experimental group also follows the Student-t distribution with degrees of freedom N_exp-1.</p>
<p>Note that the N_con and N_exp are the number of users in the Control and Experimental groups, respectively.</p>
<p>$$\hat{\mu}{\text{con}} \sim t(N{\text{con}} - 1)$$</p><p>$$\hat{\mu}{\text{exp}} \sim t(N{\text{exp}} - 1)$$</p><p>Then you can calculate an estimate for the <strong>pooled variance</strong> of the two samples as follows:</p>
<p>$$S^2_{\text{pooled}} = \frac{(N_{\text{con}} - 1) * \sigma^2_{\text{con}} + (N_{\text{exp}} - 1) * \sigma^2_{\text{exp}}}{N_{\text{con}} + N_{\text{exp}} - 2} * \left(\frac{1}{N_{\text{con}}} + \frac{1}{N_{\text{exp}}}\right)$$</p><p>where σ²_con and σ²_exp are the sample variances of the Control and Experimental groups, respectively. Then the <strong>Standard Error</strong> is equal to the square root of the estimate of the pooled variance, and can be defined as:</p>
<p>$$SE = \sqrt{\hat{S}^2_{\text{pooled}}}$$</p><p>Consequently, the <strong>test statistics</strong> of the 2-sample T-test with the hypothesis stated earlier can be calculated as follows:</p>
<p>$$T = \frac{\hat{\mu}{\text{con}} - \hat{\mu}{\text{exp}}}{\sqrt{\hat{S}^2_{\text{pooled}}}}$$</p><p>In order to test the <strong>statistical significance</strong> of the observed difference between sample means, we need to calculate the <strong>p-value</strong> of our test statistics.</p>
<p>The p-value is the probability of observing values at least as extreme as the common value when this is due to a random chance. Stated differently, the p-value is the probability of obtaining an effect at least as extreme as the one in your sample data, assuming the null hypothesis is true.</p>
<p>Then the p-value of the test statistics can be calculated as follows:</p>
<p>$$p_{\text{value}} = \Pr[t \leq -T \text{ or } t \geq T]$$</p><p>$$= 2 * \Pr[t \geq T]$$</p><p>The interpretation of a <em>p</em>-value is dependent on the chosen significance level, alpha, which you choose before running the test during the <em>power analysis</em>.</p>
<p>If the calculated <em>p</em>-value appears to be smaller than equal to alpha (for example, 0.05 for 5% significance level) we can reject the null hypothesis and state that there is a statistically significant difference between the primary metrics of the Control and Experimental groups.</p>
<p>Finally, to determine how accurate the obtained results are and also to comment about the practical significance of the obtained results, you can compute the <strong>Confidence Interval</strong> of your test by using the following formula:</p>
<p>$$CI = \left[ (\hat{\mu}{\text{con}} - \hat{\mu}{\text{exp}}) - t_{\frac{\alpha}{2}} * SE(\hat{\mu}{\text{con}} - \hat{\mu}{\text{exp}}), (\hat{\mu}{\text{con}} - \hat{\mu}{\text{exp}}) + t_{\frac{\alpha}{2}} * SE \right]$$</p><p>where the t_(1-alpha/2) is the critical value of the test corresponding to the two-sided t-test with alpha significance level. It can be found using the <a target="_blank" href="https://www.sjsu.edu/faculty/gerstman/StatPrimer/t-table.pdf">t-table</a>.</p>
<p>The Python code provided performs a two-sample t-test, which is used in statistics to determine if two sets of data are significantly different from each other. This particular snippet simulates two groups (control and experimental) with data following a t-distribution, calculates the mean and variance for each group, and then performs the following steps:</p>
<ol>
<li><p>It calculates the pooled variance, which is a weighted average of the variances of the two groups.</p>
</li>
<li><p>It computes the standard error of the difference between the two means.</p>
</li>
<li><p>It calculates the t-statistic, which is the difference between the two sample means divided by the standard error. This statistic measures how much the groups differ in units of standard error.</p>
</li>
<li><p>It determines the critical t-value from the t-distribution for the given significance level and degrees of freedom, which is used to decide whether the t-statistic is large enough to indicate a statistically significant difference between the groups.</p>
</li>
<li><p>It calculates the p-value, which indicates the probability of observing such a difference between means if the null hypothesis (that there is no difference) is true.</p>
</li>
<li><p>It computes the margin of error and constructs the confidence interval around the difference in means.</p>
</li>
</ol>
<p>Finally, the code prints out the t-statistic, critical t-value, p-value, and confidence interval. These results can be used to infer whether the observed differences in means are statistically significant or likely due to random variation.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> scipy.stats <span class="hljs-keyword">import</span> t

N_con = <span class="hljs-number">20</span>
df_con = N_con - <span class="hljs-number">1</span> <span class="hljs-comment"># degrees of freedom of Control </span>
N_exp = <span class="hljs-number">20</span>
df_exp = N_exp - <span class="hljs-number">1</span> <span class="hljs-comment"># degrees of freedom of Experimental </span>

<span class="hljs-comment"># Significance level</span>
alpha = <span class="hljs-number">0.05</span>

<span class="hljs-comment"># data of control group with t-distribution</span>
X_con = np.random.standard_t(df_con,N_con)
<span class="hljs-comment"># data of experimental group with t-distribution</span>
X_exp = np.random.standard_t(df_exp,N_exp)

<span class="hljs-comment"># mean of control</span>
mu_con = np.mean(X_con)
<span class="hljs-comment"># mean of experimental</span>
mu_exp = np.mean(X_exp)

<span class="hljs-comment"># variance of control</span>
sigma_sqr_con = np.var(X_con)
<span class="hljs-comment">#variance of control</span>
sigma_sqr_exp = np.var(X_exp)

<span class="hljs-comment"># pooled variance</span>
pooled_variance_t_test = ((N_con<span class="hljs-number">-1</span>)*sigma_sqr_con + (N_exp <span class="hljs-number">-1</span>) * sigma_sqr_exp)/(N_con + N_exp<span class="hljs-number">-2</span>)*(<span class="hljs-number">1</span>/N_con + <span class="hljs-number">1</span>/N_exp)

<span class="hljs-comment"># Standard Error</span>
SE = np.sqrt(pooled_variance_t_test)

<span class="hljs-comment"># Test Statistics</span>
T = (mu_con-mu_exp)/SE

<span class="hljs-comment"># Critical value for two sided 2 sample t-test</span>
t_crit = t.ppf(<span class="hljs-number">1</span>-alpha/<span class="hljs-number">2</span>, N_con + N_exp - <span class="hljs-number">2</span>)

<span class="hljs-comment"># P-value of the two sided T-test using t-distribution and its symmetric property</span>
p_value = t.sf(T, N_con + N_exp - <span class="hljs-number">2</span>)*<span class="hljs-number">2</span>

<span class="hljs-comment"># Margin of Error</span>
margin_error = t_crit * SE
<span class="hljs-comment"># Confidence Interval</span>
CI = [(mu_con-mu_exp) - margin_error, (mu_con-mu_exp) + margin_error]

print(<span class="hljs-string">"T-score: "</span>, T)
print(<span class="hljs-string">"T-critical: "</span>, t_crit)
print(<span class="hljs-string">"P_value: "</span>, p_value)
print(<span class="hljs-string">"Confidence Interval of 2 sample T-test: "</span>, np.round(CI,<span class="hljs-number">2</span>))
</code></pre>
<h2 id="heading-2-sample-z-test">2-sample Z-test</h2>
<p>There are various situations when you may want to use a 2-sample z-test:</p>
<ul>
<li><p>if you want to test whether there is a statistically significant difference between the control and experimental groups’ metrics that are in the form of averages (for example, average purchase amount) or proportions (for example, Click Through Rate)</p>
</li>
<li><p>if the metric follows <em>Normal</em> distribution</p>
</li>
<li><p>when the sample size is larger than 30, such that you can use the Central Limit Theorem (CLT) to state that the sampling distributions of the Control and Experimental groups are asymptotically Normal</p>
</li>
</ul>
<p>Here we will make a distinction between two cases: where the primary metric is in the form of proportions (like Click Through Rate) and where the primary metric is in the form of averages (like average purchase amount).</p>
<h3 id="heading-case-1-z-test-for-comparing-proportions-2-sided">Case 1: Z-test for comparing proportions (2-sided)</h3>
<p>If you want to test whether there is a statistically significant difference between the Control and Experimental groups’ metrics that are in the form of proportions (like CTR) and if the click event occurs independently, you can use a 2-sample Z-test to test the following hypothesis:</p>
<p>$$\begin{cases} H_0: p_{\text{con}} = p_{\text{exp}} \\ H_1: p_{\text{con}} \neq p_{\text{exp}} \end{cases}$$</p><p>$$\begin{cases} H_0: p_{\text{con}} - p_{\text{exp}} = 0 \\ H_1: p_{\text{con}} - p_{\text{exp}} \neq 0 \end{cases}$$</p><p>where each click event can be described by a random variable that can take two possible values: 1 (success) and 0 (failure). It also follows a Bernoulli distribution (click: success and no click: failure) where p_con and p_exp are the probabilities of clicking (probability of success) of Control and Experimental groups, respectively.</p>
<p>So, after collecting the interaction data of the Control and Experimental users, you can calculate the estimates of these two probabilities as follows:</p>
<p>$$SE = \sqrt{\hat{S}^2_{\text{pooled}}}$$</p><p>$$Z = \frac{(\hat{p}{\text{con}} - \hat{p}{\text{exp}})}{SE}$$</p><p>Since we are testing for the difference in these probabilities, we need to obtain an estimate for the pooled probability of success and an estimate for pooled variance, which can be done as follows:</p>
<p>$$\hat{p}{\text{pooled}} = \frac{X{\text{con}} + X_{\text{exp}}}{N_{\text{con}} + N_{\text{exp}}} = \frac{\#\text{clicks}{\text{con}} + \#\text{clicks}{\text{exp}}}{\#\text{impressions}{\text{con}} + \#\text{impressions}{\text{exp}}}$$</p><p>$$\hat{S}^2_{\text{pooled}} = \hat{p}{\text{pooled}}(1 - \hat{p}{\text{pooled}}) * \left(\frac{1}{N_{\text{con}}} + \frac{1}{N_{\text{exp}}}\right)$$</p><p>Then the <strong>Standard Error</strong> is equal to the square root of the estimate of the pooled variance. It can be defined as:</p>
<p>$$SE = \sqrt{\hat{S}^2_{\text{pooled}}}$$</p><p>And so, the <strong>test statistics</strong> of the 2-sample Z-test for the difference in proportions can be calculated as follows:</p>
<p>$$Z = \frac{(\hat{p}{\text{con}} - \hat{p}{\text{exp}})}{SE}$$</p><p>Then the p-value of this test statistics can be calculated as follows:</p>
<p>$$p_{\text{value}} = \Pr[Z \leq -T \text{ or } z \geq T]$$</p><p>$$= 2 * \Pr[Z \geq T]$$</p><p>Finally, you can compute the <strong>Confidence Interval</strong> of the test as follows:</p>
<p>$$CI = \left[ (\hat{p}{\text{con}} - \hat{p}{\text{exp}}) - z_{\frac{\alpha}{2}} * SE, (\hat{p}{\text{con}} - \hat{p}{\text{exp}}) + z_{\frac{\alpha}{2}} * SE \right]$$</p><p>where the z_(1-alpha/2) is the critical value of the test corresponding to the two-sided Z-test with alpha significance level. You can find it using the <a target="_blank" href="http://www.z-table.com/">Z-table</a>.</p>
<p>The rejection region of this two-sided 2-sample Z-test can be visualized by the following graph:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-hHddr3psz2Zxy-hzbLVVwA.png" alt="Image Source: LunarTech" width="600" height="400" loading="lazy"></p>
<p><em>Image Source: The Author</em></p>
<p>The Python code snippet you’ve provided performs a two-sample Z-test for proportions. This type of test is used to determine whether there is a significant difference between the proportions of two groups. Here’s a brief explanation of the steps the code performs:</p>
<ol>
<li><p>Calculates the sample proportions for both the control and experimental groups.</p>
</li>
<li><p>Computes the pooled sample proportion, which is an estimate of the proportion assuming the null hypothesis (that there is no difference between the group proportions) is true.</p>
</li>
<li><p>Calculates the pooled sample variance based on the pooled proportion and the sizes of the two samples.</p>
</li>
<li><p>Derives the standard error of the difference in sample proportions.</p>
</li>
<li><p>Calculates the Z-test statistic, which measures the number of standard errors between the sample proportion difference and the null hypothesis.</p>
</li>
<li><p>Finds the critical Z-value from the standard normal distribution for the given significance level.</p>
</li>
<li><p>Computes the p-value to assess the evidence against the null hypothesis.</p>
</li>
<li><p>Calculates the margin of error and the confidence interval for the difference in proportions.</p>
</li>
<li><p>Outputs the test statistic, critical value, p-value, and confidence interval, and based on the test statistic and critical value, it may print a statement to either reject or not reject the null hypothesis.</p>
</li>
</ol>
<p>The latter part of the code uses Matplotlib to create a visualization of the standard normal distribution and the rejection regions for the two-sided Z-test. This visual aid helps to understand where the test statistic falls in relation to the distribution and the critical values.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">import</span> <span class="hljs-selector-tag">numpy</span> <span class="hljs-selector-tag">as</span> <span class="hljs-selector-tag">np</span>
<span class="hljs-selector-tag">from</span> <span class="hljs-selector-tag">scipy</span><span class="hljs-selector-class">.stats</span> <span class="hljs-selector-tag">import</span> <span class="hljs-selector-tag">norm</span>

<span class="hljs-selector-tag">X_con</span> = 1242 <span class="hljs-selector-id">#clicks</span> <span class="hljs-selector-tag">control</span>
<span class="hljs-selector-tag">N_con</span> = 9886 <span class="hljs-selector-id">#impressions</span> <span class="hljs-selector-tag">control</span>
<span class="hljs-selector-tag">X_exp</span> = 974 <span class="hljs-selector-id">#clicks</span> <span class="hljs-selector-tag">experimental</span>
<span class="hljs-selector-tag">N_exp</span> = 10072 <span class="hljs-selector-id">#impressions</span> <span class="hljs-selector-tag">experimetal</span>

# <span class="hljs-selector-tag">Significance</span> <span class="hljs-selector-tag">Level</span>
<span class="hljs-selector-tag">alpha</span> = 0<span class="hljs-selector-class">.05</span>

<span class="hljs-selector-tag">p_con_hat</span> = <span class="hljs-selector-tag">X_con</span> / <span class="hljs-selector-tag">N_con</span>
<span class="hljs-selector-tag">p_exp_hat</span> = <span class="hljs-selector-tag">X_exp</span> / <span class="hljs-selector-tag">N_exp</span>

<span class="hljs-selector-tag">p_pooled_hat</span> = (<span class="hljs-selector-tag">X_con</span> + <span class="hljs-selector-tag">X_exp</span>)/(<span class="hljs-selector-tag">N_con</span> + <span class="hljs-selector-tag">N_exp</span>)
<span class="hljs-selector-tag">pooled_variance</span> = <span class="hljs-selector-tag">p_pooled_hat</span>*(1<span class="hljs-selector-tag">-p_pooled_hat</span>) * (1/<span class="hljs-selector-tag">N_con</span> + 1/<span class="hljs-selector-tag">N_exp</span>)

# <span class="hljs-selector-tag">Standard</span> <span class="hljs-selector-tag">Error</span>
<span class="hljs-selector-tag">SE</span> = <span class="hljs-selector-tag">np</span><span class="hljs-selector-class">.sqrt</span>(<span class="hljs-selector-tag">pooled_variance</span>)

# <span class="hljs-selector-tag">test</span> <span class="hljs-selector-tag">statsitics</span>
<span class="hljs-selector-tag">Test_stat</span> = (<span class="hljs-selector-tag">p_con_hat</span> <span class="hljs-selector-tag">-</span> <span class="hljs-selector-tag">p_exp_hat</span>)/<span class="hljs-selector-tag">SE</span>
# <span class="hljs-selector-tag">critical</span> <span class="hljs-selector-tag">value</span> <span class="hljs-selector-tag">usig</span> <span class="hljs-selector-tag">the</span> <span class="hljs-selector-tag">standard</span> <span class="hljs-selector-tag">normal</span> <span class="hljs-selector-tag">distribution</span>
<span class="hljs-selector-tag">Z_crit</span> = <span class="hljs-selector-tag">norm</span><span class="hljs-selector-class">.ppf</span>(1<span class="hljs-selector-tag">-alpha</span>/2)

# <span class="hljs-selector-tag">Margin</span> <span class="hljs-selector-tag">of</span> <span class="hljs-selector-tag">error</span>
<span class="hljs-selector-tag">m</span> = <span class="hljs-selector-tag">SE</span> * <span class="hljs-selector-tag">Z_crit</span>
# <span class="hljs-selector-tag">two</span> <span class="hljs-selector-tag">sided</span> <span class="hljs-selector-tag">test</span> <span class="hljs-selector-tag">and</span> <span class="hljs-selector-tag">using</span> <span class="hljs-selector-tag">symmetry</span> <span class="hljs-selector-tag">property</span> <span class="hljs-selector-tag">of</span> <span class="hljs-selector-tag">Normal</span> <span class="hljs-selector-tag">distibution</span> <span class="hljs-selector-tag">so</span> <span class="hljs-selector-tag">we</span> <span class="hljs-selector-tag">multiple</span> <span class="hljs-selector-tag">with</span> 2
<span class="hljs-selector-tag">p_value</span> = <span class="hljs-selector-tag">norm</span><span class="hljs-selector-class">.sf</span>(<span class="hljs-selector-tag">Test_stat</span>)*2

# <span class="hljs-selector-tag">Confidence</span> <span class="hljs-selector-tag">Interval</span>
<span class="hljs-selector-tag">CI</span> = <span class="hljs-selector-attr">[(p_con_hat-p_exp_hat) - SE * Z_crit, (p_con_hat-p_exp_hat) + SE * Z_crit]</span>

<span class="hljs-selector-tag">if</span> <span class="hljs-selector-tag">np</span><span class="hljs-selector-class">.abs</span>(<span class="hljs-selector-tag">Test_stat</span>) &gt;= <span class="hljs-selector-tag">Z_crit</span>:
    <span class="hljs-selector-tag">print</span>("<span class="hljs-selector-tag">reject</span> <span class="hljs-selector-tag">the</span> <span class="hljs-selector-tag">null</span>")
    <span class="hljs-selector-tag">print</span>(<span class="hljs-selector-tag">p_value</span>)

<span class="hljs-selector-tag">print</span>("<span class="hljs-selector-tag">Test</span> <span class="hljs-selector-tag">Statistics</span> <span class="hljs-selector-tag">stat</span>: ", <span class="hljs-selector-tag">Test_stat</span>)
<span class="hljs-selector-tag">print</span>("<span class="hljs-selector-tag">Z-critical</span>: ", <span class="hljs-selector-tag">Z_crit</span>)
<span class="hljs-selector-tag">print</span>("<span class="hljs-selector-tag">P_value</span>: ", <span class="hljs-selector-tag">p_value</span>)
<span class="hljs-selector-tag">print</span>("<span class="hljs-selector-tag">Confidence</span> <span class="hljs-selector-tag">Interval</span> <span class="hljs-selector-tag">of</span> 2 <span class="hljs-selector-tag">sample</span> <span class="hljs-selector-tag">Z-test</span> <span class="hljs-selector-tag">for</span> <span class="hljs-selector-tag">proportions</span>: ", <span class="hljs-selector-tag">np</span><span class="hljs-selector-class">.round</span>(<span class="hljs-selector-tag">CI</span>,2))

<span class="hljs-selector-tag">import</span> <span class="hljs-selector-tag">matplotlib</span><span class="hljs-selector-class">.pyplot</span> <span class="hljs-selector-tag">as</span> <span class="hljs-selector-tag">plt</span>
<span class="hljs-selector-tag">z</span> = <span class="hljs-selector-tag">np</span><span class="hljs-selector-class">.arange</span>(<span class="hljs-selector-tag">-3</span>,3,  0<span class="hljs-selector-class">.1</span>)
<span class="hljs-selector-tag">plt</span><span class="hljs-selector-class">.plot</span>(<span class="hljs-selector-tag">z</span>, <span class="hljs-selector-tag">norm</span><span class="hljs-selector-class">.pdf</span>(<span class="hljs-selector-tag">z</span>), <span class="hljs-selector-tag">label</span> = '<span class="hljs-selector-tag">Standard</span> <span class="hljs-selector-tag">Normal</span> <span class="hljs-selector-tag">Distribution</span>',<span class="hljs-selector-tag">color</span> = '<span class="hljs-selector-tag">purple</span>',<span class="hljs-selector-tag">linewidth</span> = 2<span class="hljs-selector-class">.5</span>)
<span class="hljs-selector-tag">plt</span><span class="hljs-selector-class">.fill_between</span>(<span class="hljs-selector-tag">z</span><span class="hljs-selector-attr">[z&gt;Z_crit]</span>, <span class="hljs-selector-tag">norm</span><span class="hljs-selector-class">.pdf</span>(<span class="hljs-selector-tag">z</span><span class="hljs-selector-attr">[z&gt;Z_crit]</span>), <span class="hljs-selector-tag">label</span> = '<span class="hljs-selector-tag">Right</span> <span class="hljs-selector-tag">Rejection</span> <span class="hljs-selector-tag">Region</span>',<span class="hljs-selector-tag">color</span> ='<span class="hljs-selector-tag">y</span>' )
<span class="hljs-selector-tag">plt</span><span class="hljs-selector-class">.fill_between</span>(<span class="hljs-selector-tag">z</span><span class="hljs-selector-attr">[z&lt;(-1)*Z_crit]</span>, <span class="hljs-selector-tag">norm</span><span class="hljs-selector-class">.pdf</span>(<span class="hljs-selector-tag">z</span><span class="hljs-selector-attr">[z&lt;(-1)*Z_crit]</span>), <span class="hljs-selector-tag">label</span> = '<span class="hljs-selector-tag">Left</span> <span class="hljs-selector-tag">Rejection</span> <span class="hljs-selector-tag">Region</span>',<span class="hljs-selector-tag">color</span> ='<span class="hljs-selector-tag">y</span>' )
<span class="hljs-selector-tag">plt</span><span class="hljs-selector-class">.title</span>("<span class="hljs-selector-tag">Two</span> <span class="hljs-selector-tag">Sample</span> <span class="hljs-selector-tag">Z-test</span> <span class="hljs-selector-tag">rejection</span> <span class="hljs-selector-tag">region</span>")
<span class="hljs-selector-tag">plt</span><span class="hljs-selector-class">.legend</span>()
<span class="hljs-selector-tag">plt</span><span class="hljs-selector-class">.show</span>()
</code></pre>
<h3 id="heading-case-2-z-test-for-comparing-means-2-sided">Case 2: Z-test for Comparing Means (2-sided)</h3>
<p>If you want to test whether there is a statistically significant difference between the Control and Experimental groups’ metrics that are in the form of averages (like average purchase amount) you can use a 2-sample Z-test to test the following hypothesis:</p>
<p>$$\begin{cases} H_0: {CR}{\text{con}} = {CR}{\text{exp}} \\ H_1:{CR}{\text{con}} \neq {CR}{\text{exp}} \end{cases}$$</p><p>$$\begin{cases} H_0: {CR}{\text{con}} - {CR}{\text{exp}} = 0 \\ H_1: {CR}{\text{con}} - {CR}{\text{exp}} \neq 0 \end{cases}$$</p><p>where the sampling distribution of means of the Control group follows Normal distribution with mean mu_con and σ²_con/N_con. Moreover, the sampling distribution of means of the Experimental group also follows the Normal distribution with mean mu_exp and σ²_exp/N_exp.</p>
<p>$$\hat{\mu}{\text{con}} \sim N(\mu{con}, \frac{\sigma^2_{con}}{N_{con}})$$</p><p>$$\hat{\mu}{\text{exp}} \sim N(\mu{exp}, \frac{\sigma^{exp}2}{N{exp}})$$</p><p>Then the difference in the means of the control and experimental groups also follows Normal distributions with mean mu_con-mu_exp and variance σ²_con/N_con + σ²_exp/N_exp.</p>
<p>$$\hat{\mu}{\text{con}}-\hat{\mu}{\text{exp}} \sim N(\mu_{con}-\mu_{exp}, \frac{\sigma^2_{con}}{N_{con}}+\frac{\sigma^2_{exp}}{N_{exp}})$$</p><p>Consequently, the <strong>test statistics</strong> of the 2-sample Z-test for the difference in means can be calculated as follows:</p>
<p>$$T = \frac{\hat{\mu}{\text{con}}-\hat{\mu}{\text{exp}}}{\sqrt{\frac{\sigma^2_{con}}{N_{con}} + \frac{\sigma^2_{exp}}{N_{exp}}}} \sim N(0,1)$$</p><p>The <strong>Standard Error</strong> is equal to the square root of the estimate of the pooled variance and can be defined as:</p>
<p>$$SE = \sqrt{\frac{\sigma^2_{con}}{N_{con}} + \frac{\sigma^2_{exp}}{N_{exp}}}}$$</p><p>Then the p-value of this test statistics can be calculated as follows:</p>
<p>$$p_{\text{value}} = \Pr[Z \leq -T \text{ or } Z \geq T]$$</p><p>$$= 2 * \Pr[Z \geq T]$$</p><p>Finally, you can compute the <strong>Confidence Interval</strong> of the test as follows:</p>
<p>$$CI = [(\mu_hat_{con} - \mu_hat_{exp}) - z_{1-\alpha/2}*SE,((\mu_hat_{con} - \mu_hat_{exp}) + z_{1-\alpha/2)*SE]$$</p><p>The Python code provided appears to be set up for conducting a two-sample Z-test, typically used to determine if there is a significant difference between the means of two independent groups. In this context, the code might be comparing two different processes or treatments.</p>
<ol>
<li><p>It generates two arrays of random integers to represent data for a control group (<code>X_A</code>) and an experimental group (<code>X_B</code>).</p>
</li>
<li><p>It calculates the sample means (<code>mu_con</code>, <code>mu_exp</code>) and variances (<code>variance_con</code>, <code>variance_exp</code>) for both groups.</p>
</li>
<li><p>The pooled variance is computed, which is used in the denominator of the test statistic formula for the Z-test, providing a measure of the data's common variance.</p>
</li>
<li><p>The Z-test statistic (<code>T</code>) is calculated by taking the difference between the two sample means and dividing it by the standard error of the difference.</p>
</li>
<li><p>The p-value is calculated to test the hypothesis of whether the means of the two groups are statistically different from each other.</p>
</li>
<li><p>The critical Z-value (<code>Z_crit</code>) is determined from the standard normal distribution, which defines the cutoff points for significance.</p>
</li>
<li><p>A margin of error is computed, and a confidence interval for the difference in means is constructed.</p>
</li>
<li><p>The test statistic, critical value, p-value, and confidence interval are printed to the console.</p>
</li>
</ol>
<p>Lastly, the code uses Matplotlib to plot the standard normal distribution and highlight the rejection regions for the Z-test. This visualization can help in understanding the result of the Z-test in terms of where the test statistic lies relative to the distribution and the critical values for a two-sided test.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> scipy.stats <span class="hljs-keyword">import</span> norm

N_con = <span class="hljs-number">60</span>
N_exp = <span class="hljs-number">60</span>

<span class="hljs-comment"># Significance Level</span>
alpha = <span class="hljs-number">0.05</span>

X_A = np.random.randint(<span class="hljs-number">100</span>, size = N_con)
X_B = np.random.randint(<span class="hljs-number">100</span>, size = N_exp)

<span class="hljs-comment"># Calculating means of control and experimental groups</span>
mu_con = np.mean(X_A)
mu_exp = np.mean(X_B)

variance_con = np.var(X_A)
variance_exp = np.var(X_B)

<span class="hljs-comment"># Pooled Variance</span>
pooled_variance = np.sqrt(variance_con/N_con + variance_exp/N_exp)

<span class="hljs-comment"># Test statistics</span>
T = (mu_con-mu_exp)/np.sqrt(variance_con/N_con + variance_exp/N_exp)

<span class="hljs-comment"># two sided test and using symmetry property of Normal distibution so we multiple with 2</span>
p_value = norm.sf(T)*<span class="hljs-number">2</span>

<span class="hljs-comment"># Z-critical value</span>
Z_crit  = norm.ppf(<span class="hljs-number">1</span>-alpha/<span class="hljs-number">2</span>)

<span class="hljs-comment"># Margin of error</span>
m = Z_crit*pooled_variance

<span class="hljs-comment"># Confidence Interval</span>
CI = [(mu_con - mu_exp) - m, (mu_con - mu_exp) + m]


print(<span class="hljs-string">"Test Statistics stat: "</span>, T)
print(<span class="hljs-string">"Z-critical: "</span>, Z_crit)
print(<span class="hljs-string">"P_value: "</span>, p_value)
print(<span class="hljs-string">"Confidence Interval of 2 sample Z-test for proportions: "</span>, np.round(CI,<span class="hljs-number">2</span>))

<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
z = np.arange(<span class="hljs-number">-3</span>,<span class="hljs-number">3</span>,  <span class="hljs-number">0.1</span>)
plt.plot(z, norm.pdf(z), label = <span class="hljs-string">'Standard Normal Distribution'</span>,color = <span class="hljs-string">'purple'</span>,linewidth = <span class="hljs-number">2.5</span>)
plt.fill_between(z[z&gt;Z_crit], norm.pdf(z[z&gt;Z_crit]), label = <span class="hljs-string">'Right Rejection Region'</span>,color =<span class="hljs-string">'y'</span> )
plt.fill_between(z[z&lt;(<span class="hljs-number">-1</span>)*Z_crit], norm.pdf(z[z&lt;(<span class="hljs-number">-1</span>)*Z_crit]), label = <span class="hljs-string">'Left Rejection Region'</span>,color =<span class="hljs-string">'y'</span> )
plt.title(<span class="hljs-string">"Two Sample Z-test rejection region"</span>)
plt.legend()
plt.show()
</code></pre>
<h3 id="heading-chi-squared-test">Chi-Squared test</h3>
<p>If you want to test whether there is a statistically significant difference between the Control and Experimental groups’ performance metrics (for example their conversions) and you don’t really want to know the nature of this relationship (which one is better) you can use a Chi-Squared test to test the following hypothesis:</p>
<p>$$\begin{cases} H_0: \CR_{\text{con}} = \CR_{\text{exp}} \\ H_1: \CR_{\text{con}} \neq \CR_{\text{exp}} \end{cases}$$</p><p>$$\begin{cases} H_0: \CR_{\text{con}} - \CR_{\text{exp}} = 0 \\ H_1: \CR_{\text{con}} - \CR_{\text{exp}} \neq 0 \end{cases}$$</p><p>Note that the metric should be in the form of a binary variable (for example, conversion or no conversion/click or no click). The data can then be represented in the form of the following table, where O and T correspond to observed and theoretical values, respectively.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-1RVqOq4mc4-oach5QHCy5g.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Table showing the data from Chi-Squared test</em></p>
<p>Then the test statistics of the Chi-2 test can be expressed as follows:</p>
<p>$$T = \sum_{i} \frac{(Observed_i - Expected_i)^2}{Expected_i}$$</p><p>where the <em>Observed</em> corresponds to the observed data and the <em>Expected</em> corresponds to the theoretical value, and i can take values 0 (no conversion) and 1(conversion). It’s important to see that each of these factors has a separate denominator. The formula for the test statistics when you have two groups only can be represented as follows:</p>
<p>$$T = \frac{(Observed_{con,1} - T_{con,1})^2}{T_{con,1}} + \frac{(Observed_{con,0} - T_{con,0})^2}{T_{con,0}} + \frac{(Observed_{exp,1} - T_{exp,1})^2}{T_{exp,1}} + \frac{(Observed_{exp,0} - T_{exp,0})^2}{T_{exp,0}}$$</p><p>The expected value is simply equal to the number of times each version of the product is viewed multiplied by the probability of it leading to conversion (or to a click in case of CTR).</p>
<p>Note that, since the Chi-2 test is not a parametric test, its Standard Error and Confidence Interval can’t be calculated in a standard way as we did in the parametric Z-test or T-test.</p>
<p>The rejection region of this two-sided 2-sample Z-test can be visualized by the following graph:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-t8GYhf7iX1NJ2wNA8bHQ_A.png" alt="Image Source: LunarTech" width="600" height="400" loading="lazy"></p>
<p><em>Image Source: The Author</em></p>
<p>The Python code you've shared is for conducting a Chi-squared test, a statistical hypothesis test that is used to determine whether there is a significant difference between the expected frequencies and the observed frequencies in one or more categories.</p>
<p>In the provided code snippet, it looks like the test is being used to compare two categorical datasets:</p>
<ol>
<li><p>It calculates the Chi-squared test statistic by summing the squared difference between observed (<code>O</code>) and expected (<code>T</code>) frequencies, divided by the expected frequencies for each category. This is known as the squared relative distance and is used as the test statistic for the Chi-squared test.</p>
</li>
<li><p>It then calculates the p-value for this test statistic using the degrees of freedom, which in this case is assumed to be 1 (but this would typically depend on the number of categories minus one).</p>
</li>
<li><p>The Matplotlib library is used to plot the probability density function (pdf) of the Chi-squared distribution with one degree of freedom. It also highlights the rejection region for the test, which corresponds to the critical value of the Chi-squared distribution that the test statistic must exceed for the difference to be considered statistically significant.</p>
</li>
</ol>
<p>The visualization helps to understand the Chi-squared test by showing where the test statistic lies in relation to the Chi-squared distribution and its critical value. If the test statistic is within the rejection region, the null hypothesis of no difference in frequencies can be rejected.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">from</span> scipy.stats <span class="hljs-keyword">import</span> chi2

O = np.array([<span class="hljs-number">86</span>, <span class="hljs-number">83</span>, <span class="hljs-number">5810</span>,<span class="hljs-number">3920</span>])
T = np.array([<span class="hljs-number">105</span>,<span class="hljs-number">65</span>,<span class="hljs-number">5781</span>, <span class="hljs-number">3841</span>])

<span class="hljs-comment"># Squared_relative_distance</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">calculate_D</span>(<span class="hljs-params">O,T</span>):</span>
    D_sum = <span class="hljs-number">0</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(len(O)):
        D_sum += (O[i] - T[i])**<span class="hljs-number">2</span>/T[i]
    <span class="hljs-keyword">return</span>(D_sum)

D = calculate_D(O,T)
p_value = chi2.sf(D, df = <span class="hljs-number">1</span>)


<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
<span class="hljs-comment"># Step 1: pick a x-axis range like in case of z-test (-3,3,0.1)</span>
d = np.arange(<span class="hljs-number">0</span>,<span class="hljs-number">5</span>,<span class="hljs-number">0.1</span>)
<span class="hljs-comment"># Step 2: drawing the initial pdf of chi-2 with df = 1 and x-axis d range we just created</span>
plt.plot(d, chi2.pdf(d, df = <span class="hljs-number">1</span>), color = <span class="hljs-string">"purple"</span>)
<span class="hljs-comment"># Step 3: filling in the rejection region</span>
plt.fill_between(d[d&gt;D], chi2.pdf(d[d&gt;D], df = <span class="hljs-number">1</span>), color = <span class="hljs-string">"y"</span>)
<span class="hljs-comment"># Step 4: adding title</span>
plt.title(<span class="hljs-string">"Two Sample Chi-2 Test rejection region"</span>)
<span class="hljs-comment"># Step 5: showing the plt graph</span>
plt.show()
</code></pre>
<h3 id="heading-p-values">P-Values</h3>
<p>Another quick way to determine whether to reject or to support the Null Hypothesis is by using <strong>p-values</strong>. The p-value is the probability of the condition under the Null occurring. Stated differently, the p-value is the probability, assuming the null hypothesis is true, of observing a result at least as extreme as the test statistic. The smaller the p-value, the stronger is the evidence against the Null Hypothesis, suggesting that it can be rejected.</p>
<p>The interpretation of a <em>p</em>-value is dependent on the chosen significance level. Most often, 1%, 5%, or 10% significance levels are used to interpret the p-value. So, instead of using the t-test and the F-test, p-values of these test statistics can be used to test the same hypotheses.</p>
<p>The following figure shows a sample output of an OLS regression with two independent variables. In this table, the p-value of the t-test, testing the statistical significance of <em>class_size</em> variable’s parameter estimate, and the p-value of the F-test, testing the joint statistical significance of the <em>class_size,</em> and <em>el_pct</em> variables parameter estimates, are underlined.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-aJh-8BEvYnwid5jS7fDLHA.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>_Image Source:[ Stock and Whatson](https://www.uio.no/studier/emner/sv/oekonomi/ECON4150/v18/lecture7_ols_multiple_regressors_hypothesis_tests.pdf" data-href="https://www.uio.no/studier/emner/sv/oekonomi/ECON4150/v18/lecture7_ols_multiple_regressors_hypothesis_tests.pdf" class="markup--anchor markup--figure-anchor" rel="noopener" target="<em>blank)</em></p>
<p>The p-value corresponding to the <em>class_size</em> variable is 0.011. When we compare this value to the significance levels 1% or 0.01 , 5% or 0.05, 10% or 0.1, then we can make the following conclusions:</p>
<ul>
<li><p>0.011 &gt; 0.01 → Null of the t-test can’t be rejected at 1% significance level</p>
</li>
<li><p>0.011 &lt; 0.05 → Null of the t-test can be rejected at 5% significance level</p>
</li>
<li><p>0.011 &lt; 0.10 → Null of the t-test can be rejected at 10% significance level</p>
</li>
</ul>
<p>So, this p-value suggests that the coefficient of the <em>class_size</em> variable is statistically significant at 5% and 10% significance levels. The p-value corresponding to the F-test is 0.0000. And since 0 is smaller than all three cutoff values (0.01, 0.05, 0.10), we can conclude that the Null of the F-test can be rejected in all three cases.</p>
<p>This suggests that the coefficients of <em>class_size</em> and <em>el_pct</em> variables are jointly statistically significant at 1%, 5%, and 10% significance levels.</p>
<h4 id="heading-limitation-of-p-values">Limitation of p-values</h4>
<p>Using p-values has many benefits, but it has also limitations. One of the main ones is that the p-value depends on both the magnitude of association and the sample size. If the magnitude of the effect is small and statistically insignificant, the p-value might still show a <strong>significant impact</strong> because the sample size is large. The opposite can occur as well – an effect can be large, but fail to meet the p&lt;0.01, 0.05, or 0.10 criteria if the sample size is small.</p>
<h2 id="heading-inferential-statistics">Inferential Statistics</h2>
<p>Inferential statistics uses sample data to make reasonable judgments about the population from which the sample data originated. We use it to investigate the relationships between variables within a sample and make predictions about how these variables will relate to a larger population.</p>
<p>Both the <strong>Law of Large Numbers (LLN)</strong> and the <strong>Central Limit Theorem (CLM)</strong> have a significant role in Inferential statistics because they show that the experimental results hold regardless of what shape the original population distribution was when the data is large enough.</p>
<p>The more data is gathered, the more accurate the statistical inferences become – hence, the more accurate parameter estimates are generated.</p>
<h3 id="heading-law-of-large-numbers-lln">Law of Large Numbers (LLN)</h3>
<p>Suppose <strong>X1, X2, . . . , Xn</strong> are all independent random variables with the same underlying distribution (also called independent identically-distributed or i.i.d), where all X’s have the same mean <strong>μ</strong> and standard deviation <strong>σ</strong>. As the sample size grows, the probability that the average of all X’s is equal to the mean μ is equal to 1.</p>
<p>The Law of Large Numbers can be summarized as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-guDCKe5lIntrCicvX1WeBQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-central-limit-theorem-clm">Central Limit Theorem (CLM)</h3>
<p>Suppose <strong>X1, X2, . . . , Xn</strong> are all independent random variables with the same underlying distribution (also called independent identically-distributed or i.i.d), where all X’s have the same mean <strong>μ</strong> and standard deviation <strong>σ</strong>. As the sample size grows, the probability distribution of X <strong>converges in the distribution</strong> in Normal distribution with mean <strong>μ</strong> and variance **σ-**squared.</p>
<p>The Central Limit Theorem can be summarized as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-FCDUcznU-VRRdctstA1WJA.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Stated differently, when you have a population with mean μ and standard deviation σ and you take sufficiently large random samples from that population with replacement, then the distribution of the sample means will be approximately normally distributed.</p>
<h2 id="heading-dimensionality-reduction-techniques">Dimensionality Reduction Techniques</h2>
<p>Dimensionality reduction is the transformation of data from a <strong>high-dimensional space</strong> into a <strong>low-dimensional space</strong> such that this low-dimensional representation of the data still contains the meaningful properties of the original data as much as possible.</p>
<p>With the increase in popularity in Big Data, the demand for these dimensionality reduction techniques, reducing the amount of unnecessary data and features, increased as well. Examples of popular dimensionality reduction techniques are <a target="_blank" href="https://builtin.com/data-science/step-step-explanation-principal-component-analysis">Principle Component Analysis</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Factor_analysis">Factor Analysis</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Canonical_correlation">Canonical Correlation</a>, <a target="_blank" href="https://towardsdatascience.com/understanding-random-forest-58381e0602d2">Random Forest</a>.</p>
<h3 id="heading-principle-component-analysis-pca">Principle Component Analysis (PCA)</h3>
<p>Principal Component Analysis (PCA) is a dimensionality reduction technique that is very often used to reduce the dimensionality of large data sets. It does this by transforming a large set of variables into a smaller set that still contains most of the information or the variation in the original large dataset.</p>
<p>Let’s assume we have a data X with p variables X1, X2, …., Xp with <strong>eigenvectors</strong> e1, …, ep, and <strong>eigenvalues</strong> λ1,…, λp. Eigenvalues show the variance explained by a particular data field out of the total variance.</p>
<p>The idea behind PCA is to create new (independent) variables, called Principal Components, that are a linear combination of the existing variable. The i_th_ principal component can be expressed as follows:</p>
<p>$$Y_i = e_{i1}X_1 + e_{i2}X_2 + e_{i3}X_3 + ... + e_{ip}X_p$$</p><p>Then using the <strong>Elbow Rule</strong> or <a target="_blank" href="https://docs.displayr.com/wiki/Kaiser_Rule"><strong>Kaiser Rule</strong></a>, you can determine the number of principal components that optimally summarize the data without losing too much information.</p>
<p>It is also important to look at <strong>the proportion of total variation (PRTV)</strong> that is explained by each principal component to decide whether it is beneficial to include or to exclude it. PRTV for the i_th_ principal component can be calculated using eigenvalues as follows:</p>
<p>$$PRTV_i = \frac{{\lambda_i}}{{\sum_{k=1}^{p} \lambda_k}}$$</p><h3 id="heading-elbow-rule">Elbow Rule</h3>
<p>The elbow rule or the elbow method is a heuristic approach that we can use to determine the number of optimal principal components from the PCA results.</p>
<p>The idea behind this method is to plot <em>the explained variation</em> as a function of the number of components and pick the elbow of the curve as the number of optimal principal components.</p>
<p>Following is an example of such a scatter plot where the PRTV (Y-axis) is plotted on the number of principal components (X-axis). The elbow corresponds to the X-axis value 2, which suggests that the number of optimal principal components is 2.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/1-cLCESS2u2ZIsQbPBd7Ljlg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Image Source: [Multivariate Statistics Github](https://raw.githubusercontent.com/TatevKaren/Multivariate-Statistics/main/Elbow_rule</em>%25varc_explained.png" data-href="https://raw.githubusercontent.com/TatevKaren/Multivariate-Statistics/main/Elbow_rule_%25varc_explained.png" class="markup--anchor markup--figure-anchor" rel="noopener" target="<em>blank)</em></p>
<h3 id="heading-factor-analysis-fa">Factor Analysis (FA)</h3>
<p>Factor analysis or FA is another statistical method for dimensionality reduction. It is one of the most commonly used inter-dependency techniques. We can use it when the relevant set of variables shows a systematic inter-dependence and our objective is to find out the latent factors that create a commonality.</p>
<p>Let’s assume we have a data X with p variables X1, X2, …., Xp. The FA model can be expressed as follows:</p>
<p>$$X-\mu = AF + u$$</p><p>where:</p>
<ul>
<li><p>X is a [p x N] matrix of p variables and N observations</p>
</li>
<li><p>µ is [p x N] population mean matrix</p>
</li>
<li><p>A is [p x k] common <strong>factor loadings matrix</strong></p>
</li>
<li><p>F [k x N] is the matrix of common factors</p>
</li>
<li><p>and u [pxN] is the matrix of specific factors.</p>
</li>
</ul>
<p>So, to put it differently, a factor model is as a series of multiple regressions, predicting each of the variables Xi from the values of the unobservable common factors are:</p>
<p>$$X_1 = \mu_1 + a_{11}f_1 + a_{12}f_2 + ... + a_{1m}f_m + u1\\ X_2 = \mu_2 + a_{21}f_1 + a_{22}f_2 + ... + a_{2m}f_m + u2\\ .\\ .\\ .\\ X_p = \mu_p + a_{p1}f_1 + a_{p2}f_2 + ... + a_{pm}f_m + up$$</p><p>Each variable has k of its own common factors, and these are related to the observations via the factor loading matrix for a single observation as follows:</p>
<p>In factor analysis, the <strong>factors</strong> are calculated to <strong>maximize between-group variance</strong> while <strong>minimizing in-group varianc</strong>e. They are factors because they group the underlying variables. Unlike the PCA, in FA the data needs to be normalized, given that FA assumes that the dataset follows Normal Distribution.</p>
<h2 id="heading-interview-prep-top-7-statistics-questions-with-answers">Interview Prep – Top 7 Statistics Questions with Answers</h2>
<p>Are you preparing for interviews in statistics, data analysis, or data science? It's crucial to know key statistical concepts and their applications.</p>
<p>Below I've included seven important statistics questions with answers, covering basic statistical tests, probability theory, and the use of statistics in decision-making, like A/B testing.</p>
<h3 id="heading-question-1-what-is-the-difference-between-a-t-test-and-z-test">Question 1: What is the d<strong>ifference</strong> b<strong>etween</strong> a <strong>t-test and Z-test</strong>?</h3>
<p>The question "What is the difference between a t-test and Z-test?" is a common question in data science interviews because it tests the candidate's understanding of basic statistical concepts used in comparing group means.</p>
<p>This knowledge is crucial because choosing the right test affects the validity of conclusions drawn from data, which is a daily task in a data scientist's role when it comes to interpreting experiments, analyzing survey results, or evaluating models.</p>
<h3 id="heading-answer">Answer:</h3>
<p>Both t-tests and Z-tests are statistical methods used to determine if there are significant differences between the means of two groups. But they have key differences:</p>
<ul>
<li><p><strong>Assumptions</strong>: You can use a t-test when the sample sizes are small and the population standard deviation is unknown. It doesn't require the sample mean to be normally distributed if the sample size is sufficiently large due to the Central Limit Theorem. The Z-test assumes that both the sample and the population distributions are normally distributed.</p>
</li>
<li><p><strong>Sample Size</strong>: T-tests are typically used for sample sizes smaller than 30, whereas Z-tests are used for larger sample sizes (greater than or equal to 30) when the population standard deviation is known.</p>
</li>
<li><p><strong>Test Statistic</strong>: The t-test uses the t-distribution to calculate the test statistic, taking into account the sample standard deviation. The Z-test uses the standard normal distribution, utilizing the known population standard deviation.</p>
</li>
<li><p><strong>P-Value</strong>: The p-value in a t-test is determined based on the t-distribution, which accounts for the variability in smaller samples. The Z-test uses the standard normal distribution to calculate the p-value, suitable for larger samples or known population parameters.</p>
</li>
</ul>
<h3 id="heading-question-2-what-is-a-p-value">Question 2: What is a p-value?</h3>
<p>The question "What is a p-value?" requires the understanding of a fundamental concept in hypothesis testing that we descussed in this blog in detail with examples. It's not just a number – it's a bridge between the data you collect and the conclusions you draw for data driven decision making.</p>
<p>P-values quantify the evidence against a null hypothesis—how likely it is to observe the collected data if the null hypothesis were true.</p>
<p>For data scientists, p-values are part of everyday language in statistical analysis, model validation, and experimental design. They have to interpret p-values correctly to make informed decisions and often need to explain their implications to stakeholders who might not have deep statistical knowledge.</p>
<p>Thus, understanding p-values helps data scientists to convey the level of certainty or doubt in their findings and to justify subsequent actions or recommendations.</p>
<p>So here you need to show your understanding of what p-value measures and connect it to statistical significance and hypothesis testing.</p>
<h3 id="heading-answer-1">Answer:</h3>
<p>The p-value measures the probability of observing a test statistic at least as extreme as the one observed, under the assumption that the null hypothesis is true. It helps in deciding whether the observed data significantly deviate from what would be expected under the null hypothesis.</p>
<p>If the p-value is lower than a predetermined threshold (alpha level, usually set at 0.05), the null hypothesis is rejected, indicating that the observed result is statistically significant.</p>
<h3 id="heading-question-3-what-are-limitations-of-p-values">Question 3: What are limitations of p-values?</h3>
<p>P-values are a staple of inferential statistics, providing a metric for evaluating evidence against a null hypothesis. In these question you need to name couple of them.</p>
<h3 id="heading-answer-2">Answer</h3>
<ul>
<li><p><strong>Dependence on Sample Size</strong>: The p-value is sensitive to the sample size. Large samples might yield significant p-values even for trivial effects, while small samples may not detect significant effects even if they exist.</p>
</li>
<li><p><strong>Not a Measure of Effect Size or Importance</strong>: A small p-value does not necessarily mean the effect is practically significant – it simply indicates it's unlikely to have occurred by chance.</p>
</li>
<li><p><strong>Misinterpretation</strong>: P-values can be misinterpreted as the probability that the null hypothesis is true, which is incorrect. They only measure the evidence against the null hypothesis.</p>
</li>
</ul>
<h3 id="heading-question-4-what-is-a-confidence-level">Question 4: What is a Confidence Level?</h3>
<p>A confidence level represents the frequency with which an estimated confidence interval would contain the true population parameter if the same process were repeated multiple times.</p>
<p>For example, a 95% confidence level means that if the study were repeated 100 times, approximately 95 of the confidence intervals calculated from those studies would be expected to contain the true population parameter.</p>
<h3 id="heading-question-5-what-is-the-probability-of-picking-5-red-and-5-blue-balls-without-replacement">Question 5: What is the Probability of Picking 5 Red and 5 Blue Balls Without Replacement?</h3>
<p>What is the probability of picking exactly 5 red balls and 5 blue balls in 10 picks without replacement from a set of 100 balls, where there are 70 red balls and 30 blue balls? The text describes how to calculate this probability using combinatorial mathematics and the hypergeometric distribution.</p>
<p>In this question, you're dealing with a classic probability problem that involves combinatorial principles and the concept of probability without replacement. The context is a finite set of balls, each draw affecting the subsequent ones because the composition of the set changes with each draw.</p>
<p>To approach this problem, you need to consider:</p>
<ul>
<li><p><strong>The total number of balls</strong>: If the question doesn't specify this, you need to ask or make a reasonable assumption based on the context.</p>
</li>
<li><p><strong>Initial proportion of balls</strong>: Know the initial count of red and blue balls in the set.</p>
</li>
<li><p><strong>Sequential probability</strong>: Remember that each time you draw a ball, you don't put it back, so the probability of drawing a ball of a certain color changes with each draw.</p>
</li>
<li><p><strong>Combinations</strong>: Calculate the number of ways to choose 5 red balls from the total red balls and 5 blue balls from the total blue balls, then divide by the number of ways to choose any 10 balls from the total.</p>
</li>
</ul>
<p>Thinking through these points will guide you in formulating the solution based on the hypergeometric distribution, which describes the probability of a given number of successes in draws without replacement from a finite population.</p>
<p>This question tests your ability to apply probability theory to a dynamic scenario, a skill that's invaluable in data-driven decision-making and statistical modeling.</p>
<h3 id="heading-answer-3">Answer:</h3>
<p>To find the probability of picking exactly 5 red balls and 5 blue balls in 10 picks without replacement, we calculate the probability of picking 5 red balls out of 70 and 5 blue balls out of 30, and then divide by the total ways to pick 10 balls out of 100:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Screenshot-2024-04-09-at-12.35.56-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let's calculate this probability:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Screenshot-2024-04-09-at-12.36.16-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-question-6-explain-bayes-theorem-and-its-importance-in-calculating-posterior-probabilities">Question 6: Explain Bayes' Theorem and its importance in calculating posterior probabilities.</h3>
<p>Provide an example of how it might be used in genetic testing to determine the likelihood of an individual carrying a certain gene.</p>
<p>Bayes' Theorem is a cornerstone of probability theory that enables the updating of initial beliefs (prior probabilities) with new evidence to obtain updated beliefs (posterior probabilities). This question wants to test candidates ability to explain the concept, mathematical framework for incorporating new evidence into existing predictions or models.</p>
<h3 id="heading-answer-4">Answer:</h3>
<p>Bayes' Theorem is a fundamental theorem in probability theory and statistics that describes the probability of an event, based on prior knowledge of conditions that might be related to the event. It's crucial for calculating posterior probabilities, which are the probabilities of hypotheses given observed evidence.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Screenshot-2024-04-09-at-12.41.03-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li><p><em>P</em>(<em>A_∣_B</em>) is the posterior probability: the probability of hypothesis <em>A</em> given the evidence <em>B</em>.</p>
</li>
<li><p>P(B∣A) is the likelihood: the probability of observing evidence <em>B</em> given that hypothesis <em>A</em> is true.</p>
</li>
<li><p>P(A) is the prior probability: the initial probability of hypothesis <em>A</em>, before observing evidence <em>B</em>.</p>
</li>
<li><p>P(B) is the marginal probability: the total probability of observing evidence B_B_ under all possible hypotheses.</p>
</li>
</ul>
<h3 id="heading-question-7-describe-how-you-would-statistically-determine-if-the-results-of-an-ab-test-are-significant-walk-me-through-ab-testing-process">Question 7: Describe how you would statistically determine if the results of an A/B test are significant - walk me through AB Testing process.</h3>
<p>In this question, the interviewer is assessing your comprehensive knowledge of the A/B testing framework. They are looking for evidence that you can navigate the full spectrum of A/B testing procedures, which is essential for data scientists and AI professionals tasked with optimizing features, making data-informed decisions, and testing software products.</p>
<p>The interviewer wants to confirm that you understand each step in the process, beginning with formulating statistical hypotheses derived from business objectives. They are interested in your ability to conduct a power analysis and discuss its components, including determining effect size, significance level, and power, all critical in calculating the minimum sample size needed to detect a true effect and prevent p-hacking.</p>
<p>The discussion on randomization, data collection, and monitoring checks whether you grasp how to maintain the integrity of the test conditions. You should also be prepared to explain the selection of appropriate statistical tests, calculation of test statistics, p-values, and interpretation of results for both statistical and practical significance.</p>
<p>Ultimately, the interviewer is testing whether you can act as a data advocate: someone who can meticulously run A/B tests, interpret the results, and communicate findings and recommendations effectively to stakeholders, thereby driving data-driven decision-making within the organization.</p>
<p>To Learn AB Testing check my <a target="_blank" href="https://www.youtube.com/watch?v=QzAXW7kQ0I8&amp;t=1707s">AB Testing Crash Course on YouTube</a>.</p>
<h3 id="heading-answer-5">Answer:</h3>
<p>In an A/B test, my first step is to establish clear business and statistical hypotheses. For example, if we’re testing a new webpage layout, the business hypothesis might be that the new layout increases user engagement. Statistically, this translates to expecting a higher mean engagement score for the new layout compared to the old.</p>
<p>Next, I’d conduct a power analysis. This involves deciding on an effect size that's practically significant for our business context—say, a 10% increase in engagement. I'd choose a significance level, commonly 0.05, and aim for a power of 80%, reducing the likelihood of Type II errors.</p>
<p>The power analysis, which takes into account the effect size, significance level, and power, helps determine the minimum sample size needed. This is crucial for ensuring that our test is adequately powered to detect the effect we care about and for avoiding p-hacking by committing to a sample size upfront.</p>
<p>With our sample size determined, I’d ensure proper randomization in assigning users to the control and test groups, to eliminate selection bias. During the test, I’d closely monitor data collection for any anomalies or necessary adjustments.</p>
<p>Upon completion of the data collection, I’d choose an appropriate statistical test based on the data distribution and variance homogeneity—typically a t-test if the sample size is small or a normal distribution can’t be assumed, or a Z-test for larger samples with a known variance.</p>
<p>Calculating the test statistic and the corresponding p-value allows us to test the null hypothesis. If the p-value is less than our chosen alpha level, we reject the null hypothesis, suggesting that the new layout has a statistically significant impact on engagement.</p>
<p>In addition to statistical significance, I’d evaluate the practical significance by looking at the confidence interval for the effect size and considering the business impact.</p>
<p>Finally, I’d document the entire process and results, then communicate them to stakeholders in a clear, non-technical language. This includes not just the statistical significance, but also how the results translate to business outcomes. As a data advocate, my goal is to support data-driven decisions that align with our business objectives and user experience strategy</p>
<p>For getting more interview questions from Stats to Deep Learning - with over 400 Q&amp;A as well as personalized interview preparation check out our <a target="_blank" href="https://lunartech.ai/free-resources/">Free Resource Hub</a> and our <a target="_blank" href="https://lunartech.ai/course-overview/">Data Science Bootcamp with Free Trial</a>.</p>
<p>Thank you for choosing this guide as your learning companion. As you continue to explore the vast field of machine learning, I hope you do so with confidence, precision, and an innovative spirit. Best wishes in all your future endeavors!</p>
<h2 id="heading-about-the-author">About the Author</h2>
<p>I am <a target="_blank" href="https://tatevaslanyan.com"><strong>Tatev</strong></a> <strong>Aslanyan</strong>, Senior Machine Learning and AI Researcher, and Co-Founder of <a target="_blank" href="https://lunartech.ai"><strong>LunarTech</strong></a> where we are making Data Science and AI accessible to everyone. I have had the privilege of working in Data Science across numerous countries, including the US, UK, Canada, and the Netherlands.</p>
<p>With an MSc and BSc in Econometrics under my belt, my journey in Machine and AI has been nothing short of incredible. Drawing from my technical studies during my Bachelors &amp; Masters, along with over 5 years of hands-on experience in the Data Science Industry, in Machine Learning and AI, I've gathered this high-level summary of ML topics to share with you.</p>
<h2 id="heading-how-can-you-dive-deeper">How Can You Dive Deeper?</h2>
<p>After studying this guide, if you're keen to dive even deeper and structured learning is your style, consider joining us at <a target="_blank" href="https://lunartech.ai"><strong>LunarTech</strong></a>, we offer individual courses and Bootcamp in Data Science, Machine Learning and AI.</p>
<p>We provide a comprehensive program that offers an in-depth understanding of the theory, hands-on practical implementation, extensive practice material, and tailored interview preparation to set you up for success at your own phase.</p>
<p>You can check out our <a target="_blank" href="https://lunartech.ai/course-overview/">Ultimate Data Science Bootcamp</a> and join <a target="_blank" href="https://lunartech.ai/pricing/">a free trial</a> to try the content first hand. This has earned the recognition of being one of the <a target="_blank" href="https://www.itpro.com/business-strategy/careers-training/358100/best-data-science-boot-camps">Best Data Science Bootcamps of 2023</a>, and has been featured in esteemed publications like <a target="_blank" href="https://www.forbes.com.au/brand-voice/uncategorized/not-just-for-tech-giants-heres-how-lunartech-revolutionizes-data-science-and-ai-learning/">Forbes</a>, <a target="_blank" href="https://finance.yahoo.com/news/lunartech-launches-game-changing-data-115200373.html?guccounter=1&amp;guce_referrer=aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8&amp;guce_referrer_sig=AQAAAAM3JyjdXmhpYs1lerU37d64maNoXftMA6BYjYC1lJM8nVa_8ZwTzh43oyA6Iz0DfqLtjVHnknO0Zb8QTLIiHuwKzQZoodeM85hkI39fta3SX8qauBUsNw97AeiBDR09BUDAkeVQh6eyvmNLAGblVj3GSf1iCo81bwHQxknmhgng#">Yahoo</a>, <a target="_blank" href="https://www.entrepreneur.com/ka/business-news/outpacing-competition-how-lunartech-is-redefining-the/463038">Entrepreneur</a> and more. This is your chance to be a part of a community that thrives on innovation and knowledge. Here is the Welcome message!</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/c-SXFXegVTw" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-connect-with-me">Connect with Me</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/Screenshot-2024-04-09-at-12.05.32-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://substack.com/@lunartech"><em>LunarTech</em></a> <em>Newsletter</em></p>
<ul>
<li><p><a target="_blank" href="https://www.linkedin.com/in/tatev-karen-aslanyan/">Follow me on <strong>LinkedIn</strong></a> and on <a target="_blank" href="https://www.youtube.com/@LunarTech_ai"><strong>YouTube</strong></a></p>
</li>
<li><p><a target="_blank" href="https://lunartech.ai/free-resources/">Check LunarTech.ai for FREE Resources</a></p>
</li>
<li><p>Subscribe to my <a target="_blank" href="https://tatevaslanyan.substack.com/"><strong>The Data Science and AI Newsletter</strong></a></p>
</li>
</ul>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://substack.com/@lunartech">https://substack.com/@lunartech</a></div>
<p> </p>
<p>If you want to learn more about a career in Data Science, Machine Learning and AI, and learn how to secure a Data Science job, you can download this free <a target="_blank" href="https://downloads.tatevaslanyan.com/six-figure-data-science-ebook">Data Science and AI Career Handbook</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Is Hypothesis Testing? Types and Python Code Example ]]>
                </title>
                <description>
                    <![CDATA[ Curiosity has always been a part of human nature. Since the beginning of time, this has been one of the most important tools for birthing civilizations. Still, our curiosity grows — it tests and expands our limits. Humanity has explored the plains of... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-hypothesis-testing/</link>
                <guid isPermaLink="false">66c71f7855df43f1418b5b23</guid>
                
                    <category>
                        <![CDATA[ data analysis ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mene-Ejegi Ogbemi ]]>
                </dc:creator>
                <pubDate>Fri, 22 Sep 2023 00:41:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/Banner---Tech-writing---hypothesis.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Curiosity has always been a part of human nature. Since the beginning of time, this has been one of the most important tools for birthing civilizations. Still, our curiosity grows — it tests and expands our limits. Humanity has explored the plains of land, water, and air. We've built underwater habitats where we could live for weeks. Our civilization has explored various planets. We've explored land to an unlimited degree. </p>
<p>These things were possible because humans asked questions and searched until they found answers. However, for us to get these answers, a proven method must be used and followed through to validate our results. Historically, philosophers assumed the earth was flat and you would fall off when you reached the edge. While philosophers like Aristotle argued that the earth was spherical based on the formation of the stars, they could not prove it at the time. </p>
<p>This is because they didn't have adequate resources to explore space or mathematically prove Earth's shape. It was a Greek mathematician named Eratosthenes who calculated the earth's circumference with incredible precision. He used scientific methods to show that the Earth was not flat. Since then, other methods have been used to prove the Earth's spherical shape.</p>
<p>When there are questions or statements that are yet to be tested and confirmed based on some scientific method, they are called hypotheses. Basically, we have two types of hypotheses: null and alternate.</p>
<p>A <strong>null hypothesis</strong> is one's default belief or argument about a subject matter. In the case of the earth's shape, the null hypothesis was that the earth was flat.</p>
<p>An <strong>alternate hypothesis</strong> is a belief or argument a person might try to establish. Aristotle and Eratosthenes argued that the earth was spherical.</p>
<p>Other examples of a random alternate hypothesis include:</p>
<ul>
<li>The weather may have an impact on a person's mood.</li>
<li>More people wear suits on Mondays compared to other days of the week.</li>
<li>Children are more likely to be brilliant if both parents are in academia, and so on.</li>
</ul>
<h2 id="heading-what-is-hypothesis-testing">What is Hypothesis Testing?</h2>
<p>Hypothesis testing is the act of testing whether a hypothesis or inference is true. When an alternate hypothesis is introduced, we test it against the null hypothesis to know which is correct. Let's use a plant experiment by a 12-year-old student to see how this works.</p>
<p>The hypothesis is that a plant will grow taller when given a certain type of fertilizer. The student takes two samples of the same plant, fertilizes one, and leaves the other unfertilized. He measures the plants' height every few days and records the results in a table. </p>
<p>After a week or two, he compares the final height of both plants to see which grew taller. If the plant given fertilizer grew taller, the hypothesis is established as fact. If not, the hypothesis is not supported. This simple experiment shows how to form a hypothesis, test it experimentally, and analyze the results.</p>
<p>In hypothesis testing, there are two types of error: Type I and Type II.</p>
<p>When we reject the null hypothesis in a case where it is correct, we've committed a Type I error. Type II errors occur when we fail to reject the null hypothesis when it is incorrect.</p>
<p>In our plant experiment above, if the student finds out that both plants' heights are the same at the end of the test period yet opines that fertilizer helps with plant growth, he has committed a Type I error. </p>
<p>However, if the fertilized plant comes out taller and the student records that both plants are the same or that the one without fertilizer grew taller, he has committed a Type II error because he has failed to reject the null hypothesis.</p>
<h2 id="heading-what-are-the-steps-in-hypothesis-testing">What are the Steps in Hypothesis Testing?</h2>
<p>The following steps explain how we can test a hypothesis:</p>
<h3 id="heading-step-1-define-the-null-and-alternative-hypotheses">Step #1 - Define the Null and Alternative Hypotheses</h3>
<p>Before making any test, we must first define what we are testing and what the default assumption is about the subject. In this article, we'll be testing if the average weight of 10-year-old children is more than 32kg. </p>
<p>Our null hypothesis is that 10 year old children weigh 32 kg on average. Our alternate hypothesis is that the average weight is more than 32kg. <code>Ho</code> denotes a null hypothesis, while <code>H1</code> denotes an alternate hypothesis.</p>
<p>Ho = 32</p>
<p>H1 = 32</p>
<h3 id="heading-step-2-choose-a-significance-level">Step #2 - Choose a Significance Level</h3>
<p>The significance level is a threshold for determining if the test is valid. It gives credibility to our hypothesis test to ensure we are not just luck-dependent but have enough evidence to support our claims. We usually set our significance level before conducting our tests. The criterion for determining our significance value is known as p-value. </p>
<p>A lower p-value means that there is stronger evidence against the null hypothesis, and therefore, a greater degree of significance. A p-value of 0.05 is widely accepted to be significant in most fields of science. P-values do not denote the probability of the outcome of the result, they just serve as a benchmark for determining whether our test result is due to chance. For our test, our p-value will be 0.05.</p>
<h3 id="heading-step-3-collect-data-and-calculate-a-test-statistic">Step #3 - Collect Data and Calculate a Test Statistic</h3>
<p>You can obtain your data from online data stores or conduct your research directly. Data can be scraped or researched online. The methodology might depend on the research you are trying to conduct.</p>
<p>We can calculate our test using any of the appropriate hypothesis tests. This can be a T-test, Z-test, Chi-squared, and so on. There are several hypothesis tests, each suiting different purposes and research questions. In this article, we'll use the T-test to run our hypothesis, but I'll explain the Z-test, and chi-squared too.</p>
<p>T-test is used for comparison of two sets of data when we don't know the population standard deviation. It's a parametric test, meaning it makes assumptions about the distribution of the data. These assumptions include that the data is normally distributed and that the variances of the two groups are equal. In a more simple and practical sense, imagine that we have test scores in a class for males and females, but we don't know how different or similar these scores are. We can use a t-test to see if there's a real difference.</p>
<p>The Z-test is used for comparison between two sets of data when the population standard deviation is known. It is also a parametric test, but it makes fewer assumptions about the distribution of data. The z-test assumes that the data is normally distributed, but it does not assume that the variances of the two groups are equal. In our class test example, with the t-test, we can say that if we already know how spread out the scores are in both groups, we can now use the z-test to see if there's a difference in the average scores.</p>
<p>The Chi-squared test is used to compare two or more categorical variables. The chi-squared test is a non-parametric test, meaning it does not make any assumptions about the distribution of data. It can be used to test a variety of hypotheses, including whether two or more groups have equal proportions.</p>
<h3 id="heading-step-4-decide-on-the-null-hypothesis-based-on-the-test-statistic-and-significance-level">Step #4 - Decide on the Null Hypothesis Based on the Test Statistic and Significance Level</h3>
<p>After conducting our test and calculating the test statistic, we can compare its value to the predetermined significance level. If the test statistic falls beyond the significance level, we can decide to reject the null hypothesis, indicating that there is sufficient evidence to support our alternative hypothesis. </p>
<p>On the other contrary, if the test statistic does not exceed the significance level, we fail to reject the null hypothesis, signifying that we do not have enough statistical evidence to conclude in favor of the alternative hypothesis.</p>
<h3 id="heading-step-5-interpret-the-results">Step #5 - Interpret the Results</h3>
<p>Depending on the decision made in the previous step, we can interpret the result in the context of our study and the practical implications. For our case study, we can interpret whether we have significant evidence to support our claim that the average weight of 10 year old children is more than 32kg or not.</p>
<p>For our test, we are generating random dummy data for the weight of the children. We'll use a t-test to evaluate whether our hypothesis is correct or not.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> scipy.stats <span class="hljs-keyword">as</span> stats

<span class="hljs-comment"># Create a dummy dataset of 10 year old children's weight</span>
data = np.random.randint(<span class="hljs-number">20</span>, <span class="hljs-number">40</span>, <span class="hljs-number">10</span>)

<span class="hljs-comment"># Define the null hypothesis</span>
H0 = <span class="hljs-string">"The average weight of 10 year old children is 32kg."</span>

<span class="hljs-comment"># Define the alternative hypothesis</span>
H1 = <span class="hljs-string">"The average weight of 10 year old children is more than 32kg."</span>

<span class="hljs-comment"># Calculate the test statistic</span>
t_stat, p_value = stats.ttest_1samp(data, <span class="hljs-number">32</span>)

<span class="hljs-comment"># Print the results</span>
print(<span class="hljs-string">"Test statistic:"</span>, t_stat)
print(<span class="hljs-string">"p-value:"</span>, p_value)

<span class="hljs-comment"># Conclusion</span>
<span class="hljs-keyword">if</span> p_value &lt; <span class="hljs-number">0.05</span>:
    print(<span class="hljs-string">"Reject the null hypothesis."</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Fail to reject the null hypothesis."</span>)
</code></pre>
<p>For a better understanding, let's look at what each block of code does.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> scipy.stats <span class="hljs-keyword">as</span> stats
</code></pre>
<p>The first block is the import statement, where we import <code>numpy</code> and <code>scipy.stats</code>. Numpy is a Python library used for scientific computing. It has a large library of functions for working with arrays. Scipy is a library for mathematical functions. It has a stat module for performing statistical functions, and that's what we'll be using for our t-test.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Create a dummy dataset of 10 year old children's weight</span>
data = np.random.randint(<span class="hljs-number">20</span>, <span class="hljs-number">40</span>, <span class="hljs-number">100</span>)
</code></pre>
<p>The weights of the children were generated at random since we aren't working with an actual dataset. The random module within the Numpy library provides a function for generating random numbers, which is <code>randint</code>. </p>
<p>The <code>randint</code> function takes three arguments. The first (20) is the lower bound of the random numbers to be generated. The second (40) is the upper bound, and the third (100) specifies the number of random integers to generate. That is, we are generating random weight values for 100 children. In real circumstances, these weight samples would have been obtained by taking the weight of the required number of children needed for the test.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Define the null hypothesis</span>
H0 = <span class="hljs-string">"The average weight of 10 year old children is 32kg."</span>

<span class="hljs-comment"># Define the alternative hypothesis</span>
H1 = <span class="hljs-string">"The average weight of 10 year old children is more than 32kg."</span>
</code></pre>
<p>Using the code above, we declared our null and alternate hypotheses stating the average weight of a 10-year-old in both cases.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Calculate the test statistic</span>
t_stat, p_value = stats.ttest_1samp(data, <span class="hljs-number">32</span>)
</code></pre>
<p><code>t_stat</code> and <code>p_value</code> are the variables in which we'll store the results of our functions. <code>stats.ttest_1samp</code> is the function that calculates our test. It takes in two variables, the first is the <code>data</code> variable that stores the array of weights for children, and the second (32) is the value against which we'll test the mean of our array of weights or dataset in cases where we are using a real-world dataset.</p>
<pre><code class="lang-python">
<span class="hljs-comment"># Print the results</span>
print(<span class="hljs-string">"Test statistic:"</span>, t_stat)
print(<span class="hljs-string">"p-value:"</span>, p_value)
</code></pre>
<p>The code above prints both values for <code>t_stats</code> and <code>p_value</code>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Conclusion</span>
<span class="hljs-keyword">if</span> p_value &lt; <span class="hljs-number">0.05</span>:
    print(<span class="hljs-string">"Reject the null hypothesis."</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"Fail to reject the null hypothesis."</span>)
</code></pre>
<p>Lastly, we evaluated our <code>p_value</code> against our significance value, which is 0.05. If our <code>p_value</code> is less than 0.05, we reject the null hypothesis. Otherwise, we fail to reject the null hypothesis. Below is the output of this program. Our null hypothesis was rejected.</p>
<pre><code class="lang-python">Test statistic: <span class="hljs-number">-5.114430435590074</span>
p-value: <span class="hljs-number">1.541000376540265e-06</span>
Reject the null hypothesis.
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we discussed the importance of hypothesis testing. We highlighted how science has advanced human knowledge and civilization through formulating and testing hypotheses.</p>
<p>We discussed Type I and Type II errors in hypothesis testing and how they underscore the importance of careful consideration and analysis in scientific inquiry. It reinforces the idea that conclusions should be drawn based on thorough statistical analysis rather than assumptions or biases.</p>
<p>We also generated a sample dataset using the relevant Python libraries and used the needed functions to calculate and test our alternate hypothesis.</p>
<p>Thank you for reading! Please follow me on <a target="_blank" href="https://www.linkedin.com/in/ogbemi-ejegi/">LinkedIn</a> where I also post more data related content.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is R Squared? R2 Value Meaning and Definition ]]>
                </title>
                <description>
                    <![CDATA[ Regression analysis is a statistical method used to study the relationship between a dependent variable and one or more independent variables.  One of the most commonly used methods for linear regression analysis is R-Squared.  In this article, you'l... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-r-squared-r2-value-meaning-and-definition/</link>
                <guid isPermaLink="false">66b0a38e5e73cf343a5cc01d</guid>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ihechikara Abba ]]>
                </dc:creator>
                <pubDate>Tue, 28 Mar 2023 14:51:21 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/lxrcbsv-vVHXeu0YNbk-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Regression analysis is a statistical method used to study the relationship between a dependent variable and one or more independent variables. </p>
<p>One of the most commonly used methods for linear regression analysis is R-Squared. </p>
<p>In this article, you'll get to know what R-Squared is and the meaning of its value(s). You'll also see some of the fields where it is used. </p>
<h2 id="heading-what-is-r-squared">What is R Squared?</h2>
<p>R-Squared (R²) is a statistical measure used to determine the proportion of variance in a dependent variable that can be predicted or explained by an independent variable.</p>
<p>In other words, R-Squared shows how well a regression model (independent variable) predicts the outcome of observed data (dependent variable).</p>
<p>R-Squared is also commonly known as the coefficient of determination. It is a goodness of fit model for linear regression analysis.</p>
<h2 id="heading-what-does-an-r-squared-value-mean">What Does an R Squared Value Mean?</h2>
<p>An R-Squared value shows how well the model predicts the outcome of the dependent variable. R-Squared values range from 0 to 1.</p>
<p>An R-Squared value of 0 means that the model explains or predicts 0% of the relationship between the dependent and independent variables.</p>
<p>A value of 1 indicates that the model predicts 100% of the relationship, and a value of 0.5 indicates that the model predicts 50%, and so on. </p>
<p>The formula below is mostly used to find the value of R-Squared:</p>
<p>R² = 1 - RSS/TSS</p>
<p>where,</p>
<ul>
<li>R² = coefficient of determination</li>
<li>RSS = sum of squares of residuals</li>
<li>TSS = total sum of squares</li>
</ul>
<h2 id="heading-where-is-r-squared-used">Where Is R Squared Used?</h2>
<p>R-Squared is used by different fields. It can be used for the following:</p>
<ul>
<li>Risk analysis in finance. </li>
<li>Marketing campaigns. </li>
<li>Scientific research. </li>
<li>Economics. </li>
<li>Sports analysis. </li>
</ul>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we talked about R-Squared. It is a statistical method mostly used in predicting the outcome of data. </p>
<p>We started by looking at what R-Squared means. We then talked about the meaning of its value and how to calculate it. </p>
<p>Lastly, we talked about the different fields where R-Sqaured can be used. </p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is the Difference Between an Independent Variable and a Dependent Variable? ]]>
                </title>
                <description>
                    <![CDATA[ The meaning of the word "variable" depends on the field where it's being used.  In programming, a variable is a particular piece of data that holds a value. Depending on the configuration, that value can change or remain fixed.  For instance, in Java... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/independent-variable-vs-dependent-variable/</link>
                <guid isPermaLink="false">66adf1867550d4f37c2019b7</guid>
                
                    <category>
                        <![CDATA[ research ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kolade Chris ]]>
                </dc:creator>
                <pubDate>Thu, 15 Dec 2022 17:32:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/12/snowy-4689675_1280.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The meaning of the word "variable" depends on the field where it's being used. </p>
<p>In programming, a variable is a particular piece of data that holds a value. Depending on the configuration, that value can change or remain fixed. </p>
<p>For instance, in JavaScript, you can implement a variable to change over time with the "var" and "let" keywords. But if you want, you can implement a variable so it doesn't change with the "const" keyword.</p>
<p>In this article, the kind of variable we’ll be looking at is not the one in programming but the one you'll deal with in research. Precisely, we’ll look at the differences between the two main types of variables in research – dependent and independent variables.</p>
<p>But before we look at the differences between dependent and independent variables, we need to understand what a variable is first.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-a-variable-in-research">What is a Variable in Research?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-dependent-and-independent-variables">What are Dependent and Independent Variables?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-differences-between-dependent-and-independent-variables">What are the Differences between Dependent and Independent Variables?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-identify-a-dependent-variable-from-an-independent-variable">How to Identify a Dependent Variable from an Independent Variable</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
<li><a class="post-section-overview" href="#morereadings">More Readings</a></li>
</ul>
<h2 id="heading-what-is-a-variable-in-research">What is a Variable in Research?</h2>
<p>If you’re conducting research, you’ll be measuring a lot of values. So, in research, a variable is anything you’re trying to measure. It could be age, temperature, length, height, mass, weight, or any other thing that can have a value.</p>
<p>In addition, you’ll be measuring those variables in different units – centimeters (cm), meters (m), grams (g), kilograms (kg), and many more. </p>
<p>These units can’t be neglected, but as far as variables are concerned, whether dependent or independent, the values are what really matter.</p>
<h2 id="heading-what-are-dependent-and-independent-variables">What are Dependent and Independent Variables?</h2>
<p>Dependent and independent variables depend on whether one variable determines the outcome of the other or not.</p>
<p>A dependent variable is a variable whose changes and its outcome depend on another variable. On almost all occasions, the variable the dependent variable depends on is an independent variable.</p>
<p>Dependent variables are also called the response or outcome variables because they represent the outcome of the values you're measuring. That is, what you record after manipulating the independent variables.</p>
<p>An independent variable is a variable whose outcome or changes do not depend on another variable. It is the exact opposite of the dependent variable, at least according to what the name implies.</p>
<p>Independent variables are also called predictor variables because you can use them to predict the outcome of a dependent variable. That is, when you manipulate independent variables, they can give you the outcome of a dependent variable.</p>
<h2 id="heading-what-are-the-differences-between-dependent-and-independent-variables">What are the Differences between Dependent and Independent Variables?</h2>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Basis</strong></td><td><strong>Dependent Variable</strong></td><td><strong>Independent Variable</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Type</strong></td><td>It is the "response" variable</td><td>It is the "effect" variable</td></tr>
<tr>
<td><strong>Outcome</strong></td><td>Outcome depends on another variable (usually the independent variable)</td><td>Outcome does not depend on another variable</td></tr>
<tr>
<td><strong>Changes</strong></td><td>This variable changes over time. Consider the dependent variable as a variable you declare with the "let" or "var" keyword in JavaScript. You can later change it.</td><td>This variable never changes. Consider the independent variable as the variable you declare with the "const" keyword in JavaScript. It is fixed unless you explicitly change the value.</td></tr>
<tr>
<td><strong>Manipulation</strong></td><td>Dependent variables cannot be manipulated because their value depends on the independent variable.</td><td>Independent variables can be manipulated to determine the outcome of a dependent variable.</td></tr>
<tr>
<td><strong>Position on a Graph</strong></td><td>Dependent variables are placed on the y-axis (vertical axis) on a graph</td><td>Independent variables are placed on the x-axis (horizontal axis) on a graph</td></tr>
</tbody>
</table>
</div><h2 id="heading-how-to-identify-a-dependent-variable-from-an-independent-variable">How to Identify a Dependent Variable from an Independent Variable</h2>
<p>We've taken a look at what variables are, what dependent and independent variables are, and the exact differences between dependent and independent variables. </p>
<p>But how exactly would you differentiate a dependent variable from an independent variable? We are going to look at two experiments or examples:</p>
<ul>
<li><p>how Vitamin A helps mothers produce milk</p>
</li>
<li><p>the level of light nocturnal insects (insects active at night) are attracted to</p>
</li>
</ul>
<p>For the first experiment, the sources of vitamin A the mother takes in from foods like fish oil and green vegetables are the independent variable. That's because the researcher can change [decrease or increase] the amount given to the mothers. How the body of the mother responds in producing more milk is the dependent variable.</p>
<p>For the second experiment, the level of light is the independent variable because the researcher can change it. How nocturnal insects react to that level of light is the dependent variable.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned about the differences between dependent and independent variables. We looked at:</p>
<ul>
<li><p>what a variable is in research</p>
</li>
<li><p>the two main types of variables (dependent and independent variables)</p>
</li>
<li><p>what dependent and independent variables are</p>
</li>
<li><p>and how to differentiate a dependent variable from an independent variable.</p>
</li>
</ul>
<p>I hope this article gives you a knowledge of what research variables are and how to differentiate a dependent variable from an independent variable.</p>
<p>Thank you for reading.</p>
<h3 id="heading-further-reading">Further Reading</h3>
<ul>
<li><a target="_blank" href="https://www.scribbr.com/methodology/types-of-variables/">Types of Variables in Research and Statistics</a></li>
<li><a target="_blank" href="https://www.scribbr.com/methodology/independent-and-dependent-variables/">Independent Variables v Dependent Variables</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Stratified Random Sampling? Definition and Python Example ]]>
                </title>
                <description>
                    <![CDATA[ When we wish to conduct an experiment on a population – for example, the entire population of a country – it is not always practical or realistic to include every subject (citizen) in the experiment. Instead, we rely on a sample, which is a subset of... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-stratified-random-sampling-definition-and-python-example/</link>
                <guid isPermaLink="false">66d45f46f855545810e93474</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ibrahim Ogunbiyi ]]>
                </dc:creator>
                <pubDate>Tue, 15 Nov 2022 16:33:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/pexels-viktorya-sergeeva--------10275085.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When we wish to conduct an experiment on a population – for example, the entire population of a country – it is not always practical or realistic to include every subject (citizen) in the experiment.</p>
<p>Instead, we rely on a sample, which is a subset of the population, and then draw conclusions about the population based on the sample's results.</p>
<p>Now, drawing a sample from a population is known as sampling technique, and the manner in which the sample is drawn is essential to the result.</p>
<p>There are lot of sampling techniques out there, but in this tutorial we will look at one of them called stratified random sampling and how it works. Without further ado, let's get started.</p>
<h2 id="heading-what-is-stratified-random-sampling">What is Stratified Random Sampling?</h2>
<p>Before we go into the details of stratified random sampling, let's break the term down into bits so we can grasp it better. Let's start with stratified.</p>
<p>In the context of sampling, <strong>stratified</strong> means splitting the population into smaller groups or strata based on a characteristic. To put it another way, you divide a population into groups based on their features.</p>
<p><strong>Random</strong> <strong>sampling</strong> entails randomly selecting subjects (entities) from a population. Each subject has an equal probability of being chosen from the population to form a sample (subpopulation) of the overall population.</p>
<p>So therefore, <strong>stratified random sampling</strong> is a sampling approach in which the population is separated into groups or strata depending on a particular characteristic. Then subjects from each stratum (the singular of strata) are randomly sampled.</p>
<p>You divide the population into groups based on a characteristic and then choose a subject or entity at random from each group.</p>
<h2 id="heading-types-of-stratified-random-sampling">Types of Stratified Random Sampling</h2>
<p>Stratified sampling is divided into two categories, which are:</p>
<ul>
<li><p>Proportionate stratified random sampling.</p>
</li>
<li><p>Disproportionate stratified random sampling.</p>
</li>
</ul>
<p><strong>Proportionate stratified random sampling</strong> is a type of sampling in which the size of the random sample obtained from each stratum is proportionate to the size of the entire stratum's population.</p>
<p>In other words, the proportion of the entire stratum equals the proportion of the sample stratum. Consider the following example:</p>
<pre><code class="lang-python">students = {

    <span class="hljs-string">"Name"</span>: [<span class="hljs-string">"Ibrahim"</span>, <span class="hljs-string">"Ganiyat"</span>, <span class="hljs-string">"Joel"</span>, <span class="hljs-string">"Elijah"</span>, <span class="hljs-string">"Yusuf"</span>, <span class="hljs-string">"Nurain"</span>, 
            <span class="hljs-string">"Dayo"</span>, <span class="hljs-string">"David"</span>, <span class="hljs-string">"Olu"</span>, <span class="hljs-string">"Tobi"</span>],

    <span class="hljs-string">"ID"</span>:  [<span class="hljs-string">'001'</span>, <span class="hljs-string">'002'</span>, <span class="hljs-string">'003'</span>, <span class="hljs-string">'004'</span>, <span class="hljs-string">'005'</span>, <span class="hljs-string">'006'</span>,<span class="hljs-string">'007'</span>, <span class="hljs-string">'008'</span>, <span class="hljs-string">'009'</span>, <span class="hljs-string">'010'</span>],

    <span class="hljs-string">"Grade"</span>: [<span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>, <span class="hljs-string">'C'</span>, <span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>, <span class="hljs-string">'C'</span>, <span class="hljs-string">'A'</span>, <span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>, <span class="hljs-string">'A'</span>],

    <span class="hljs-string">"Category"</span>: [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>]
}
df = pd.DataFrame(students)
&gt;&gt;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/image-35.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The above dataframe contains students' names, IDs, grades, and categories. Assume we wish to stratify students based on their grade characteristics and sample 60% of students from each group. That means we will have three strata in the above dataframe, because we have three different grades.</p>
<p>We can sample it by typing the following:</p>
<pre><code class="lang-python">df_sample = df.groupby(<span class="hljs-string">"Grade"</span>, group_keys=<span class="hljs-literal">False</span>).apply(<span class="hljs-keyword">lambda</span> x:x.sample(frac=<span class="hljs-number">0.6</span>))
</code></pre>
<p>Now what we did above is to group the dataframe into different strata using the <code>groupby()</code> method. Then we passed in the <code>Grade</code> feature. For each group (stratum) we randomly sampled out <code>0.6(60%)</code> of observation from it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/image-36.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now if we look at the proportion for <code>df_sample</code> and <code>df</code>, we will see that the proportions for both dataframes are the same.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/image-37.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Disproportionate stratified random sampling</strong>, on the other hand, involves randomly selecting strata without regard for proportion. In other words, sampling is done based on a specified number. Let's look at an example.</p>
<pre><code class="lang-python">df.groupby(<span class="hljs-string">'Grade'</span>, group_keys=<span class="hljs-literal">False</span>).apply(<span class="hljs-keyword">lambda</span> x: x.sample(n=<span class="hljs-number">2</span>))
</code></pre>
<p>In this code, you can see that we only specified the actual number of samples we want to achieve.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/image-38.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Most of the time, you'll use proportionate stratified sampling. Disproportionate requires more expert knowledge. When performing stratified sampling you will most likely use proportionate sampling.</p>
<h2 id="heading-applications-of-stratified-random-sampling">Applications of Stratified Random Sampling</h2>
<h3 id="heading-1-sampling-based-on-shared-characteristic">1. Sampling Based on Shared Characteristic:</h3>
<p>When one or more subjects in an experiment share characteristics, it suggests they are members of the same group (one subject can only be in a particular group).</p>
<p>For example, suppose 50 students take a test, and the grade range for the examination is merely A-E. So we can have students who are in the same grade group, for example, students who received an A (and it is impossible for a student to have two grades). As a result, they share the same characteristic or feature, which is grade.</p>
<p>So when you want to sample subjects based on shared characteristics, you should use stratified random sampling. This ensures that a member of a specific group will be included.</p>
<p>This is because stratified random sampling differs from simple random sampling, which is also a sampling technique. Stratified random sampling randomly samples out the population with no characteristics (that is, each subject of the population has equal chances of being picked).</p>
<p>As a result, simple random sampling cannot guarantee that a certain member of a particular group will be included in the sample.</p>
<p>Let's have a look at an example to see what we're talking about. Let's say we want to sample out 60% of students using both stratified and simple random sampling.</p>
<p>We can see the result for stratified random sampling below:</p>
<pre><code class="lang-python">df.groupby(<span class="hljs-string">'Grade'</span>, group_keys=<span class="hljs-literal">False</span>).apply(<span class="hljs-keyword">lambda</span> x: x.sample(frac=<span class="hljs-number">0.6</span>))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/image-39.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And this is the result of simple random sampling:</p>
<pre><code class="lang-python">df.sample(frac= <span class="hljs-number">0.6</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/image-40.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We can see that students with C grades are not included in the sample. This is because in simple random sampling, every observation has an equal chance of being chosen because we are not sampling based on characteristics. This means that there is a chance that an observation will not be chosen.</p>
<p>In stratified random sampling, on the other hand, we consider all the groups we want to sample and then randomly sample from each group.</p>
<h3 id="heading-2-imbalanced-dataset">2. Imbalanced Dataset:</h3>
<p>An imbalanced dataset is a machine learning classification problem in which the two class labels in the target variable are not proportional to one another. In other words, one class has a higher count than the other, resulting in an imbalance.</p>
<p>In machine learning, stratified sampling is also used to obtain the same sample proportion for a train and test set if there is an imbalance in the dataset.</p>
<p>For example, a chronic disease dataset has an imbalance label as shown below. You can click <a target="_blank" href="https://www.kaggle.com/datasets/mansoordaku/ckdisease/download?datasetVersionNumber=1">here</a> to download the dataset.</p>
<pre><code class="lang-python">df = pd.read_csv(<span class="hljs-string">"kidney_disease.csv"</span>)
df.head()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/image-41.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If we check the proportion label feature which is <code>classification</code>, we can see that it is imbalanced.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/image-42.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now let's say we want to split the train and test set using simple random sampling. We won't achieve the same proportion for the train and test set as the population proportion.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.model_selection <span class="hljs-keyword">import</span> train_test_split
X = df.drop(columns = [<span class="hljs-string">"classification"</span>])
y = df[<span class="hljs-string">"classification"</span>]
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=<span class="hljs-number">0.8</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/image-43.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We can see that the label proportion for both <code>y_train</code> and <code>y_test</code> is not the same as the population proportion. To achieve the same proportion we can make use of the <code>stratify</code> parameter in <code>train_test_split</code> as shown below:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> sklearn.model_selection <span class="hljs-keyword">import</span> train_test_split
X = df.drop(columns = [<span class="hljs-string">"classification"</span>])
y = df[<span class="hljs-string">"classification"</span>]
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=<span class="hljs-number">0.8</span>, stratify=y)
</code></pre>
<p>The above code shows that the dataset was stratified on the label. So with that we will achieve the same proportion as the population proportion.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/image-44.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we looked at stratified sampling and how you can use it in statistics and machine learning. We also looked at the types of stratified sampling.</p>
<p>Thank you for your time.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Population vs Sample – Statistics Example ]]>
                </title>
                <description>
                    <![CDATA[ When working with data sets and conducting a statistical analysis, you need to ensure that the data set you are using is relevant, valid, and correct. The appropriate data will help you make sure that you have a correct outcome and come to an effecti... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/population-vs-sample-statistics-example/</link>
                <guid isPermaLink="false">66b1e4618f7b9fe685bd613c</guid>
                
                    <category>
                        <![CDATA[ Math ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Tue, 12 Jul 2022 17:07:34 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/ruthson-zimmerman-FVwG5OzPuzo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When working with data sets and conducting a statistical analysis, you need to ensure that the data set you are using is relevant, valid, and correct.</p>
<p>The appropriate data will help you make sure that you have a correct outcome and come to an effective conclusion and solution that solves the problem at hand.</p>
<p>This is why it's necessary to know the difference between population data sets and sample data sets and whether the data you are dealing with is part of a population data set or a sample data set.</p>
<p>In this brief guide, you will learn the differences between these two popular statistical terms.</p>
<p>Let's get started!</p>
<h2 id="heading-what-is-a-population-in-statistics-population-definition">What Is A Population in Statistics? Population Definition</h2>
<p>A population is a collection that consists of all possible data values and items within the field of study. </p>
<p>A population refers to the whole number of items or the entire group of people that are of interest in the statistical study. </p>
<p>Essentially, it makes up the entire pool of the study.</p>
<p>An example of a population set is the number of all the people living in a country, such as all the number of people living in the U.S. – that is, the <em>entire population</em> of the U.S. . </p>
<p>Another example of working with a population set could be analyzing all the students in a university – this is the whole number of students studying at the University.</p>
<p>The quantity that describes the outcome of measuring the whole population is called a <em>parameter</em>. A parameter is a number that refers to the entire population.</p>
<h3 id="heading-which-method-should-you-use-to-collect-data-from-a-population">Which Method Should You Use to Collect Data from a Population?</h3>
<p>You may want to choose to collect data from a population when you need to work with a large amount of data.</p>
<p>A way of collecting data from an entire population is by conducting a census.</p>
<p>Let's take the U.S. census as an example. It's a procedure that takes place at least once every ten years.</p>
<p>It counts every person living in the U.S. and conducts a survey that collects data from all individuals and every member that makes up the population.</p>
<h3 id="heading-is-population-data-accurate">Is Population Data Accurate?</h3>
<p>Collecting data from a population is not the most efficient way of collecting data. </p>
<p>Populations are often hard to define and observe, which will inevitably introduce a bias in the study and probably skew the results and lead to unreliable conclusions.</p>
<p>There are a few reasons why this is the case:</p>
<ul>
<li>The pool of study is often too large.</li>
<li>There may be geographical constraints.</li>
<li>There may be time constraints.</li>
<li>There may be resource constraints</li>
<li>There may be accessibility constraints.</li>
<li>It is likely that there will be missing data values.</li>
</ul>
<p>Instead, you may choose to collect data from a population when the population size is relatively small. You can also gather information on the items/people that make up the population when it is easily accessible, or when you can measure the items or contact every member of the population.</p>
<h2 id="heading-what-is-a-sample-in-statistics-sample-definition">What Is a Sample in Statistics? Sample Definition</h2>
<p>A sample is a <em>subset</em> and a small portion of the population – a small part of all the possible data values that are part of the specified field of study. </p>
<p>The size of the sample data set will always be smaller than that of the population.</p>
<p>Working with sample data is helpful when the population is too large and not reliable.</p>
<p>For example, the population could be unknown in size, or even not measurable or infinite in size. </p>
<p>This is the preferred method of collecting data when the data you need is too hard to gather. It's a way to get information about the population without actually needing to access every person or item in that population.</p>
<p>The number that refers to the result of measuring from within a sample data set is called a statistic. A statistic describes a sample of a population.</p>
<h3 id="heading-what-are-the-defining-characteristics-of-a-good-sample">What Are the Defining Characteristics of a Good Sample?</h3>
<p>A sample should accurately represent the whole population. </p>
<p>One of the other most important characteristics of sample data is that it should be random and chosen without bias.</p>
<p>Insights and data should be collected randomly, meaning every item or member of a population has equal chances and the same probability of being selected.</p>
<p>Those two criteria reduce bias and ensure the results are valid.</p>
<h3 id="heading-how-is-data-collected-from-a-sample">How Is Data Collected from a Sample?</h3>
<p>The process of collecting data from a small subset of the population is known as sampling. </p>
<p>Sampling is helpful when it is difficult to collect all the necessary data from the population.</p>
<p>Sampling represents the entire population as it generalizes and reflects the individuals that are part of it.</p>
<p>Gathering all the necessary information and contacting the members of interest is easier, less time-consuming, and less costly.</p>
<p>A way to collect data from a sample is to conduct a poll, which is what happens during an election period. </p>
<p>Polls are a helpful tool for gauging voters' preferences and support of the parties taking part in the election.</p>
<p>It's impossible to gather all registered voters in the country and ask who they prefer to win the election since they might be in the millions.</p>
<p>Instead, it is better to gather several thousand responses from different sections of the population, such as from various cities and regions and from unrelated spots within those cities and regions.</p>
<p>This selection needs to be random, and people need to be chosen by chance. This ideally means that everyone should equally have the same chance of being picked for the poll.</p>
<h3 id="heading-what-is-sampling-bias-and-how-to-avoid-it">What Is Sampling Bias and How to Avoid It</h3>
<p>As mentioned earlier, a sample should accurately represent and reflect the entire population from which it has been taken.</p>
<p>For the sample to be representative, it should be gathered randomly. If not, the result of the analysis will most likely be prone to bias or what is otherwise known as sampling bias.</p>
<p>Sampling bias occurs when the methods used to collect the sample encourage systemic prejudice.  </p>
<p>The methods are either in favor of or against an individual or group, which will inevitably skew the outcome of the analysis. Members of the specific population are not selected correclty, meaning they either have a higher or lower chance of being selected.</p>
<p>Essentially, the sample is collected in a way that unfairly favors only certain members of the population over others.</p>
<p>For example, a survey that questions students at the University’s cafe regarding their University experience excludes various groups of students.</p>
<p>It excludes:</p>
<ul>
<li>Students who are distance learning and studying from home.<ul>
<li>Students who may be studying part-time and working at the time the survey took place.</li>
<li>Students on an exchange program in a different country.</li>
</ul>
</li>
<li>Students in a class following a lecture.</li>
</ul>
<p>Firstly, this method is not random. Secondly, it is prone to sampling bias as it is limiting and favors only the section of students that were able to be present in the cafe during morning hours and therefore is not representative. </p>
<p>These students may have specific characteristics and probably do not reflect the overall population of students in the whole University.</p>
<p>Let's take another example.</p>
<p>Say that a poll is conducted during an election period to find out which candidate is the most favorable to the public.</p>
<p>If the members polled are only white collar workers, the results will be inaccurate since it doesn't accurately describe the entire population.</p>
<p>The population also includes blue-collar workers and people who might work more than one minimum wage job to make ends meet. The preferences for the candidate will likely differ from group to group.</p>
<p>In this case, the bias is heavy since the poll is not diverse – it reflects only one section of the population.</p>
<p>A way to lower the risk of sampling bias is through stratified random sampling. </p>
<p>Stratified random sampling involves accurately defining the population of interest, the characteristics it needs to have, and how you want it divided. </p>
<p>It also involves choosing your sample size and then dividing the sample into precise, homogenous smaller sub-groups that match the relevant criteria you set while ensuring the population and sample match. </p>
<p>Stratified random sampling leads to a more representative sample.</p>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>And there you have it! You now have a high-level understanding of the differences between two widely used statistical terms - population and sample.</p>
<p>To learn more about Statistics, check out <a target="_blank" href="https://www.freecodecamp.org/news/free-statistics-course/">this free 8-hour course</a> from freeCodeCamp.</p>
<p>Thank you for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Detect Outliers in Machine Learning – 4 Methods for Outlier Detection ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever trained a machine learning model on a real-world dataset? If yes, you’ll have likely come across outliers.  Outliers are those data points that are significantly different from the rest of the dataset. They are often abnormal observatio... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-detect-outliers-in-machine-learning/</link>
                <guid isPermaLink="false">66bb8b33d2bda3e43154919c</guid>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Math ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bala Priya C ]]>
                </dc:creator>
                <pubDate>Tue, 05 Jul 2022 22:02:13 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/Outlier-Detection.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever trained a machine learning model on a real-world dataset? If yes, you’ll have likely come across <em>outliers</em>. </p>
<p>Outliers are those data points that are <em>significantly</em> different from the rest of the dataset. They are often abnormal observations that skew the data distribution, and arise due to inconsistent data entry, or erroneous observations.</p>
<p>To ensure that the trained model generalizes well to the valid range of test inputs, it’s important to detect and remove outliers.</p>
<p>In this guide, we’ll explore some statistical techniques that are widely used for outlier detection and removal.</p>
<h2 id="heading-why-should-you-detect-outliers">Why Should You Detect Outliers?</h2>
<p>In the machine learning pipeline, <em>data cleaning</em> <em>and preprocessing</em> is an important step as it helps you better understand the data. During this step, you deal with missing values, detect outliers, and more.</p>
<p>As outliers are very different values—abnormally low or abnormally high—their presence can often skew the results of statistical analyses on the dataset. This could lead to less effective and less useful models.</p>
<p>But dealing with outliers often requires domain expertise, and none of the outlier detection techniques should be applied <em>without</em> understanding the data distribution and the use case.</p>
<p>For example, in a dataset of house prices, if you find a <em>few</em> houses priced at around $1.5 million—much higher than the median house price, they’re likely outliers. However, if the dataset contains a significantly large number of houses priced at $1 million and above—they may be indicative of an increasing trend in house prices. So it would be <em>incorrect</em> to label them all as outliers. In this case, you need some knowledge of the real estate domain.</p>
<p>The goal of outlier detection is to remove the points—which are truly outliers—so you can build a model that performs well on unseen test data. We’ll go over a few techniques that’ll help us detect outliers in data.</p>
<h2 id="heading-how-to-detect-outliers-using-standard-deviation">How to Detect Outliers Using Standard Deviation</h2>
<p>When the data, or certain features in the dataset, follow a <a target="_blank" href="https://mathworld.wolfram.com/NormalDistribution.html">normal distribution</a>, you can use the standard deviation of the data, or the equivalent z-score to detect outliers.</p>
<p>In statistics, standard deviation measures the <em>spread of data around the mean</em>, and in essence, it captures how far away from the mean the data points are. </p>
<p>For data that is normally distributed, around 68.2% of the data will lie within one standard deviation from the mean. Close to 95.4% and 99.7% of the data lie within two and three standard deviations from the mean, respectively. </p>
<p>Let’s denote the standard deviation of the distribution by σ, and the mean by μ.</p>
<p>One approach to outlier detection is to set the <em>lower</em> limit to three standard deviations below the mean (μ - 3<em>σ), and the <em>upper</em> limit to three standard deviations above the mean (μ + 3</em>σ). Any data point that falls outside this range is detected as an outlier. </p>
<p>As 99.7% of the data typically lies within three standard deviations, the number of outliers will be close to 0.3% of the size of the dataset.</p>
<h3 id="heading-code-for-outlier-detection-using-standard-deviation">Code for Outlier Detection Using Standard Deviation</h3>
<p>Now, let's create a normally-distributed dataset of student scores, and perform outlier detection on it.</p>
<p>As a first step, we’ll import the necessary modules.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> pandas <span class="hljs-keyword">as</span> pd
<span class="hljs-keyword">import</span> seaborn <span class="hljs-keyword">as</span> sns
</code></pre>
<p>Next, let’s define the function <code>generate_scores()</code> that returns a normally-distributed dataset of student scores containing 200 records. We’ll make a call to the function, and store the returned array in the variable <code>scores_data</code>.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">generate_scores</span>(<span class="hljs-params">mean=<span class="hljs-number">60</span>,std_dev=<span class="hljs-number">12</span>,num_samples=<span class="hljs-number">200</span></span>):</span>
    np.random.seed(<span class="hljs-number">27</span>)
    scores = np.random.normal(loc=mean,scale=std_dev,size=num_samples)
    scores = np.round(scores, decimals=<span class="hljs-number">0</span>)
    <span class="hljs-keyword">return</span> scores
scores_data = generate_scores()
</code></pre>
<p>You can use Seaborn’s <code>displot()</code> function to visualize the data distribution. In this case, the dataset follows a normal distribution, as seen in the figure below.</p>
<pre><code class="lang-python">sns.set_theme()
sns.displot(data=scores_data).set(title=<span class="hljs-string">"Distribution of Scores"</span>, xlabel=<span class="hljs-string">"Scores"</span>)
</code></pre>
<p><img src="https://lh6.googleusercontent.com/EqfsNr10SYnFcCpdC_5Bdt9Z3jWIsaTI1yCcATGbf10BXTwwqKuJHUMuZT9n6M3bGuU8k4QOA8Vb87BStDzxQRRdQ-MzMwLT2EZZJL4ieB0_u0LnvsUXCkYBTllcll15mF1oGziS1QqZrfYR5A" alt="Image" width="348" height="381" loading="lazy">
<em>Figure 1: Normal Distribution of Scores</em></p>
<p>Next, let's load the data into a <a target="_blank" href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html">Pandas dataframe</a> for further analysis.</p>
<pre><code class="lang-python">df_scores = pd.DataFrame(scores_data,columns=[<span class="hljs-string">'score'</span>])
</code></pre>
<p>To obtain the mean and standard deviation of the data in the dataframe <code>df_scores</code>, you can use the <code>.mean()</code> and the <code>.std()</code> methods, respectively. </p>
<pre><code class="lang-python">df_scores.mean()
<span class="hljs-comment"># Output</span>
score    <span class="hljs-number">61.005</span>
dtype: float64
df_scores.std()
<span class="hljs-comment"># Output</span>
score    <span class="hljs-number">11.854434</span>
dtype: float64
</code></pre>
<p>As discussed earlier, set the lower limit (<code>lower_limit</code>) to be three standard deviations below the mean, and the upper limit (<code>upper_limit</code>) to be three standard deviations above the mean.</p>
<pre><code class="lang-python">lower_limit = df_scores.mean() - <span class="hljs-number">3</span>*df_scores.std()
upper_limit = df_scores.mean() + <span class="hljs-number">3</span>*df_scores.std()
print(lower_limit)
print(upper_limit)
<span class="hljs-comment"># Output</span>
<span class="hljs-number">25.530716709142666</span>
<span class="hljs-number">96.47928329085734</span>
</code></pre>
<p>Now that you’ve defined the lower and upper limits, you may filter the dataframe <code>df_scores</code> to only retain the data points in the interval <code>[lower_limit, upper_limit]</code>, as shown below.</p>
<pre><code class="lang-python">df_scores_filtered=df_scores[(df_scores[<span class="hljs-string">'score'</span>]&gt;lower_limit)&amp;(df_scores[<span class="hljs-string">'score'</span>]&lt;upper_limit)]
print(df_scores_filtered)
<span class="hljs-comment"># Output</span>
score
<span class="hljs-number">0</span>     <span class="hljs-number">75.0</span>
<span class="hljs-number">1</span>     <span class="hljs-number">56.0</span>
<span class="hljs-number">2</span>     <span class="hljs-number">67.0</span>
<span class="hljs-number">3</span>     <span class="hljs-number">65.0</span>
<span class="hljs-number">4</span>     <span class="hljs-number">63.0</span>
..     ...
<span class="hljs-number">194</span>   <span class="hljs-number">42.0</span>
<span class="hljs-number">195</span>   <span class="hljs-number">76.0</span>
<span class="hljs-number">196</span>   <span class="hljs-number">67.0</span>
<span class="hljs-number">197</span>   <span class="hljs-number">74.0</span>
<span class="hljs-number">199</span>   <span class="hljs-number">53.0</span>
[<span class="hljs-number">198</span> rows x <span class="hljs-number">1</span> columns]
</code></pre>
<p>From the output above, you can see that two records have been removed, and <code>df_scores_filtered</code> contains 198 records.</p>
<h2 id="heading-how-to-detect-outliers-using-the-z-score">How to Detect Outliers Using the Z-Score</h2>
<p>Now let's explore the concept of the z-score. For a normal distribution with mean μ and standard deviation σ, the z-score for a value x in the dataset is given by:</p>
<p><strong>z = (x - μ)/σ</strong></p>
<p>From the above equation, we have the following:</p>
<ul>
<li>When x = μ, the value of z-score is 0.</li>
<li>When x = μ ± 1, μ ± 2, or μ ± 3, the z-score is ± 1, ± 2, or ± 3, respectively.</li>
</ul>
<p>Notice how this technique is equivalent to the scores based on standard deviation we had earlier. Under this transformation, all data points that lie below the lower limit, μ - 3*σ, now map to points that are less than -3 on the z-score scale.</p>
<p>Similarly, all points that lie above the upper limit, μ + 3*σ map to a value above 3 on the z-score scale. So <code>[lower_limit, upper_limit]</code> becomes [-3, 3].</p>
<p>Let’s use this technique on our dataset of scores.</p>
<h3 id="heading-code-for-outlier-detection-using-z-score">Code for Outlier Detection Using Z-Score</h3>
<p>Let's compute z-scores for all points in the dataset, and add z_score as a column to the dataframe <code>df_scores</code>.</p>
<pre><code class="lang-python">df_scores[<span class="hljs-string">'z_score'</span>]=(df_scores[<span class="hljs-string">'score'</span>] - df_scores[<span class="hljs-string">'score'</span>].mean())/df_scores[<span class="hljs-string">'score'</span>].std()
df_scores.head()
<span class="hljs-comment"># Output</span>
score    z_score
<span class="hljs-number">0</span>    <span class="hljs-number">75.0</span>    <span class="hljs-number">1.180571</span>
<span class="hljs-number">1</span>    <span class="hljs-number">56.0</span>    <span class="hljs-number">-0.422205</span>
<span class="hljs-number">2</span>    <span class="hljs-number">67.0</span>    <span class="hljs-number">0.505718</span>
<span class="hljs-number">3</span>    <span class="hljs-number">65.0</span>    <span class="hljs-number">0.337005</span>
<span class="hljs-number">4</span>    <span class="hljs-number">63.0</span>    <span class="hljs-number">0.168291</span>
</code></pre>
<p>You can filter the dataframe <code>df_scores</code> to retain points whose z-scores are in the range [-3, 3], as shown below. The filtered dataframe contains 198 records, as expected.</p>
<pre><code class="lang-python">df_scores_filtered= df_scores[(df_scores[<span class="hljs-string">'z_score'</span>]&gt;<span class="hljs-number">-3</span>) &amp; (df_scores[<span class="hljs-string">'z_score'</span>]&lt;<span class="hljs-number">3</span>)]

print(df_scores_filtered)

<span class="hljs-comment"># Output</span>
     score   z_score

<span class="hljs-number">0</span>     <span class="hljs-number">75.0</span>  <span class="hljs-number">1.180571</span>

<span class="hljs-number">1</span>     <span class="hljs-number">56.0</span> <span class="hljs-number">-0.422205</span>

<span class="hljs-number">2</span>     <span class="hljs-number">67.0</span>  <span class="hljs-number">0.505718</span>

<span class="hljs-number">3</span>     <span class="hljs-number">65.0</span>  <span class="hljs-number">0.337005</span>

<span class="hljs-number">4</span>     <span class="hljs-number">63.0</span>  <span class="hljs-number">0.168291</span>

..     ...       ...

<span class="hljs-number">194</span>   <span class="hljs-number">42.0</span> <span class="hljs-number">-1.603198</span>

<span class="hljs-number">195</span>   <span class="hljs-number">76.0</span>  <span class="hljs-number">1.264928</span>

<span class="hljs-number">196</span>   <span class="hljs-number">67.0</span>  <span class="hljs-number">0.505718</span>

<span class="hljs-number">197</span>   <span class="hljs-number">74.0</span>  <span class="hljs-number">1.096214</span>

<span class="hljs-number">199</span>   <span class="hljs-number">53.0</span> <span class="hljs-number">-0.675275</span>


[<span class="hljs-number">198</span> rows x <span class="hljs-number">2</span> columns]
</code></pre>
<p>The methods involving standard deviation and z-scores can be used only when the data set, or the feature that you are examining, follows a normal distribution. </p>
<p>Next, we’ll discuss two outlier detection techniques that can be used <em>independently</em> of the data distribution.</p>
<h2 id="heading-how-to-detect-outliers-using-the-interquartile-range-iqr">How to Detect Outliers Using the Interquartile Range (IQR)</h2>
<p>In statistics, interquartile range or IQR is a quantity that measures the difference between the first and the third quartiles in a given dataset. </p>
<ul>
<li>The first quartile is also called the one-fourth quartile, or the 25% quartile.</li>
<li>If <code>q25</code> is the first quartile, it means 25% of the points in the dataset have values less than <code>q25</code>.</li>
<li>The third quartile is also called the three-fourth, or the 75% quartile.</li>
<li>If <code>q75</code> is the three-fourth quartile, 75% of the points have values less than <code>q75</code>.</li>
<li>Using the above notations, <code>IQR = q75 - q25</code>.</li>
</ul>
<h3 id="heading-code-for-outlier-detection-using-interquartile-range-iqr">Code for Outlier Detection Using Interquartile Range (IQR)</h3>
<p>You can use the box plot, or the box and whisker plot, to explore the dataset and visualize the presence of outliers. The points that lie beyond the whiskers are detected as outliers.</p>
<p>You can generate box plots in Seaborn using the <code>boxplot</code> function.</p>
<pre><code class="lang-python">sns.boxplot(data=scores_data).set(title=<span class="hljs-string">"Box Plot of Scores"</span>)
</code></pre>
<p><img src="https://lh6.googleusercontent.com/PwEktzeOWRSXfPHTG1WBtFkLA536gNo56REH-5_MYnIpO2r01EeI-QGrTuznsticijoik534i-4ylgP0PDUMUmSm3EaOfl7gXQjOUCVw5XQqPWt9AkY_vpbqODMGSpW7CJ8ST2duYamvREoICA" alt="Image" width="379" height="267" loading="lazy">
<em>Figure 2: Box Plot of Scores</em></p>
<p>Now, call the describe method on the dataframe <code>df_scores</code>.</p>
<pre><code class="lang-python">df_scores.describe()
<span class="hljs-comment"># Output</span>
score
count    <span class="hljs-number">200.000000</span>
mean    <span class="hljs-number">61.005000</span>
std        <span class="hljs-number">11.854434</span>
min        <span class="hljs-number">20.000000</span>
<span class="hljs-number">25</span>%        <span class="hljs-number">54.000000</span>
<span class="hljs-number">50</span>%        <span class="hljs-number">62.000000</span>
<span class="hljs-number">75</span>%        <span class="hljs-number">67.000000</span>
max        <span class="hljs-number">98.000000</span>
</code></pre>
<p>We use the 25% and 75% quartile values from the above result to compute IQR, and subsequently set the lower and upper limits to filter <code>df_scores</code>. </p>
<pre><code class="lang-python">IQR = <span class="hljs-number">67</span><span class="hljs-number">-54</span>
lower_limit = <span class="hljs-number">54</span> - <span class="hljs-number">1.5</span>*IQR
upper_limit = <span class="hljs-number">67</span> + <span class="hljs-number">1.5</span>*IQR
print(upper_limit)
print(lower_limit)
<span class="hljs-comment"># Output</span>
<span class="hljs-number">86.5</span>
<span class="hljs-number">34.5</span>
</code></pre>
<p>As a next step, filter the dataframe <code>df_scores</code> to retain records that lie in the permissible range.</p>
<pre><code class="lang-python">df_scores_filtered = df_scores[(df_scores[<span class="hljs-string">'score'</span>]&gt;lower_limit) &amp; (df_scores[<span class="hljs-string">'score'</span>]&lt;upper_limit)]
print(df_scores_filtered)
<span class="hljs-comment"># Output</span>
score
<span class="hljs-number">0</span>     <span class="hljs-number">75.0</span>
<span class="hljs-number">1</span>     <span class="hljs-number">56.0</span>
<span class="hljs-number">2</span>     <span class="hljs-number">67.0</span>
<span class="hljs-number">3</span>     <span class="hljs-number">65.0</span>
<span class="hljs-number">4</span>     <span class="hljs-number">63.0</span>
..     ...
<span class="hljs-number">194</span>   <span class="hljs-number">42.0</span>
<span class="hljs-number">195</span>   <span class="hljs-number">76.0</span>
<span class="hljs-number">196</span>   <span class="hljs-number">67.0</span>
<span class="hljs-number">197</span>   <span class="hljs-number">74.0</span>
<span class="hljs-number">199</span>   <span class="hljs-number">53.0</span>
[<span class="hljs-number">192</span> rows x <span class="hljs-number">1</span> columns]
</code></pre>
<p>As seen in the output, this method labels eight points as outliers, and the filtered dataframe is 192 records long.</p>
<p>You don't always have to call the describe method to identify the quartiles. You may instead use the <code>percentile()</code> function in <a target="_blank" href="https://numpy.org/doc/stable/user/index.html#user">NumPy</a>. It takes in two arguments, <code>a</code>: an array or a dataframe and <code>q</code>: a list of quartiles. </p>
<p>The code cell below shows how you can calculate the first and the third quartiles using the percentile function.</p>
<pre><code class="lang-python">q25,q75 = np.percentile(a = df_scores,q=[<span class="hljs-number">25</span>,<span class="hljs-number">75</span>])
IQR = q75 - q25
print(IQR)
<span class="hljs-comment"># Output</span>
<span class="hljs-number">13.0</span>
</code></pre>
<h2 id="heading-how-to-detect-outliers-using-percentile">How to Detect Outliers Using Percentile</h2>
<p>In the previous section, we explored the concept of interquartile range, and its application to outlier detection. You can think of percentile as an extension to the interquartile range. </p>
<p>As discussed earlier, the interquartile range works by dropping all points that are outside the range <code>[q25 - 1.5*IQR, q75 + 1.5*IQR]</code> as outliers. But removing outliers this way may not be the most optimal choice when your observations have a <em>wide</em> distribution. And you may be discarding more points—than you <em>actually</em> should—as outliers. </p>
<p>Depending on the domain, you may want to widen the range of permissible values to estimate the outliers better. Next, let’s revisit the scores dataset, and use percentile to detect outliers.</p>
<h3 id="heading-code-for-outlier-detection-using-percentile">Code for Outlier Detection Using Percentile</h3>
<p>Let’s define a custom range that accommodates all data points that lie anywhere between 0.5 and 99.5 percentile of the dataset. To do this, set <code>q = [0.5, 99.5]</code> in the percentile function, as shown below.</p>
<pre><code class="lang-python">lower_limit, upper_limit = np.percentile(a=df_scores,q=[<span class="hljs-number">0.5</span>,<span class="hljs-number">99.5</span>])
print(upper_limit)
print(lower_limit)

<span class="hljs-comment"># Output</span>
<span class="hljs-number">91.035</span>
<span class="hljs-number">28.955</span>
</code></pre>
<p>Next, you may filter the dataframe using the lower and upper limits obtained from the previous step.</p>
<pre><code class="lang-python">df_scores_filtered = df_scores[(df_scores[<span class="hljs-string">'score'</span>]&gt;lower_limit) &amp; (df_scores[<span class="hljs-string">'score'</span>]&lt;upper_limit)]
print(df_scores_filtered)

<span class="hljs-comment"># Output</span>
score
<span class="hljs-number">0</span>     <span class="hljs-number">75.0</span>
<span class="hljs-number">1</span>     <span class="hljs-number">56.0</span>
<span class="hljs-number">2</span>     <span class="hljs-number">67.0</span>
<span class="hljs-number">3</span>     <span class="hljs-number">65.0</span>
<span class="hljs-number">4</span>     <span class="hljs-number">63.0</span>
..     ...
<span class="hljs-number">194</span>   <span class="hljs-number">42.0</span>
<span class="hljs-number">195</span>   <span class="hljs-number">76.0</span>
<span class="hljs-number">196</span>   <span class="hljs-number">67.0</span>
<span class="hljs-number">197</span>   <span class="hljs-number">74.0</span>
<span class="hljs-number">199</span>   <span class="hljs-number">53.0</span>
[<span class="hljs-number">198</span> rows x <span class="hljs-number">1</span> columns]
</code></pre>
<p>From the code cell above, you can see that there are two outliers, and the filtered dataframe has 198 data records.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this guide, we covered what outliers are, and why we need to detect them. We then went over the most common techniques for outlier detection.</p>
<p>Here’s a summary:</p>
<ul>
<li>If the data, or feature of interest is normally distributed, you may use standard deviation and z-score to label points that are farther than three standard deviations away from the mean as outliers.</li>
<li>If the data is not normally distributed, you can use the interquartile range or percentage methods to detect outliers.</li>
</ul>
<p>In addition, we discussed the best practices in outlier detection. When a large fraction of data is being labeled as outliers, they are not really outliers but can be attributed to a wider data distribution. </p>
<p>In applying all of the above techniques, it's also important to be aware of the current trend to identify how certain values are evolving, and check for permissible lower and upper limits using domain knowledge.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Statistics for Beginners – Top Stats Concepts to Know Before Getting into Data Science ]]>
                </title>
                <description>
                    <![CDATA[ You've probably heard that statistics is the gateway to data science and that the data science map starts with stats. Perhaps you've also heard from others that you have to learn statistics before learning data science. But then you ponder, "Since I'... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/top-statistics-concepts-to-know-before-getting-into-data-science/</link>
                <guid isPermaLink="false">66d45f4247a8245f78752a62</guid>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ibrahim Ogunbiyi ]]>
                </dc:creator>
                <pubDate>Fri, 10 Jun 2022 16:33:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/who-s-denilo-3ECPkzvwlBs-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You've probably heard that statistics is the gateway to data science and that the data science map starts with stats.</p>
<p>Perhaps you've also heard from others that you have to learn statistics before learning data science. But then you ponder, "Since I'm not from a technical background like science, technology, engineering, or math (STEM), do I need to learn everything in statistics before getting into data science?" And those same people will tell you "Yes! You have to learn statistics."</p>
<p>Well, here's my answer: you don't need to learn all of statistics before beginning data science (though you do need to learn some fundamentals).</p>
<p>You can also learn as you go instead of wasting time learning statistics first before data science (that is, as you advance in your knowledge of data science, you can always learn more statistics concepts).</p>
<p>That being said, it is helpful to know statistics basics before jumping into data science. You can indeed say that stats is the gateway to data science because it will help you to have some intuition about your data and how to work with it.</p>
<p>In this article, we'll look at the top statistical concepts you need to know before diving into data science. I'll make it as simple as possible even if you don't come from a technical background. I can tell you're excited and ready to dive into the realm of data science. Let's get started.</p>
<h1 id="heading-what-is-statistics">What is Statistics?</h1>
<p>According to economist and sampling technique pioneer Arthur Lyon Bowley, Statistics is:</p>
<blockquote>
<p>"numerical statements of facts in any department of inquiry placed in relation to each other."</p>
</blockquote>
<p>That basically means that statistics helps us comprehend our data and also helps us convey the results in that data to others.</p>
<p>Statistical methods (that is, the techniques employed in dealing with data in statistics) are classified into two types:</p>
<ol>
<li><p>Descriptive Statistics</p>
</li>
<li><p>Inferential Statistics</p>
</li>
</ol>
<p><strong>Descriptive Statistics</strong> is a discipline of statistics that assists us in summarizing data through numerical values or graphical visualization.</p>
<p>Descriptive statistics helps us identify and understand some key properties in our data. It includes concepts such as central tendency, dispersion, boxplots, histograms, and so on, which we'll discuss later in the article.</p>
<p><strong>Inferential Statistics,</strong> on the other hand, is a branch of statistics that helps us make decisions or predictions based on the data that we have gathered.</p>
<p>Inferential statistics is a significantly more advanced topic because it requires a deep understanding of descriptive statistics. It includes concepts such as hypothesis, probability, and so forth.</p>
<h1 id="heading-top-statistical-concepts-to-know-before-learning-data-science">Top Statistical Concepts to Know Before Learning Data Science</h1>
<p>Since you're now familiar with the definition of statistics, let's have a look at some of the concepts you'll need to know in statistics that'll help guide you when you dive into the realm of statistics.</p>
<p>Among the most fundamental concepts are:</p>
<h2 id="heading-what-is-a-subject">What is a Subject?</h2>
<p>This is the specific thing we wish to observe. It could be a person, an animal, or something else. It is also known as observation.</p>
<h2 id="heading-what-is-a-population">What is a Population?</h2>
<p>Population refers to the entire set of topics in which we are interested (that is, that we want to observe). Assume you wish to count the number of females in a specific country.</p>
<h2 id="heading-what-is-a-sample">What is a Sample?</h2>
<p>In reality, observing a population is hardly an ideal situation (because it can be very expensive to perform, and also time-consuming).</p>
<p>Consider the following scenario: you wish to observe every female in the world. This type of observation can be costly to carry out. However, in statistics, we have something called a sample, which is a portion/subset of the population that you want to study. We can now make a decision (inferential statistic) about the full population using the sample.</p>
<h2 id="heading-what-are-parameters">What are Parameters?</h2>
<p>This is a property/summary of a population. Consider the following scenario: you are observing the entire country and you discover that 90% of the inhabitants are males while 10% are females. The numerical values, 90%, and 10% are a numerical summary (that is, descriptive statistics) of the entire population. As a result, the summary is known as the population parameter.</p>
<h2 id="heading-what-is-a-statistic">What is a Statistic?</h2>
<p>On the other hand, a statistic (not to be confused with statistic(s)) is about a sample's property. As stated in the preceding example, instead of working with the full population, we work with samples, so the numerical value is referred to as the statistic of the sample.</p>
<p>Hopefully you now have a decent understanding of what population, sample, statistic, and parameters are. Let's take a look at another concept with which we are all too familiar: <strong>"Data"</strong>.</p>
<p><strong>Data</strong>, as the term implies, represents factual information. That is, it conveys a message to us. It can, however, be divided into two categories:</p>
<ol>
<li><p>Quantitative data.</p>
</li>
<li><p>Qualitative data.</p>
</li>
</ol>
<h2 id="heading-what-is-quantitative-data">What is Quantitative Data?</h2>
<p>This is also known as numerical data. These data are a sort of data in which numerical values can be counted or measured. Quantitative data can be further classified into two types:</p>
<p><strong>Quantitative discrete data:</strong> These are numerical data that can be counted but cannot be measured. Counting the number of shoes in a shoe store is a common example.</p>
<p><strong>Quantitative continuous data:</strong> This is a type of numerical data that is based on measurement. For example, measuring the weight of a glass cylinder is continuous, not discrete.</p>
<h2 id="heading-what-is-qualitative-data">What is Qualitative Data?</h2>
<p>These are sorts of data that represent categories or groups of data. They are also known as categorical data. They are usually written in text. They can be characteristics, names, or anything else.</p>
<p>A common example is a person's name, dog breeds, and so on. However, there are some data that appear to be numerical data but are encoded as categorical data.</p>
<p>For example, suppose you wanted to group a certain group of people based on their age and discovered that the lowest and highest ages are 10 and 60, respectively. You then divided the ages into 5 categories (10-20, 21-30, 31-40, 41-50, 51-60) and assigned numerical values to each of those categories where 1 represents 10-20, 2 represents 21-30, and so on.</p>
<p>In this situation, the numerical values will be handled as categorical data rather than quantitative data. As your data science career progresses, you will learn how to work with categorical data.</p>
<p>Now you know the categories of data. Quantitative and qualitative data can be treated in statistics using these levels of measurement. Data in statistics can be classified into 4 levels of measurement which are:</p>
<ol>
<li><p>Nominal scale data</p>
</li>
<li><p>Ordinal Scale data</p>
</li>
<li><p>Interval Scale data</p>
</li>
<li><p>Ratio Scale data</p>
</li>
</ol>
<p>Qualitative data can be measured using:</p>
<p><strong>Nominal scale data:</strong> These are the type of categorical data that do not have an ordered sense. That is, they cannot be ordered.</p>
<p>Each piece of data represents a single unit. An example of such categorical data includes color. It is not very ideal to rank blue over yellow. When working with nominal data, each data point must be handled as a separate unit.</p>
<p><strong>Ordinal Scale data:</strong> Ordinal Scale data consists of ordered categorical data. When data is ranked, there is a sense of order in it. A survey response such as excellent, good, satisfactory, and unsatisfactory is an example of this. It makes sense to rank excellence above good.</p>
<p>Quantitative data can be measured using:</p>
<p><strong>Interval Scale Data:</strong> These are numerical data with ordering and can be measured (for example find the difference between the data). The readings on a temperature scale are an example of interval data.</p>
<p>For example, you can measure the difference between 4 and 10 degrees Celsius, and 10 degrees is higher than 4 degrees. However, there are two exceptions for interval scale data:</p>
<ol>
<li><p>It does not have a starting point (that is, it does not begin from zero and you can have a temperature value below zero)</p>
</li>
<li><p>You can't figure out their ratio: For example, it makes no logic to claim that 4 times 20 degrees Celsius is 80 degrees Celsius.</p>
</li>
</ol>
<p><strong>Ratio Scale data</strong>: These are numerical data that have the features of interval scale data (that is they may be ordered and measured), but also solve the exception of interval scale data (they have a starting point, and also you can find the ratio between them).</p>
<p>A grade score of 20, 68, 90, or 80 is an example. We can order it, measure it, and find the ratio between the values. It makes sense to say the score of 80 is 4 times better than the score of 20.</p>
<p>Now that we've covered the fundamentals of data, let's look at how the first category of statistics (descriptive statistics) can be applied to data.</p>
<p>As previously stated, descriptive statistics require summarizing data either numerically or graphically. Let's take a look at some of the most typical numerical and graphical summaries you'll encounter when dealing with data on a regular basis.</p>
<h2 id="heading-mean-vs-median-vs-mode-what-is-the-difference">Mean vs Median vs Mode – What is the Difference?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Visualisation_mode_median_mean.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Mean, Median, and Mode explained through illustration. Mode is the high point, Median is the half way point, and Mean is the average.</em></p>
<h3 id="heading-what-is-a-mean">What is a Mean?</h3>
<p>When we have a set of numerical data like this (4, 5, 6, 7, 10), each value in the set of data is referred to as a data point. We might want to find the data's average value.</p>
<p>So mean is essentially the average of a set of data and is calculated as the sum of all the data points divided by the total number of data points.</p>
<p>In our above data set, their sum is 32 and the total number of data points is 5. So the average number, that is the mean, is 6.4</p>
<p>Mean is only used on numerical data. Finding the average of our category data is impractical.</p>
<h3 id="heading-what-is-a-median">What is a Median?</h3>
<p>Also, given a group of values, we may want to discover the value in the center. The median is used to compute the value in the middle. Median also is used on numerical data only.</p>
<h3 id="heading-what-is-a-mode">What is a Mode?</h3>
<p>This is the value with the highest frequency (that is a value that has the highest number of occurrences). The mode can be used for numerical or categorical data.</p>
<h2 id="heading-what-is-an-outlier">What is an Outlier?</h2>
<p>Outliers are data points that differ from other data points and, when present, can lead us to incorrect conclusions. Here's a typical example of how outliers are harmful.</p>
<p>Consider the following scenario: you have a machine that counts how many customers enter your supermarket every day, and the readings are thus for a given week (20, 23, 26, 27, 302). We can see that the number 302 is an outlier because it deviates significantly from the other data points.</p>
<p>Outliers could have resulted from a sudden change, machine faults, or other circumstances. However, when they are present, they can lead us to make incorrect decisions, such as if you want to find the average number of consumers who visit your supermarket, the value 302 may lead you to an incorrect result. The mean of the preceding values is 75.</p>
<h2 id="heading-what-is-a-standard-deviation">What is a Standard Deviation?</h2>
<p>A Standard Deviation is a summary value that indicates how far our data point deviates from the mean. It is used to determine the spread of our data.</p>
<p>The closer the standard deviation is to zero, the closer our data points are to one another.</p>
<p>The standard deviation is an extremely valuable summary that informs us that we have some outliers in our dataset. Here's how it works:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/1920px-Standard_deviation_diagram.svg.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A chart of a Normal Distribution, with the number of standard deviations listed on the x axis.</em></p>
<p>In the above chart, we see a Normal Distribution. 34.1% + 34.1% = 68.2% of all observations are within one standard deviation, or 1σ (pronounced one Sigma).</p>
<p>13.6% + 13.6% = 27.2% of the remaining observations are within two standard deviations, or 2σ. And so on.</p>
<p>And yes, if you've heard of Six Sigma, that is a concept in engineering where six standard deviation's worth of possibilities are accounted for in the quality assurance process. Meaning you are accounting for all but the most extreme outliers. 99.99966% of all possibilities, to be exact.</p>
<p>Now that we've grasped some numerical summaries, let's take a look at some common graphical summaries.</p>
<h2 id="heading-what-is-a-bar-chart">What is a Bar Chart?</h2>
<p>A bar chart is a type of data visualization used for categorical data. You use it to graphically show the frequency of categorical data (that is the number of times a categorical data point occurs). Here's an example:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/download-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-what-is-a-histogram">What is a Histogram?</h2>
<p>A histogram is similar to a bar chart in that it shows the frequency of your numerical data called height, but it groups the numerical data points into bins or ranges.</p>
<p>It is a very efficient visualization tool because it helps you visualize the distribution of your numerical data. You can read more <a target="_blank" href="https://www.cuemath.com/data/histograms/">here</a> to learn more about histograms.</p>
<p><img alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-what-is-a-boxplot">What is a Boxplot?</h2>
<p>Another excellent visualization that helps you visualize the distribution of your data is the boxplot.</p>
<p>A boxplot, for example, allows you to visually observe if there are any outliers in your data collection. It includes terms such as minimum, 25th percentile, 50th percentile, 75th percentile, and maximum. A Boxplot looks as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/OutliersAnomalies--1-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Image by Ibrahim Ogunbiyi</em></p>
<p>So let’s go over what we have in the above diagram:</p>
<p><strong>Minimum</strong>: The minimum value does not imply the smallest value in our dataset. It is calculated using this formula ( Q1 -1.5*IQR) where:</p>
<ul>
<li><p>Q1 – implies The 25th percentile</p>
</li>
<li><p>IQR – implies the Interquartile range (which is the difference between the 75th percentile and the 25th percentile).</p>
</li>
</ul>
<p>With the minimum, it can help us detect data points that are also far below the other observed values.</p>
<p>For instance, assuming our data points are spread like these [345, 402, 295, 386, 10]. We can see that the value 10 is also an outlier because it is a lower value that is far below other observations.</p>
<p><strong>The 25th percentile</strong> is a value that tells us that 25% of our data points are below that value and 75% of our data points are above that value. The 25th percentile is also known as the first quartile.</p>
<p><strong>The 50th percentile</strong> is a value that indicates that 50% of our data points are below that value and the remaining 50% are above that value. It is also known as the second quartile.</p>
<p><strong>The 75th percentile</strong> is a value that tells us that 75 percent of our data point is below that value and the remaining 25 percent is above it. It is also known as the third quartile.</p>
<p><strong>Maximum:</strong> Also like the minimum, the maximum does not imply the highest value in the dataset. It is calculated using the formula (Q3 + 1.5*IQR) where:</p>
<ul>
<li><p>Q3 – implies the 75th percentile</p>
</li>
<li><p>IQR implies Interquartile Range (which is the difference between the 75th percentile and the 25th percentile).</p>
</li>
</ul>
<p>With maximum also, it can help us detect data points that are also far above the other observed values.</p>
<p>For instance, assuming our data points are spread like these [645, 40, 25, 38, 42]. We can see that the value 645 is also an outlier because it is a higher value that is far above other observations.</p>
<p>We've seen some graphical summaries of what we'll be dealing with on a daily basis. Let's look at the final topic we will discuss in this article:</p>
<h2 id="heading-what-is-the-association-between-quantitative-variables">What is the Association Between Quantitative Variables?</h2>
<p><strong>Variables</strong> are any values (alphabetical or numerical, but typically alphabetical) that represent a collection of observations. It is sometimes referred to as a column in a table.</p>
<p>Two variables are said to be associated if a specific value of one variable is most likely to occur with a specific value of another variable.</p>
<p>To study the association between two quantitative variables (often referred to as correlation), we calculate it using the Karl Pearson formula, and the result is between -1 and +1.</p>
<p>If the correlation value approaches 1, it indicates that the two variables are positively correlated (that is, as one variable increases the other variable increases as well). If the value approaches -1, it indicates that the variables are negatively linked (that is as one variable increases, the other variable decreases). Finally, if the correlation current is 0, there is no correlation between the variables.</p>
<p>You can read more <a target="_blank" href="https://www.statisticshowto.com/probability-and-statistics/correlation-coefficient-formula/">here</a> to know more about correlation and Karl Pearson formula</p>
<h2 id="heading-what-is-a-scatter-plot">What is a Scatter Plot?</h2>
<p>We can represent the correlation between quantitative variables in a graphical summary by using a plot called a scatter plot.</p>
<p>A scatter plot looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/scatter-ice-cream1.svg" alt="Image" width="600" height="400" loading="lazy"></p>
<p><a target="_blank" href="https://www.mathsisfun.com/data/scatter-xy-plots.html"><em>Scatter (XY) Plots (mathsisfun.com)</em></a></p>
<p>To learn about scatter plots you can read more <a target="_blank" href="https://byjus.com/maths/scatter-plot/#:~:text=Scatter%20plots%20are%20the%20graphs,plotted%20on%20the%20Y%2Daxis.">here</a>.</p>
<h1 id="heading-conclusion-and-learning-more">Conclusion and Learning More</h1>
<p>In this tutorial, we've explored some fundamental statistics concepts that will help you work more efficiently with your data.</p>
<p>But the learning does not stop here – there are a few fundamental topics that you must be familiar with. Because this is only the beginning, you can delve deeper by consulting online resources or textbooks.</p>
<p>Thank you very much for reading, and please share the article so that beginners who want to go into data science can learn as well.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is an Outlier? Definition and How to Find Outliers in Statistics ]]>
                </title>
                <description>
                    <![CDATA[ Outliers are an important part of a dataset. They can hold useful information about your data. Outliers can give helpful insights into the data you're studying, and they can have an effect on statistical results. This can potentially help you disover... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-an-outlier-definition-and-how-to-find-outliers-in-statistics/</link>
                <guid isPermaLink="false">66b1e4e0ab763c1471e56790</guid>
                
                    <category>
                        <![CDATA[ data analysis ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Dionysia Lemonaki ]]>
                </dc:creator>
                <pubDate>Tue, 24 Aug 2021 20:32:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/08/rupert-britton-l37N7a1lL6w-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Outliers are an important part of a dataset. They can hold useful information about your data.</p>
<p>Outliers can give helpful insights into the data you're studying, and they can have an effect on statistical results. This can potentially help you disover inconsistencies and detect any errors in your statistical processes.</p>
<p>So, knowing how to find outliers in a dataset will help you better understand your data.</p>
<p>There are a few different ways to find outliers in statistics.</p>
<p>This article will explain how to detect numeric outliers by calculating the  interquartile range.</p>
<p>I give an example of a very simple dataset and how to calculate the interquartile range, so you can follow along if you want.</p>
<p>Let's get started!</p>
<h2 id="heading-what-is-an-outlier-in-statistics-a-definition">What is an Outlier in Statistics? A Definition</h2>
<p>In simple terms, an outlier is an extremely high or extremely low data point relative to the nearest data point and the rest of the neighboring co-existing values in a data graph or dataset you're working with.</p>
<p>Outliers are extreme values that stand out greatly from  the overall pattern of values in a dataset or graph.</p>
<p>Below, on the far left of the graph, there is an outlier.</p>
<p>The value in the month of January is significantly less than in the other months.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/08/Screenshot-2021-08-24-at-3.07.05-PM.jpeg" alt="Screenshot-2021-08-24-at-3.07.05-PM" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-identify-an-outlier-in-a-dataset">How to Identify an Outlier in a Dataset</h2>
<p>Alright, how do you go about finding outliers?</p>
<p>An outlier has to satisfy either of the following two conditions:</p>
<pre><code>outlier &lt; Q1 - <span class="hljs-number">1.5</span>(IQR)
</code></pre><pre><code>outlier &gt; Q3 + <span class="hljs-number">1.5</span>(IQR)
</code></pre><p>The rule for a low outlier is that a data point in a dataset has to be less than <code>Q1 - 1.5xIQR</code>.</p>
<p>This means that a data point needs to fall more than 1.5 times the Interquartile range <em>below</em> the first quartile to be considered a low outlier.</p>
<p>The rule for a high outlier is that if any data point in a dataset is more than <code>Q3 - 1.5xIQR</code>, it's a high outlier.</p>
<p>More specifically, the data point needs to fall more than 1.5 times the Interquartile range <em>above</em> the third quartile to be considered a high outlier.</p>
<p>As you can see, there are certain individual values you need to calculate first in a dataset, such as the <code>IQR</code>. But to find the <code>IQR</code>, you need to find the so called first and third quartiles which are  <code>Q1</code> and <code>Q3</code> respectively. </p>
<p>So, let's see what each of those does and break down how to find their values in both an odd and an even dataset.</p>
<h2 id="heading-how-to-find-the-upper-and-lower-quartiles-in-an-odd-dataset">How to Find the Upper and Lower Quartiles in an Odd Dataset</h2>
<p>To get started, let's say that you have this dataset:</p>
<pre><code><span class="hljs-number">25</span>,<span class="hljs-number">14</span>,<span class="hljs-number">6</span>,<span class="hljs-number">5</span>,<span class="hljs-number">5</span>,<span class="hljs-number">30</span>,<span class="hljs-number">11</span>,<span class="hljs-number">11</span>,<span class="hljs-number">13</span>,<span class="hljs-number">4</span>,<span class="hljs-number">2</span>
</code></pre><p>The first step is to <strong>sort the values in ascending numerical order</strong>,from smallest to largest number.</p>
<pre><code><span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">11</span>,<span class="hljs-number">11</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">25</span>,<span class="hljs-number">30</span>
</code></pre><p>The lowest value (<strong>MIN</strong>) is <code>2</code> and the highest (<strong>MAX</strong>) is <code>30</code>.</p>
<h3 id="heading-how-to-calculate-q2-in-an-odd-dataset">How to calculate <code>Q2</code> in an odd dataset</h3>
<p>The next step is to find the <strong>median</strong> or <em>quartile 2 (Q2)</em>.</p>
<p>This particular set of data has an odd number of values, with a total of <code>11</code> scores all together.</p>
<p>To find the median in a dataset means that you're finding the middle value – the single middle number in the set.</p>
<p>In odd datasets, there in only one middle number.</p>
<p>Since there are <code>11</code> values in total, an easy way to do this is to split the set in two equal parts with each side containing <code>5</code> values.</p>
<p>The median value will have <code>5</code> values on one side and <code>5</code> values on the other.</p>
<p><code>(2,4,5,5,6)</code>, <strong><code>11</code></strong> ,<code>(11,13,14,25,30)</code></p>
<p>The median is <code>11</code> as it is the number that separates the first half from the second half.</p>
<p>An alternative way to double check if you're right is to do this:</p>
<p> <code>(total_number_of_scores + 1) / 2</code>.</p>
<p>This is <code>(11 + 1) /2 = 6</code>, which means you want the number in the <code>6th</code> place of this set of data – which is <code>11</code>.</p>
<p>So <code>Q2 = 11</code>.</p>
<h3 id="heading-how-to-calculate-q1-in-an-odd-dataset">How to calculate <code>Q1</code> in an odd dataset</h3>
<p>Next, to find the <em>lower quartile</em>, <code>Q1</code>, we need to find the median of the first half of the dataset, which is on the left hand side.</p>
<p>As a reminder, the initial dataset is:</p>
<p><code>(2,4,5,5,6)</code>, <strong><code>11</code></strong> ,<code>(11,13,14,25,30)</code></p>
<p>The first half of the dataset, or the <em>lower half</em>, does not include the median:</p>
<pre><code><span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>
</code></pre><p>This time, there is again an odd set of scores – specifically there are <code>5</code> values.</p>
<p>You want to again split this half set into another half, with an equal number of two values on each side. You'll get a unique number, which will be the number in the middle of the <code>5</code> values.</p>
<p>Pick the middle value that stands out:</p>
<p><code>(2,4)</code>,<strong><code>5</code></strong>,<code>(5,6)</code></p>
<p>In this case it's <code>Q1 = 5</code>.</p>
<p>To double check, you can also do <code>total_number_of_values + 1 / 2</code>, similar to the previous example:</p>
<p><code>(5 + 1) /2 =  3</code>.</p>
<p>This means you want the number in the 3rd place, which is <code>5</code>.</p>
<h3 id="heading-how-to-calculate-q3-in-an-odd-dataset">How to calculate <code>Q3</code> in an odd dataset</h3>
<p>To find the <em>upper quartile</em>, Q3, the process is the same as for <code>Q1</code> above. But in this case you take the second half on the right hand side of the dataset, above the median and without the median itself included:</p>
<p><code>(2,4,5,5,6)</code>, <strong><code>11</code></strong> ,<code>(11,13,14,25,30)</code></p>
<pre><code><span class="hljs-number">11</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">25</span>,<span class="hljs-number">30</span>
</code></pre><p>You split this half of the odd set of numbers into another half to find the median and subsequently the value of <code>Q3</code>. </p>
<p>You again want the number in the 3rd place like you did for the first half.</p>
<p><code>(11,13)</code>,<strong><code>14</code></strong>,<code>(25,30)</code></p>
<p>So <code>Q3 = 14</code>.</p>
<h3 id="heading-how-to-calculate-iqr-in-an-odd-dataset">How to calculate <code>IQR</code> in an odd dataset</h3>
<p>Now, the next step is to calculate the IQR which stands for Interquartile Range.</p>
<p>This is the difference/distance between the lower quartile (Q1) and the upper quartile (Q3) you calculated above.</p>
<p>As a reminder, the formula to do so is the following:</p>
<pre><code>IQR = Q3 - Q1
</code></pre><p>To find the IQR of the dataset from above:</p>
<pre><code>IQR= <span class="hljs-number">14</span> - <span class="hljs-number">5</span>
IQR = <span class="hljs-number">9</span>
</code></pre><h3 id="heading-how-to-find-an-outlier-in-an-odd-dataset">How to find an outlier in an odd dataset</h3>
<p>To recap so far, the dataset is the one below:</p>
<pre><code><span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">5</span>,<span class="hljs-number">6</span>,<span class="hljs-number">11</span>,<span class="hljs-number">11</span>,<span class="hljs-number">13</span>,<span class="hljs-number">14</span>,<span class="hljs-number">25</span>,<span class="hljs-number">30</span>
</code></pre><p>and so far, you have calucalted the five number summary:</p>
<pre><code>MIN = <span class="hljs-number">2</span>
Q1 = <span class="hljs-number">5</span>
MED = <span class="hljs-number">11</span>
Q3 = <span class="hljs-number">14</span>
MAX = <span class="hljs-number">30</span>
</code></pre><p>Finally, let's find out if there are any outliers in the dataset.</p>
<p>As a reminder, an outlier must fit the following criteria:</p>
<pre><code>outlier &lt; Q1 - <span class="hljs-number">1.5</span>(IQR)
</code></pre><p>Or </p>
<pre><code>outlier &gt; Q3 + <span class="hljs-number">1.5</span>(IQR)
</code></pre><p>To see if there is a lowest value outlier, you need to calculate the first part and see if there is a number in the set that satisfies the condition.</p>
<pre><code>Outlier &lt; Q1 - <span class="hljs-number">1.5</span>(IQR)
Outlier &lt; <span class="hljs-number">5</span> - <span class="hljs-number">1.5</span>(<span class="hljs-number">9</span>)
Outlier &lt; <span class="hljs-number">5</span> - <span class="hljs-number">13.5</span> 
outlier &lt; - <span class="hljs-number">8.5</span>
</code></pre><p>There are no lower outliers, since there isn't a number less than <code>-8.5</code> in the dataset.</p>
<p>Next, to see if there are any higher outliers:</p>
<pre><code>Outlier &gt; Q3  + <span class="hljs-number">1.5</span>(IQR)=
Outlier &gt; <span class="hljs-number">14</span> + <span class="hljs-number">1.5</span>(<span class="hljs-number">9</span>)
Outlier &gt; <span class="hljs-number">14</span> + <span class="hljs-number">13.5</span>
Outlier &gt; <span class="hljs-number">27</span>,<span class="hljs-number">5</span>
</code></pre><p>And there is a number in the dataset that is more than <code>27,5</code>:</p>
<p><code>2,4,5,5,6,11,11,13,14,25,</code><strong><code>30</code></strong></p>
<p>In this case, <code>30</code> is the outlier in the existing dataset.</p>
<h2 id="heading-how-to-find-the-upper-and-lower-quartiles-in-an-even-dataset">How to Find the Upper and Lower Quartiles in an Even Dataset</h2>
<p>What happens when you have a dataset that consists of an even set of data?</p>
<p>There isn't just one stand-out median (Q2), nor is there a standout upper quartile (Q1) or standout lower quartile (Q3).</p>
<p>So the process of calculating quartiles and then finding an outlier is a bit different.</p>
<h3 id="heading-how-to-calculate-q2-in-an-even-dataset">How to calculate <code>Q2</code> in an even dataset</h3>
<p>Say that you have this dataset with <code>8</code> numbers:</p>
<p><code>10,15,20,26,28,30,35,40</code></p>
<p>This time, the numbers are already sorted from lowest to highest value.</p>
<p>To find the <strong>median</strong> number in an even dataset, you need to find the value that would be in between the <em>two</em> numbers that are in the middle. You add them together and divide them by <code>2</code>, like so:</p>
<p><code>10,15,20</code>,<strong><code>26,28</code></strong>,<code>30,35,40</code></p>
<pre><code><span class="hljs-number">26</span> + <span class="hljs-number">28</span> = <span class="hljs-number">54</span>
<span class="hljs-number">54</span> / <span class="hljs-number">2</span> = <span class="hljs-number">27</span>
</code></pre><h3 id="heading-how-to-calculate-q1-in-an-even-dataset">How to calculate <code>Q1</code> in an even dataset</h3>
<p>To calculate to upper and lower quartiles in an even dataset, you keep all the numbers in the dataset (as opposed to in the odd set you removed the median).</p>
<p>This time, the dataset is cut in half.</p>
<p><code>10,15,20,26 | 28,30,35,40</code></p>
<p>To find <code>Q1</code>, you split the first half of the dataset into another half which leaves you with a remaining even set:</p>
<p><code>10,15 | 20,26</code></p>
<p>To find the median of this half, you take the two numbers in the middle and divide them by two:</p>
<pre><code>Q1 = (<span class="hljs-number">15</span> + <span class="hljs-number">20</span>)/<span class="hljs-number">2</span>
Q1 =  <span class="hljs-number">35</span> / <span class="hljs-number">2</span>
Q1 = <span class="hljs-number">17</span>,<span class="hljs-number">5</span>
</code></pre><h3 id="heading-how-to-calculate-q3-in-an-even-dataset">How to calculate <code>Q3</code> in an even dataset</h3>
<p>To find <code>Q3</code>, you need to focus on the second half of the dataset and split that half into another half:</p>
<p><code>28,30,35,40</code> -&gt; <code>28,30 | 35,40</code></p>
<p>The two numbers in the middle are <code>30</code> and <code>35</code>.</p>
<p>You add them and divide them by two, and the result is:</p>
<pre><code>Q3 = (<span class="hljs-number">30</span> + <span class="hljs-number">35</span>)/<span class="hljs-number">2</span>
Q3 =  <span class="hljs-number">65</span> / <span class="hljs-number">2</span>
Q3 = <span class="hljs-number">32</span>,<span class="hljs-number">5</span>
</code></pre><h3 id="heading-how-to-calculate-the-iqr-in-an-even-dataset">How to calculate the <code>IQR</code> in an even dataset</h3>
<p>The formula for calculating IQR is exactly the same as the one we used to calculate it for the odd dataset.</p>
<pre><code>IQR = Q3 - Q1
IQR = <span class="hljs-number">32</span>,<span class="hljs-number">5</span> - <span class="hljs-number">17</span>,<span class="hljs-number">5</span>
IQR = <span class="hljs-number">15</span>
</code></pre><h3 id="heading-how-to-find-an-outlier-in-an-even-dataset">How to find an outlier in an even dataset</h3>
<p>As a recap, so far the five number summary is the following:</p>
<pre><code>MIN = <span class="hljs-number">10</span>
Q1 = <span class="hljs-number">17</span>,<span class="hljs-number">5</span>
MED = <span class="hljs-number">27</span>
Q3 = <span class="hljs-number">32</span>,<span class="hljs-number">5</span>
MAX = <span class="hljs-number">40</span>
</code></pre><p>To calculate any outliers in the dataset:</p>
<pre><code>outlier &lt; Q1 - <span class="hljs-number">1.5</span>(IQR)
</code></pre><p>Or</p>
<pre><code>outlier &gt; Q3 + <span class="hljs-number">1.5</span>(IQR)
</code></pre><p>To find any lower outliers, you calcualte <code>Q1 - 1.5(IQR)</code> and see if there are any values less than the result.</p>
<pre><code>outlier &lt; <span class="hljs-number">17</span>,<span class="hljs-number">5</span> - <span class="hljs-number">1.5</span>(<span class="hljs-number">15</span>)=
outlier &lt; <span class="hljs-number">17</span>,<span class="hljs-number">5</span> - <span class="hljs-number">22</span>,<span class="hljs-number">5</span>
outlier &lt; <span class="hljs-number">-5</span>
</code></pre><p>There aren't any values in the dataset that are less than <code>-5</code>.</p>
<p>Finally, to find any higher outliers, you calculate <code>Q3 - 1.5(IQR)</code> and see if there are any values in the dataset that are higher than the result</p>
<pre><code>outlier &gt; <span class="hljs-number">32.5</span> + <span class="hljs-number">1.5</span>(<span class="hljs-number">15</span>)=
outlier &gt; <span class="hljs-number">32.5</span> + <span class="hljs-number">22.5</span>
outlier &gt; <span class="hljs-number">55</span>
</code></pre><p>There aren't any values higher than <code>55</code> so this dataset doesn't have any outliers.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article you learned how to find the interquartile range in a dataset and in that way calculate any outliers.</p>
<p>If you are interested in learning more about Statistics and the basics of Data Science, check out this <a target="_blank" href="https://www.youtube.com/watch?v=xxpc-HPKN28">free 8hour University course</a> on freeCodeCamp's YouTube channel.</p>
<p>Thank you for for reading and happy learning.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Skewness and Kurtosis – Positively Skewed and Negatively Skewed Distributions in Statistics Explained ]]>
                </title>
                <description>
                    <![CDATA[ By Rishit Dagli In this article, I'll explain two important concepts in statistics: skewness and kurtosis. And don't worry – you won't need to know very much math to understand these concepts and learn how to apply them. What are Density Curves? Let'... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/skewness-and-kurtosis-in-statistics-explained/</link>
                <guid isPermaLink="false">66d460ce3a8352b6c5a2aaef</guid>
                
                    <category>
                        <![CDATA[ Advanced Mathematics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Math ]]>
                    </category>
                
                    <category>
                        <![CDATA[ MathJax ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 16 Jun 2021 20:56:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/06/stats-article-image.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Rishit Dagli</p>
<p>In this article, I'll explain two important concepts in statistics: skewness and kurtosis. And don't worry – you won't need to know very much math to understand these concepts and learn how to apply them.</p>
<h2 id="heading-what-are-density-curves">What are Density Curves?</h2>
<p>Let's first talk a bit about density curves, as skewness and kurtosis are based on them. They're simply a way for us to represent a distribution. Let's see what I mean through an example.</p>
<p>Say that you need to record the heights of a lot of people. So your distribution has let's say 20 categories representing the range of the output (58-59 in, 59-60 in ... 78-79). You can plot a histogram representing these categories and the number of people whose height falls in each category.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/06/Percent-of-population-vs.-Height.png" alt="Image" width="600" height="400" loading="lazy">
<em>Histogram of height vs population</em></p>
<p>Well, you might do this for thousands of people, so you are not interested in the exact number – rather the percentage or probability of these categories. </p>
<p>I also explicitly mentioned that you have a rather large distribution since percentages are often useless for smaller distributions.</p>
<p>If you use percentages with smaller numbers I often refer to it as <em>lying</em> with statistics – it's a statement that is technically correct but creates the wrong impression in our minds. </p>
<p>Let me give you an example: a student is extremely excited and tells everyone in his class that he made a 100% improvement in his marks! But what he doesn't say is that his marks went from a 2/30 to 4/30 😂. </p>
<p>I hope you now clearly see the problem of using percentages with smaller numbers.</p>
<p>Coming back to density curves, when you are working with a large distribution you want to have more granular categories. So you make each category which was 1 inch wide now 2 categories each (\frac{1}{2}) inch wide. Maybe you want to get even more granular and start using (\frac{1}{4}) inch wide categories. Can you guess where I am going with this?</p>
<p>At a point, we get an infinite number of such categories with an infinitely small length. This allows us to create a curve from this histogram which we had earlier divided into discrete categories. See our density curve below drawn from the histogram.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/06/image-155.png" alt="Image" width="600" height="400" loading="lazy">
<em>Probability density curve for our distribution</em></p>
<h3 id="heading-why-go-through-the-effort">Why go through the effort?</h3>
<p>Great question! As you may have guessed, I like to explain myself with examples, so let's look at another density curve to make it a bit easier for us to understand. Feel free to skip the curve equation at this stage if you have not worked with distributions before.</p>
<p>You can also follow along and create the graphs and visualizations in this article yourself through <a target="_blank" href="https://www.geogebra.org/classic/barxehx4">this Geogebra project</a> (it runs in the browser).</p>
<p>$$ f(x) = \frac{1}{0.4 \sqrt{2 \pi} } \cdot e^{-\frac{1}{2} (\frac{x - 1.6}{0.4})^2} $$</p><p><img src="https://www.freecodecamp.org/news/content/images/2021/06/image-9.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>So now what if I ask you "What percent of my distribution is in the category 1 - 1.6?" Well, you just calculate the area under the curve between 1 and 1.6, like this:</p>
<p>$$ \int_{1}^{1.6} f(x) \,dx $$</p><p><img src="https://www.freecodecamp.org/news/content/images/2021/06/image-11.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>It would also be relatively easy for you to answer similar questions from the density curve like: "What percent of the distribution is under 1.2?" or "What percent of the distribution is above 1.2?"</p>
<p>You can now probably see why the effort of making this making a density curve is worth it and how it allows you to make inferences easily 🚀.</p>
<h2 id="heading-skewed-distributions">Skewed Distributions</h2>
<p>Let's now talk a bit about skewed distributions – that is, those that are not as pleasant and symmetric as the curves we saw earlier. We'll talk about this more intuitively using the ideas of mean and median.</p>
<p>From this density curve graph's image, try figuring out where the median of this distribution would be. Perhaps it was easy for you to figure out – the curve is symmetrical and you might have concluded that the median is 1.6 since it was symmetric about (x=1.6). </p>
<p>Another way to go about this would be to say that the median is the value where the area under the curve to the left of it it and the area under the curve to the right of it are equal.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/06/skewness-and-kurtosis-blog.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We're talking about this idea since it allows us to also calculate the median for non-symmetric density curves. </p>
<p>As an example here, I show two very common skewed distributions and how the idea of equal areas we just discussed helps us find their medians. If we tried eyeballing our median, this is what we'd get since we want the areas on either side to be equal.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/06/Eyballing-median.png" alt="Image" width="600" height="400" loading="lazy">
<em>Eyeballing the median for skewed curves</em></p>
<p>You can also calculate the mean through these density curves. Maybe you've tried calculating the mean yourself already, but notice that if you use the general formula to calculate the mean:</p>
<p>$$ mean = \frac{\sum a_n}{n} $$</p><p>you might notice a flaw in it: we take into account the ( x ) values but we also have probabilities associated with these values too. And it just makes sense to factor that in too. </p>
<p>So we modify the way we calculate the mean by using weighted averages. We will now also have a term (w_n) representing the associated weights:</p>
<p>$$ mean = \frac{\sum{a_n \cdot w_n}}{n} $$</p><p>So, we will be using the idea we just discussed to calculate the mean from our density curve. </p>
<p>You can also more intuitively understand this as the point on the x-axis where you could place a fulcrum and balance the curve if it was a solid object. This idea should help you better understand finding the mean from our density curve. </p>
<p>But another really interesting way to look at this would be as the x-coordinate of the point on this curve where the rotational inertia would be zero.</p>
<p>You might have already figured out how we can locate the mean for symmetric curves: our median and mean lie at the same point, the point of symmetry. </p>
<p>We will be using the idea we just discussed, placing a fulcrum on the x-axis and balancing the curve, to eyeball out the mean for skewed graphs like the ones we saw earlier while calculating the median.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/06/mean.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We will soon discuss the idea of skewness in greater detail. But at this stage, <em>generally speaking</em>, you can identify the direction where your curve is skewed. If the median is to the right of the mean, then it is negatively skewed. And if the mean is to the right of median, then it is positively skewed. </p>
<p>Later in this article, for simplicity's sake we'll also refer to the narrow part of these curves as a "tail".</p>
<h2 id="heading-what-are-moments">What are Moments?</h2>
<p>Before we talk more about skewness and kurtosis let's explore the idea of moments a bit. Later we'll use this concept to develop an idea for measuring skewness and kurtosis in our distribution.</p>
<p>We'll use a small dataset, [1, 2, 3, 3, 3, 6]. These numbers mean that you have points that are 1 unit away from the origin, 2 units away from the origin, and so on. </p>
<p>So, we care a lot about the distances from the origin in our dataset. We can represent the average distance from the origin in our data by writing:</p>
<p>$$ \frac{\sum a_n -0}{n} = \frac{\sum a_n}{n} $$</p><p>This is what we call our first moment. Calculating this for our sample dataset we get 3 but if we change our dataset and make all elements equal to 3,</p>
<p>$$ [1, 2, 3, 3, 3, 6] \rightarrow [3, 3, 3, 3, 3, 3] $$</p><p>you'll see that our first moment remains the same. Can we devise something to differentiate our two datasets that have equal first moments? (PS: It's the second moment.) </p>
<p>We will calculate the average sum of squared distances rather than the average sum of distances:</p>
<p>$$ \frac{\sum (a_n)^2}{n} $$</p><p>Our second moment for our original dataset is 11.33 and for our new dataset is 9. Notice that the magnitude of the second moment is larger for our original dataset than the new one. Also, we have a higher value for the second moment in the original dataset because it is spread out and has a greater average squared distance. </p>
<p>Essentially we are saying that we have a couple of values in our original dataset larger than the mean value, which, when squared, increases our second moment by a lot.</p>
<p>Here's an interesting way of thinking about moments – assume our distribution is mass, and then the first moment would be the center of the mass, and the second moment would be the rotational inertia.</p>
<p>You can also see that our second moment is highly dependent on our first moment. But we are interested in knowing the information the second moment can give us independently. </p>
<p>To do so we calculate the squared distances from the mean or the first moment rather than from the origin.</p>
<p>$$ \frac{\sum (a_n- \mu_{1}^{'})^2 }{n} $$</p><p>Did you notice that we also intuitively derived a formula for variance? Going forward you will see how we use the ideas we just talked about to measure skewness and kurtosis.</p>
<h2 id="heading-intro-to-skewness-and-kurtosis">Intro to Skewness and Kurtosis?</h2>
<p>Let's see how we can use the idea of moments we talked about earlier to figure out how we can measure skewness (which you already have some idea about) and kurtosis.</p>
<h3 id="heading-what-is-skewness">What is Skewness?</h3>
<p>Let's take the idea of moments we talked about just now and try to calculate the third moment. As you might have guessed, we can calculate the cubes of our distances. But as we discussed above, we are more interested in seeing the additional information the third moment provides.</p>
<p>So we want to subtract the second moment from our third moment. Later, we will also refer to this factor as the adjustment to the moment. So our adjusted moment will look like this:</p>
<p>$$ skewness = \frac{\sum (a_n - \mu)^3 }{n \cdot \sigma ^3} $$</p><p>This adjusted moment is what we call <em>skewness.</em> It helps us measure the asymmetry in the data. </p>
<p>Perfectly symmetrical data would have a skewness value of 0. A negative skewness value implies that a distribution has its tail on the left side of the distribution, while a positive skewness value has its tail on the on the right side of the distribution. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/06/image-100.png" alt="Image" width="600" height="400" loading="lazy">
<em>Positive skew and negative skew</em></p>
<p>At this stage, it might seem like calculating skewness would be pretty tough to do since in the formulas we use the population mean ( \mu ) and the population standard deviation ( \sigma ) which we wouldn't have access to while taking a sample. </p>
<p>Instead, you only have the sample mean and the sample standard deviation, so we will soon see how you can use these.</p>
<h3 id="heading-what-is-kurtosis">What is Kurtosis?</h3>
<p>As you might have guessed, this time we will calculate our fourth moment or use the fourth power of our distances. And like we talked about earlier we are interested in seeing the additional information this provides so we will also subtract out the adjustment factor from it. </p>
<p>This is what we call <em>kurtosis</em> or a measure of whether our data has a lot of outliers or very few outliers. This will look like:</p>
<p>$$  kurtosis = \frac{\sum (a_n - \mu)^4 }{n \cdot \sigma ^4} $$</p><p>A better term for what's going on here is to figure out if the distribution is heavy-tailed or light-tailed. We can compare this to a normal distribution. </p>
<p>If you do a simple substitution you'll see that the kurtosis for normal distribution is 3. And since we are interested in comparing kurtosis to the normal distribution, often we use excess kurtosis which simply subtracts 3 from the above equation.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/06/positive-negative-kurtosis.png" alt="Image" width="600" height="400" loading="lazy">
<em>Positive and negative kurtosis (Adapted from Analytics Vidhya)</em></p>
<p>This is us essentially trying to force the kurtosis of our normal distribution to be 0 for easier comparison. So, if our distribution has positive kurtosis, it indicates a heavy-tailed distribution while negative kurtosis indicates a light-tailed distribution. Graphically, this would look something like the image above.</p>
<h2 id="heading-sampling-adjustment">Sampling Adjustment</h2>
<p>So, a problem with the equations we just built is that they have two terms in them, the distribution mean ( \mu ) and the distribution standard deviation ( \sigma ). But we are taking a sample of observations so we do not have the parameters for the whole distribution. We'd only have the sample mean and the sample standard deviation.</p>
<p>To keep this article focused, we will not be talking in detail about sampling adjustment terms since degrees of freedom is not in the scope of this article. </p>
<p>The idea is to use our sample mean ( \bar{x} ) and our sample standard deviation ( s ) to estimate these values for our distribution. We will also have to adjust our degree of freedom in these equations for it. </p>
<p>Don't worry if you don't understand this concept completely at this point. We can move on anyway. This leads to us modifying the equations we talked about earlier like so:</p>
<p>$$ skewness = \frac{\sum (a_n - \bar{x})^3 }{s^3} \cdot \frac{n}{(n-1)(n-2)} $$</p><p>$$ kurtosis = \frac{\sum (a_n - \bar{x})^4 }{s^4} \cdot \frac{n(n+1)}{(n-1)(n-2)(n-3)} - \frac{3(n-1)^2}{(n-2)(n-3)} $$</p><h2 id="heading-how-to-implement-this-in-python">How to Implement this in Python</h2>
<p>Finally, let's finish up by seeing how you can measure skewness and kurtosis in Python with an example. In case you want to follow along and try out the code, you can follow along with <a target="_blank" href="https://colab.research.google.com/drive/1pbWIz7X7_k5iNZ5w2x6eQUPz24l7yfLm?usp=sharing">this Colab Notebook</a> where we measure the skewness and kurtosis of a dataset.</p>
<p>It is pretty straightforward to implement this in Python with <a target="_blank" href="https://www.scipy.org/">Scipy</a>. It has methods to easily measure skewness and kurtosis for a distribution with pre-built methods. </p>
<p>The below code block shows how to measure skewness and kurtosis for the <a target="_blank" href="https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html">Boston housing dataset</a>, but you could also use it for your own distributions.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> scipy.stats <span class="hljs-keyword">import</span> skew
<span class="hljs-keyword">from</span> scipy.stats <span class="hljs-keyword">import</span> kurtosis

skew(data[<span class="hljs-string">"MEDV"</span>].dropna())
kurtosis(data[<span class="hljs-string">"MEDV"</span>].dropna())
</code></pre>
<h2 id="heading-thank-you-for-reading"><strong>Thank you for reading!</strong></h2>
<p>Thank you for sticking with me until the end. I hope you have learned a lot from this article.</p>
<p>I am excited to see if this article helped you better understand these two very important ideas. If you have any feedback or suggestions for me please feel free to <a target="_blank" href="https://twitter.com/rishit_dagli">reach out to me on Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Data Science Learning Roadmap ]]>
                </title>
                <description>
                    <![CDATA[ Although nothing really changes but the date, a new year fills everyone with the hope of starting things afresh. If you add in a bit of planning, some well-envisioned goals, and a learning roadmap, you'll have a great recipe for a year full of growth... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/data-science-learning-roadmap/</link>
                <guid isPermaLink="false">66d45f3747a8245f78752a56</guid>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Harshit Tyagi ]]>
                </dc:creator>
                <pubDate>Tue, 12 Jan 2021 00:24:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/01/Blue-and-Ivory-Photo-Musician-Influencer-Digital-Brutalism-YouTube-Thumbnail-Set.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Although nothing really changes but the date, a new year fills everyone with the hope of starting things afresh. If you add in a bit of planning, some well-envisioned goals, and a learning roadmap, you'll have a great recipe for a year full of growth.</p>
<p>This post intends to strengthen your plan by providing you with a <strong>learning framework, resources, and project ideas</strong> to help you build a solid portfolio of work showcasing expertise in data science.</p>
<p>Just a note: I've prepared this roadmap based on my personal experience in data science. This is not the be-all and end-all learning plan. You can adapt this roadmap to better suit any specific domain or field of study that interests you. Also, this was created with Python in mind as I personally prefer it.</p>
<h2 id="heading-what-is-a-learning-roadmap">What is a learning roadmap?</h2>
<p>A learning roadmap is an extension of a curriculum. It charts out a multi-level skills map with details about <strong>what</strong> skills you want to hone, <strong>how</strong> you will measure the outcome at each level, and <strong>techniques</strong> to further master each skill.</p>
<p>My roadmap assigns weights to each level based on the complexity and commonality of its application in the real-world. I have also added an estimated time for a beginner to complete each level with exercises and projects.</p>
<p>Here is a pyramid that depicts the high-level skills in order of their complexity and application in the industry.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/IMG-0021.JPG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Data science tasks in the order of complexity</em></p>
<p>This will mark the base of our framework. We’ll now have to deep dive into each of these strata to complete our framework with more specific, measurable details.</p>
<p>Specificity comes from examining the critical topics in each layer and the resources needed to master those topics.</p>
<p>We’d be able to measure the knowledge gained by applying the learned topics to a number of real-world projects. I’ve added a few project ideas, portals, and platforms that you can use to measure your proficiency.</p>
<blockquote>
<p>Important NOTE: Take it one day at a time, one video/blog/chapter a day. It is a wide spectrum to cover. Don’t overwhelm yourself!</p>
</blockquote>
<p>Let’s deep dive into each of these strata, starting from the bottom.</p>
<h2 id="heading-1-how-to-learn-about-programming-or-software-engineering">1. How to Learn About Programming or Software Engineering</h2>
<p><strong>(Estimated time: 2-3 months)</strong></p>
<p>First, make sure you have sound programming skills. Every data science job description will ask for programming expertise in at least one languages.</p>
<h3 id="heading-specific-programming-topics-to-know-include">Specific programming topics to know include:</h3>
<ul>
<li><p>Common data structures (data types, lists, dictionaries, sets, tuples), writing functions, logic, control flow, searching and sorting algorithms, object-oriented programming, and working with external libraries.</p>
</li>
<li><p>SQL scripting: Querying databases using joins, aggregations, and subqueries</p>
</li>
<li><p>Comfort using the Terminal, version control in Git, and using GitHub</p>
</li>
</ul>
<h3 id="heading-resources-to-learn-python">Resources to learn Python:</h3>
<ul>
<li><p><a target="_blank" href="https://www.learnpython.org/">learnpython.org</a> [free]— a free resource for beginners. It covers all the basic programming topics from scratch. You get an interactive shell to practice those topics side-by-side.</p>
</li>
<li><p><a target="_blank" href="https://www.kaggle.com/learn/python">Kaggle</a> [free]— a free and interactive guide to learning python. It is a short tutorial covering all the important topics for data science.</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/learn/scientific-computing-with-python/python-for-everybody/">Python certifications on freeCodeCamp</a> [free] – freeCodeCamp offers several certifications based on Python, such as scientific computing, data analysis, and machine learning.</p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=rfscVS0vtbw">Python Course by freecodecamp on YouTube</a> [free] — This is a 5-hour course that you can follow to practice the basic concepts.</p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=HGOBQPFzWKo">Intermediate python</a> [free]— Another free course by Patrick featured on freecodecamp.org.</p>
</li>
<li><p><a target="_blank" href="https://www.coursera.org/specializations/python"><strong>Coursera Python for Everybody Specialization</strong></a> <strong>[fee]</strong> — this is a specialization encompassing beginner-level concepts, python data structures, data collection from the web, and using databases with python.</p>
</li>
</ul>
<h3 id="heading-resources-for-learning-git-and-github">Resources for learning Git and GitHub</h3>
<ul>
<li><p>Guide <a target="_blank" href="https://www.atlassian.com/git">for Git</a> and <a target="_blank" href="https://lab.github.com/">GitHub</a> [free]: complete these tutorials and labs to develop a firm grip over version control. It will help you further in contributing to open-source projects.</p>
</li>
<li><p>Here's a <a target="_blank" href="https://www.freecodecamp.org/news/git-and-github-crash-course/">Git and GitHub crash course</a> on the freeCodeCamp YouTube channel</p>
</li>
</ul>
<h3 id="heading-resources-for-learning-sql">Resources for learning SQL</h3>
<ul>
<li><p>Here's a <a target="_blank" href="https://www.freecodecamp.org/news/sql-and-databases-full-course/">course on SQL and Databases</a> on the freeCodeCamp YouTube channel</p>
</li>
<li><p><a target="_blank" href="https://www.kaggle.com/learn/intro-to-sql">Intro to SQL</a> and <a target="_blank" href="https://www.kaggle.com/learn/advanced-sql">Advanced SQL</a> on Kaggle.</p>
</li>
<li><p>freeCodeCamp now has a <a target="_blank" href="https://www.freecodecamp.org/learn/relational-database/">free interactive SQL course</a>.</p>
</li>
</ul>
<h3 id="heading-measure-your-expertise-by-solving-a-lot-of-problems-and-building-at-least-2-projects">Measure your expertise by solving a lot of problems and building at least 2 projects:</h3>
<ul>
<li><p>Solve a lot of problems here: <a target="_blank" href="https://www.hackerrank.com/">HackerRank</a> (beginner-friendly) and <a target="_blank" href="https://leetcode.com/">LeetCode</a> (solve easy or medium-level questions)</p>
</li>
<li><p>Data Extraction from a website/API endpoints — try to write Python scripts from extracting data from webpages that allow scraping like <em>soundcloud.com.</em> Store the extracted data into a CSV file or a SQL database.</p>
</li>
<li><p>Games like rock-paper-scissor, spin a yarn, hangman, dice rolling simulator, tic-tac-toe, and so on.</p>
</li>
<li><p>Simple web apps like a YouTube video downloader, website blocker, music player, plagiarism checker, and so on.</p>
</li>
</ul>
<p>Deploy these projects on GitHub pages or simply host the code on GitHub so that you learn to use Git.</p>
<h2 id="heading-2-how-to-learn-about-data-collection-and-wrangling-cleaning">2. How to Learn About Data Collection and Wrangling (Cleaning)</h2>
<p><strong>(Estimated time: 2 months)</strong></p>
<p>A significant part of data science work is centered around finding apt data that can help you solve your problem. You can collect data from different legitimate sources — scraping (if the website allows), APIs, Databases, and publicly available repositories.</p>
<p>Once you have data in hand, an analyst will often find themself cleaning dataframes, working with multi-dimensional arrays, using descriptive/scientific computations, and manipulating dataframes to aggregate data.</p>
<p>Data are rarely clean and formatted for use in the “real world”. Pandas and NumPy are the two libraries that are at your disposal to go from dirty data to ready-to-analyze data.</p>
<p>As you start feeling comfortable writing Python programs, feel free to start taking lessons on using libraries like <strong>pandas</strong> and <a target="_blank" href="https://towardsdatascience.com/numpy-essentials-for-data-science-25dc39fae39"><strong>numpy</strong></a>.</p>
<h3 id="heading-resources-to-learn-about-data-collection-and-cleaning">Resources to learn about data collection and cleaning:</h3>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=r-uOLxNrNk8">freeCodeCamp course on learning Numpy, Pandas, matplotlib, and seaborn</a> [free].</p>
</li>
<li><p>Practical tutorial on <a target="_blank" href="https://www.hackerearth.com/practice/machine-learning/data-manipulation-visualisation-r-python/tutorial-data-manipulation-numpy-pandas-python/tutorial/">data manipulation with NumPy and Pandas in Python</a> from HackerEarth.</p>
</li>
<li><p><a target="_blank" href="https://www.kaggle.com/learn/pandas">Kaggle pandas tutorial</a> [free] — A short and concise hands-on tutorial that will walk you through commonly used data manipulation skills.</p>
</li>
<li><p><a target="_blank" href="https://www.kaggle.com/learn/data-cleaning">Data Cleaning course by Kaggle</a>.</p>
</li>
<li><p><a target="_blank" href="https://www.coursera.org/learn/python-data-analysis?specialization=data-science-python">Coursera course on Introduction to Data Science in Python</a>  — This is the first course in the <a target="_blank" href="https://www.coursera.org/specializations/data-science-python">Applied Data Science with Python Specialization.</a></p>
</li>
</ul>
<h3 id="heading-data-collection-project-ideas">Data collection project Ideas:</h3>
<ul>
<li><p>Collect data from a website/API (open for public consumption) of your choice, and transform the data to store it from different sources into an aggregated file or table (DB). Example APIs include <a target="_blank" href="https://developers.themoviedb.org/3">TMDB</a>, <a target="_blank" href="https://www.quandl.com/tools/python">quandl</a>, <a target="_blank" href="https://developer.twitter.com/en/docs">Twitter API</a>, and so on.</p>
</li>
<li><p>Pick <a target="_blank" href="https://towardsdatascience.com/data-repositories-for-almost-every-type-of-data-science-project-7aa2f98128b">any publicly available dataset</a> and define a set of questions that you’d want to pursue after looking at the dataset and the domain. Wrangle the data to find out answers to those questions using Pandas and NumPy.</p>
</li>
</ul>
<h2 id="heading-3-how-to-learn-about-exploratory-data-analysis-business-acumen-and-storytelling">3. How to Learn About Exploratory Data Analysis, Business Acumen, and Storytelling</h2>
<p><strong>(Estimated time: 2–3 months)</strong></p>
<p>The next stratum to master is data analysis and storytelling. Drawing insights from the data and then communicating the same to management in simple terms and visualizations is the core responsibility of a Data Analyst.</p>
<p>The storytelling part requires you to be proficient with data visualization along with excellent communication skills.</p>
<h3 id="heading-specific-exploratory-data-analysis-and-storytelling-topics-to-learn-include">Specific exploratory data analysis and storytelling topics to learn include:</h3>
<ul>
<li><p><strong>Exploratory data analysis</strong> — defining questions, handling missing values, outliers, formatting, filtering, univariate and multivariate analysis.</p>
</li>
<li><p>Data visualization — plotting data using libraries like matplotlib, seaborn, and plotly. Know how to choose the right chart to communicate the findings from the data.</p>
</li>
<li><p>Developing dashboards — a good percent of analysts only use Excel or a specialized tool like Power BI and Tableau to build dashboards that summarise/aggregate data to help management make decisions.</p>
</li>
<li><p>Business acumen: Work on asking the right questions to answer, ones that actually target the business metrics. Practice writing clear and concise reports, blogs, and presentations.</p>
</li>
</ul>
<h3 id="heading-resources-to-learn-more-about-data-analysis">Resources to learn more about data analysis:</h3>
<ul>
<li><p>Learn data analysis with Python in this <a target="_blank" href="https://www.freecodecamp.org/news/learn-data-analysis-with-python-course/">free course on the freeCodeCamp YouTube channel</a>.</p>
</li>
<li><p><a target="_blank" href="https://www.coursera.org/learn/data-analysis-with-python">Data Analysis with Python</a> — by IBM on Coursera. The course covers wrangling, exploratory analysis, and simple model development using python.</p>
</li>
<li><p><a target="_blank" href="https://www.kaggle.com/learn/data-visualization">Data Visualization</a> — by Kaggle. Another interactive course that lets you practice all the commonly used plots.</p>
</li>
<li><p>Build product sense and business acumen with these books: <a target="_blank" href="https://www.amazon.com/Measure-What-Matters-Google-Foundation/dp/0525536221/ref=sr_1_1?crid=1A9SIXXP7S2P8&amp;dchild=1&amp;keywords=measure+what+matters&amp;qid=1610323490&amp;s=books&amp;sprefix=measure%2Cstripbooks%2C365&amp;sr=1-1"><strong>Measure what matters</strong></a><strong>,</strong> <a target="_blank" href="https://www.amazon.com/Decode-Conquer-Answers-Management-Interviews/dp/0615930417/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1530848101&amp;sr=1-1&amp;keywords=decode+and+conquer">Decode and conquer</a>, <a target="_blank" href="https://www.amazon.com/Cracking-PM-Interview-Product-Technology/dp/0984782818/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1530848116&amp;sr=1-1&amp;keywords=cracking+the+pm+interview">Cracking the PM interview</a><strong>.</strong></p>
</li>
</ul>
<h3 id="heading-data-analysis-project-ideas">Data analysis project ideas</h3>
<ul>
<li><p>Exploratory analysis on <a target="_blank" href="https://towardsdatascience.com/hitchhikers-guide-to-exploratory-data-analysis-6e8d896d3f7e">movies dataset to find the formula to create profitable movies</a> (use it as inspiration), use datasets from healthcare, finance, WHO, past census, Ecommerce, and so on.</p>
</li>
<li><p>Build dashboards (jupyter notebooks, excel, <a target="_blank" href="https://public.tableau.com/en-gb/gallery/?tab=viz-of-the-day&amp;type=viz-of-the-day">tableau</a>) using the resources provided above.</p>
</li>
</ul>
<h2 id="heading-4-how-to-learn-about-data-engineering">4. How to Learn About Data Engineering</h2>
<p><strong>(Estimated time: 4–5 months)</strong></p>
<p>Data engineering underpins the R&amp;D teams by making clean data accessible to research engineers and scientists at big data-driven firms. It is a field in itself and you may decide to skip this part if you want to focus on just the statistical algorithm side of the problems.</p>
<p>Responsibilities of a data engineer comprise building an efficient data architecture, streamlining data processing, and maintaining large-scale data systems.</p>
<p>Engineers use Shell (CLI), SQL, and Python/Scala to create ETL pipelines, automate file system tasks, and optimize the database operations to make them high-performance.</p>
<p>Another crucial skill is implementing these data architectures which demand proficiency in cloud service providers like AWS, Google Cloud Platform, Microsoft Azure, and others.</p>
<h3 id="heading-resources-to-learn-data-engineering">Resources to learn Data Engineering:</h3>
<ul>
<li><p><a target="_blank" href="https://www.udacity.com/course/data-engineer-nanodegree--nd027">Data Engineering Nanodegree by Udacity</a> — as far as a compiled list of resources is concerned, I have not come across a better-structured course on data engineering that covers all the major concepts from scratch.</p>
</li>
<li><p><a target="_blank" href="https://www.coursera.org/specializations/gcp-data-machine-learning">Data Engineering, Big Data, and Machine Learning on GCP Specialization</a> — You can complete this specialization offered by Google on Coursera that walks you through all the major APIs and services offered by GCP to build a complete data solution.</p>
</li>
</ul>
<h3 id="heading-data-engineering-project-ideascertifications-to-prepare-for">Data Engineering project ideas/certifications to prepare for:</h3>
<ul>
<li><p><a target="_blank" href="https://aws.amazon.com/certification/certified-machine-learning-specialty/">AWS Certified Machine Learning (300 USD)</a> — A proctored exam offered by AWS, adds some weight to your profile (doesn’t guarantee anything, though), requires a decent understanding of AWS services and ML.</p>
</li>
<li><p><a target="_blank" href="https://cloud.google.com/certification/data-engineer">Professional Data Engineer</a> — Certification offered by GCP. This is also a proctored exam and assesses your abilities to design data processing systems, deploying machine learning models in a production environment, and ensure solutions quality and automation.</p>
</li>
</ul>
<h2 id="heading-5-how-to-learn-about-applied-statistics-and-mathematics">5. How to Learn About Applied Statistics and Mathematics</h2>
<p><strong>(Estimated time: 4–5 months)</strong></p>
<p>Statistical methods are a central part of data science. Almost all data science interviews predominantly focus on descriptive and inferential statistics.</p>
<p>People often start coding machine learning algorithms without a clear understanding of underlying statistical and mathematical methods that explain the working of those algorithms. This, of course, isn't the best way to go about it.</p>
<h3 id="heading-topics-you-should-focus-on-in-applied-statistics-and-math">Topics you should focus on in Applied Statistics and math:</h3>
<ul>
<li><p><strong>Descriptive Statistics</strong> — to be able to summarise the data is powerful, but not always. Learn about estimates of location (mean, median, mode, weighted statistics, trimmed statistics), and variability to describe the data.</p>
</li>
<li><p><strong>Inferential statistics</strong> — designing hypothesis tests, A/B tests, defining business metrics, analyzing the collected data and experiment results using confidence interval, p-value, and alpha values.</p>
</li>
<li><p><strong>Linear Algebra, Single and multi-variate calculus</strong> to understand loss functions, gradient, and optimizers in machine learning.</p>
</li>
</ul>
<h3 id="heading-resources-to-learn-about-statistics-and-math">Resources to learn about Statistics and math:</h3>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/free-statistics-course/">Learn college-level statistics</a> in this free 8-hour course on the freeCodeCamp YouTube channel</p>
</li>
<li><p><a target="_blank" href="https://www.amazon.com/Practical-Statistics-Data-Scientists-Essential/dp/149207294X/ref=sr_1_1?crid=QOOZP96ISCU4&amp;dchild=1&amp;keywords=practical+statistics+for+data+scientists&amp;qid=1610247485&amp;s=books&amp;sprefix=practical+stat%2Cstripbooks%2C362&amp;sr=1-1">[Book] Practical statistics for data science</a> <strong>(highly recommend) —</strong> A thorough guide on all the important statistical methods along with clean and concise applications/examples.</p>
</li>
<li><p><a target="_blank" href="https://www.amazon.com/Naked-Statistics-Stripping-Dread-Data/dp/1480590185">[Book] Naked Statistics</a> — a non-technical but detailed guide to understanding the impact of statistics on our routine events, sports, recommendation systems, and many more instances.</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/free-statistics-course/">An 8-hour University-level Statistics course</a> —  a foundation course to help you start thinking statistically.</p>
</li>
<li><p><a target="_blank" href="https://www.udacity.com/course/intro-to-descriptive-statistics--ud827">Intro to Descriptive Statistics</a>— offered by Udacity. Consists of video lectures explaining widely used measures of location and variability(standard deviation, variance, median absolute deviation).</p>
</li>
<li><p><a target="_blank" href="https://www.udacity.com/course/intro-to-inferential-statistics--ud201">Inferential Statistics, Udacity</a> — the course consists of video lectures that educate you on drawing conclusions from data that might not be immediately obvious. It focuses on developing hypotheses and use common tests such as t-tests, ANOVA, and regression.</p>
</li>
<li><p>And here's a <a target="_blank" href="https://www.freecodecamp.org/news/statistics-for-data-science/">guide to statistics for data science</a> to help you get started down the right path.</p>
</li>
</ul>
<h3 id="heading-statistics-project-ideas">Statistics project ideas:</h3>
<ul>
<li><p>Solve the exercises provided in the courses above and then try to go through a number of public datasets where you can apply these statistical concepts. Ask questions like “Is there sufficient evidence to conclude that the mean age of mothers giving birth in Boston is over 25 years of age at the 0.05 level of significance”?</p>
</li>
<li><p>Try to design and run small experiments with your peers/groups/classes by asking them to interact with an app or answer a question. Run statistical methods on the collected data once you have a good amount of data after a period of time. This might be very hard to pull off but should be very interesting.</p>
</li>
<li><p>Analyze stock prices, cryptocurrencies, and design hypothesis around the average return or any other metric. Determine if you can reject the null hypothesis or fail to do so using critical values.</p>
</li>
</ul>
<h2 id="heading-6-how-to-learn-about-machine-learning-and-ai">6. How to Learn About Machine Learning and AI</h2>
<p><strong>(Estimated time: 4–5 months)</strong></p>
<p>After grilling yourself and going through all the major aforementioned concepts, you should now be ready to get started with the fancy ML algorithms.</p>
<p>There are three major types of learning:</p>
<ol>
<li><p><strong>Supervised Learning</strong> — includes regression and classification problems. Study simple linear regression, multiple regression, polynomial regression, naive Bayes, logistic regression, KNNs, tree models, ensemble models. Learn about evaluation metrics.</p>
</li>
<li><p><strong>Unsupervised Learning</strong> — Clustering and dimensionality reduction are the two widely used applications of unsupervised learning. Dive deep into PCA, K-means clustering, hierarchical clustering, and gaussian mixtures.</p>
</li>
<li><p><strong>Reinforcement learning</strong> (can skip*) — helps you build self-rewarding systems. Learn to optimize rewards, using the TF-Agents library, creating Deep Q-networks, and so on.</p>
</li>
</ol>
<p>The majority of the ML projects need you to master a number of tasks that I’ve explained in <a target="_blank" href="https://towardsdatascience.com/task-cheatsheet-for-almost-every-machine-learning-project-d0946861c6d0">this blog</a>.</p>
<h3 id="heading-resources-to-learn-about-machine-learning">Resources to learn about Machine Learning:</h3>
<ul>
<li><p>Here's a free full course on <a target="_blank" href="https://www.freecodecamp.org/news/machine-learning-with-scikit-learn-full-course/">Machine learning in Python with ScikitLearn</a> on the freeCodeCamp YouTube channel.</p>
</li>
<li><p>[book] <a target="_blank" href="https://www.amazon.com/Hands-Machine-Learning-Scikit-Learn-TensorFlow/dp/1492032646/ref=sr_1_1?dchild=1&amp;keywords=Hands-On+Machine+Learning+with+Scikit-Learn%2C+Keras%2C+and+TensorFlow%2C+2nd+Edition&amp;qid=1610253356&amp;sr=8-1">Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow, 2nd Edition</a> — one of my all-time favorite books on machine learning. Doesn’t only cover the theoretical mathematical derivations, but also showcases the implementation of algorithms through examples. You should solve the exercises given at the end of each chapter.</p>
</li>
<li><p><a target="_blank" href="https://www.coursera.org/learn/machine-learning">Machine Learning Course by Andrew Ng</a> — the go-to course for anyone trying to learn machine learning. Hands down!</p>
</li>
<li><p><a target="_blank" href="https://www.kaggle.com/learn/intro-to-machine-learning">Introduction to Machine Learning</a> — Interactive course by Kaggle.</p>
</li>
<li><p><a target="_blank" href="https://www.kaggle.com/learn/intro-to-game-ai-and-reinforcement-learning">Intro to Game AI and Reinforcement Learning</a> — another interactive course on Kaggle on reinforcement learning.</p>
</li>
</ul>
<h3 id="heading-deep-learning-specialization-by-deeplearningaihttpswwwdeeplearningaideep-learning-specialization"><a target="_blank" href="https://www.deeplearning.ai/deep-learning-specialization/">Deep Learning Specialization by deeplearning.ai</a></h3>
<p>For those of you who are interested in further diving into deep learning, you can start off by completing this specialization offered by deeplearning.ai and the Hands-ON book. This is not as important from a data science perspective unless you are planning to solve a computer vision or NLP problem.</p>
<p>Deep learning deserves a dedicated roadmap of its own. I’ll create that with all the fundamental concepts soon.</p>
<h2 id="heading-track-your-learning-progress">Track your learning progress</h2>
<p>I’ve also created a learning tracker for you on Notion. You can customize it to your needs and use it to track your progress, have easy access to all the resources and your projects.</p>
<p><a target="_blank" href="https://www.notion.so/Data-Science-learning-tracker-0d3c503280d744acb1b862a1ddd8344e">Find the learning tracker here</a>.</p>
<p>Also, here's the video version of this blog:</p>
<h3 id="heading-data-science-with-harshithttpswwwyoutubecomcdatasciencewithharshitsubconfirmation1"><a target="_blank" href="https://www.youtube.com/c/DataSciencewithHarshit?sub_confirmation=1">Data Science with Harshit</a></h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/nM_wZIzKEhc" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>This is just a high-level overview of the wide spectrum of data science. You might want to deep dive into each of these topics and create a low-level concept-based plan for each of the categories.</p>
<p>If this tutorial was helpful, you should check out my data science and machine learning courses on <a target="_blank" href="https://www.wiplane.com/">Wiplane Academy</a>. They are comprehensive yet compact and helps you build a solid foundation of work to showcase.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Explain Data Using Gaussian Distribution and Summary Statistics with Python ]]>
                </title>
                <description>
                    <![CDATA[ Once you understand the taxonomy of data, you should learn to apply a few essential foundational concepts that help describe the data using a set of statistical methods. Before we dive into data and its distribution, we should understand the differen... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-explain-data-using-gaussian-distribution-and-summary-statistics-with-python/</link>
                <guid isPermaLink="false">66d45f48706b9fb1c166b96d</guid>
                
                    <category>
                        <![CDATA[ data ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data analysis ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Harshit Tyagi ]]>
                </dc:creator>
                <pubDate>Fri, 27 Nov 2020 02:28:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/11/1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Once you understand the <a target="_blank" href="https://towardsdatascience.com/types-of-structured-data-every-data-science-enthusiast-should-know-a656b95afbe2">taxonomy of data</a>, you should learn to apply a few essential foundational concepts that help describe the data using a set of statistical methods.</p>
<p>Before we dive into data and its distribution, we should understand the difference between two very important keywords - <strong>sample</strong> and <strong>population.</strong></p>
<p>A <em>sample</em> is a snapshot of data from a larger dataset. This larger dataset which is all of the data that could be possibly collected is called <em>population.</em></p>
<p>In statistics, the population is a broad, defined, and often theoretical set of all possible observations that are generated from an experiment or from a domain.</p>
<p>Observations in a sample dataset often fit a certain kind of distribution which is commonly called <strong>normal distribution</strong>, and formally called <strong>Gaussian</strong> <strong>distribution</strong>. This is the most studied distribution, and there is an entire sub-field of statistics dedicated to Gaussian data.</p>
<h2 id="heading-what-well-cover">What we’ll cover</h2>
<p>In this post, we’ll focus on understanding:</p>
<ul>
<li><p>more about Guassian distribution and how it can be used to describe the data and observations from a machine learning model.</p>
</li>
<li><p><strong>estimates of location</strong> — the central tendency of a distribution.</p>
</li>
<li><p><strong>estimates of variability</strong> — the dispersion of data from the mean in the distribution.</p>
</li>
<li><p>the code snippets for generating normally distributed data and calculating estimates using various Python packages like <a target="_blank" href="https://towardsdatascience.com/numpy-essentials-for-data-science-25dc39fae39">numpy</a>, <a target="_blank" href="https://www.scipy.org/docs.html">scipy</a>, <a target="_blank" href="https://matplotlib.org/">matplotlib</a>, and so on.</p>
</li>
</ul>
<p>And with that, let's get started.</p>
<h2 id="heading-what-is-normal-or-guassian-distributon">What is normal or Guassian distributon?</h2>
<p>When we plot a dataset such as a histogram, the shape of that charted plot is what we call its distribution. The most commonly observed shape of continuous values is the bell curve, which is also called the Gaussian or normal distribution.</p>
<p>It is named after the German mathematician, Carl Friedrich Gauss. Some common example datasets that follow Gaussian distribution are:</p>
<ul>
<li><p>Body temperature</p>
</li>
<li><p>People’s Heights</p>
</li>
<li><p>Car mileage</p>
</li>
<li><p>IQ scores</p>
</li>
</ul>
<p>Let’s try to generate the ideal normal distribution and plot it using Python.</p>
<h3 id="heading-how-to-plot-gaussian-distribution-in-python">How to plot Gaussian distribution in Python</h3>
<p>We have libraries like Numpy, scipy, and matplotlib to help us plot an ideal normal curve.</p>
<pre><code class="lang-py"><span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
<span class="hljs-keyword">import</span> scipy <span class="hljs-keyword">as</span> sp
<span class="hljs-keyword">from</span> scipy <span class="hljs-keyword">import</span> stats
<span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt 

<span class="hljs-comment">## generate the data and plot it for an ideal normal curve</span>

<span class="hljs-comment">## x-axis for the plot</span>
x_data = np.arange(<span class="hljs-number">-5</span>, <span class="hljs-number">5</span>, <span class="hljs-number">0.001</span>)

<span class="hljs-comment">## y-axis as the gaussian</span>
y_data = stats.norm.pdf(x_axis, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>)

<span class="hljs-comment">## plot data</span>
plt.plot(x_data, y_data)plt.show()
</code></pre>
<p>Output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/2-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The points on the x-axis are the observations and the y-axis is the likelihood of each observation.</p>
<p>We generated regularly spaced observations in the range (-5, 5) using <code>np.arange()</code>. Then we ran it through the <code>norm.pdf()</code> function with a mean of 0.0 and a standard deviation of 1 which returned the likelihood of that observation.</p>
<p>Observations around 0 are the most common and the ones around -5.0 and 5.0 are rare. The technical term for the <code>pdf()</code> function is the <a target="_blank" href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html"><strong>probability density function</strong>.</a></p>
<h2 id="heading-how-to-test-for-gaussian-distribution">How to test for Gaussian Distribution</h2>
<p>It is important to note that not all data fits the Gaussian distribution, and we have to discover the distribution either by reviewing histogram plots of the data or by implementing some statistical tests.</p>
<p>Some examples of observations that do not fit a Gaussian distribution and instead may fit an exponential (hockey-stick shape) include:</p>
<ul>
<li><p>People’s incomes</p>
</li>
<li><p>Population of countries</p>
</li>
<li><p>Sales of cars.</p>
</li>
</ul>
<p>Until now, we have just talked about the ideal bell-shaped curve of the distribution but if we had to work with random data and figure out its distribution.</p>
<p>This is how we'll proceed:</p>
<ul>
<li><p>Create some random data for this example using numpy’s <code>randn()</code> function.</p>
</li>
<li><p>Plot the data using a histogram and analyze the returned graph for the expected shape.</p>
</li>
</ul>
<p>In reality, the data is rarely perfectly Gaussian, but it will have a Gaussian-like distribution. If the sample size is large enough, we treat it as Gaussian.</p>
<p>Note that you may have to change the plotting configuration (scale, number of bins, and so on) to look for the desired pattern.</p>
<p>Let's take a look at some code:</p>
<pre><code class="lang-py"><span class="hljs-comment">## setting the seed for the random generation</span>
np.random.seed(<span class="hljs-number">1</span>)

<span class="hljs-comment">## generating univariate data</span>
data = <span class="hljs-number">10</span> * np.random.randn(<span class="hljs-number">1000</span>) + <span class="hljs-number">100</span>

<span class="hljs-comment">## plotting the data</span>
plt.hist(data)plt.show()
</code></pre>
<p>Output:</p>
<p>Here’s the output of the code above with the histogram plot of the data:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/3-1.png" alt="Image for post" width="600" height="400" loading="lazy"></p>
<p>The plot looks more like a simple set of blocks. But we change the scale, which in this case is the arbitrary number of bins in the histogram.</p>
<p>Let’s specify the number of bins and plot it again:</p>
<pre><code class="lang-py">plt.hist(data, bins=<span class="hljs-number">100</span>)
plt.show()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/4-1.png" alt="Image for post" width="600" height="400" loading="lazy"></p>
<p>We can now see that the curve looks closer to a Gaussian bell-shaped curve.</p>
<p>Although, notice that we have a few observations that are going out of bounds and can be seen as noise.</p>
<p>This points to another important takeaway when working with sample dataset – you should always expect some noise or outliers.</p>
<h2 id="heading-estimates-of-location">Estimates of Location</h2>
<p>A fundamental step in exploring a dataset is getting a summarized value for each feature or variable. This is commonly an estimate of where most of the data is located, or in other words, the <strong>central tendency</strong>.</p>
<p>At first, summarizing the data might sound like a piece of cake – just take the mean of the data. In reality, although the mean is very easy to compute and use, it may not always be the best measure for the central value.</p>
<p>To solve this problem, statisticians have developed alternative estimates to mean.</p>
<p>We are going to use the Boston dataset from the sklearn package.</p>
<p>Note that I’ve dropped a few columns, and this is what the dataframe looks like now:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/5-1.png" alt="Image for post" width="600" height="400" loading="lazy"></p>
<p>Let’s look over the commonly used estimates of location with the help of an actual sample dataset, rather than Greek symbols:</p>
<h3 id="heading-mean">Mean</h3>
<p>The sum of all values divided by the number of values, also known as the average</p>
<p>Here's how to calculate the mean of the <code>Age</code> variable:</p>
<pre><code class="lang-py">df[<span class="hljs-string">'Age'</span>].mean()

<span class="hljs-comment">## output: 68.57490118577076</span>
</code></pre>
<h3 id="heading-weighted-mean">Weighted mean</h3>
<p>The sum of all values times a weight divided by the sum of the weights. This is also known as the weighted average.</p>
<p>Here are two main motivations for using a weighted mean:</p>
<ul>
<li><p>Some observations are intrinsically more variable (high standard deviation) than others, and highly variable observations are given a lower weight.</p>
</li>
<li><p>The collected data does not equally represent the different groups that we are interested in measuring.</p>
</li>
</ul>
<h3 id="heading-median">Median</h3>
<p>The value that separates one half of the data from the other, thus dividing it into a higher and lower half. This is also called the 50th percentile.</p>
<p>Here's how to calculate the median of the <code>Age</code> variable:</p>
<pre><code class="lang-py">df[<span class="hljs-string">'Age'</span>].median()

<span class="hljs-comment">## output: 77.5</span>
</code></pre>
<h3 id="heading-percentile">Percentile</h3>
<p>The value such that <em>P</em> percent of the data lies below, also known as quantile.</p>
<p>The <code>describe</code> method makes it easy to find the percentile:</p>
<pre><code class="lang-py">df.describe()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/6-1.png" alt="Image for post" width="600" height="400" loading="lazy"></p>
<p>This gives summary statistics of all the numerical variables. Note that the metrics are different for categorical variables.</p>
<h3 id="heading-weighted-median">Weighted median</h3>
<p>The value such that one half of the sum of the weights lies above and below the sorted data.</p>
<h3 id="heading-trimmed-mean">Trimmed mean</h3>
<p>The average of all values after dropping a fixed number of extreme values.</p>
<p>A trimmed mean eliminates the influence of extreme values. For example, while judging an event, we can calculate the final score using the trimmed mean of all the scores so that no judge can manipulate the result.</p>
<p>This is also known as the truncated mean.</p>
<p>For this, we are going to use the stats module from the <code>scipy</code> library:</p>
<pre><code class="lang-py"><span class="hljs-comment">## trim = 0.1 drops 10% from each end</span>

stats.trim_mean(df[<span class="hljs-string">'Age'</span>], <span class="hljs-number">0.1</span>)

<span class="hljs-comment">## output: 71.19605911330049</span>
</code></pre>
<h3 id="heading-outlier">Outlier</h3>
<p>An outlier, or extreme value, is a data value that is very different from most of the data. The median is referred to as a <em>robust</em> estimate of location since it is not influenced by <em>outliers</em>, i.e. extreme cases whereas the mean is sensitive to outliers.</p>
<h2 id="heading-estimates-of-variability">Estimates of Variability</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/7-1.png" alt="Image for post" width="600" height="400" loading="lazy"></p>
<p>Besides location, we have another method of summarizing a feature. <strong>Variability</strong>, also referred to as dispersion, tells us how spread-out or clustered the data is.</p>
<p>Calculating the variability measures for the same dataframe using libraries like pandas, numpy, and scipy.</p>
<h3 id="heading-deviations">Deviations</h3>
<p>The difference between the observed values and the estimate of location. Deviations are sometimes called errors or residuals.</p>
<h3 id="heading-variance">Variance</h3>
<p>The sum of squared deviations from the mean divided by <em>n</em> — 1 where <em>n</em> is the number of data values. This is also called the mean-squared-error.</p>
<pre><code class="lang-py">df[<span class="hljs-string">'Age'</span>].var()
</code></pre>
<h3 id="heading-standard-deviation">Standard deviation</h3>
<p>The square root of the variance.</p>
<pre><code class="lang-py">df[<span class="hljs-string">'Age'</span>].std()

<span class="hljs-comment">## output: 28.148861406903617</span>
</code></pre>
<h3 id="heading-mean-absolute-deviation">Mean absolute deviation</h3>
<p>The mean of the absolute values of the deviations from the mean. This is also referred to as the l1-norm or Manhattan norm.</p>
<p>I’ve covered this in more detail along with a mathematical explanation here: <a target="_blank" href="https://towardsdatascience.com/calculating-vector-p-norms-linear-algebra-for-data-science-iv-400511cffcf0">Calculating Vector P-Norms — Linear Algebra for Data Science -IV</a></p>
<h3 id="heading-median-absolute-deviation-from-the-median">Median absolute deviation from the median</h3>
<p>The median of the absolute values of the deviations from the median.</p>
<pre><code class="lang-py">df[<span class="hljs-string">'Age'</span>].mad()

<span class="hljs-comment">## output: 24.610885188020433</span>
</code></pre>
<h3 id="heading-range">Range</h3>
<p>The difference between the largest and the smallest value in a data set.</p>
<p>We can calculate the range of a variable using the min and max from the summary statistics of the dataframe:</p>
<pre><code class="lang-py">df[<span class="hljs-string">'Age'</span>].iloc[df[<span class="hljs-string">'Age'</span>].idxmax] - df[<span class="hljs-string">'Age'</span>].iloc[df[<span class="hljs-string">'Age'</span>].idxmin()]

<span class="hljs-comment">## output: 97.1</span>
</code></pre>
<h3 id="heading-order-statistics">Order statistics</h3>
<p>Order statistics, or ranks, are metrics based on the data values sorted from smallest to biggest.</p>
<h3 id="heading-percentile-1">Percentile</h3>
<p>The value such that <em>P</em> percent of the values take on this value or less and (100–P) percent take on this value or more. This is sometimes called quantile.</p>
<h3 id="heading-interquartile-range">Interquartile range</h3>
<p>Interquartile range, or IQR, is the difference between the 75th percentile and the 25th percentile.</p>
<pre><code class="lang-py">Q1 = df[<span class="hljs-string">'Age'</span>].quantile(<span class="hljs-number">0.25</span>)
Q3 = df[<span class="hljs-string">'Age'</span>].quantile(<span class="hljs-number">0.75</span>)
IQR = Q3 - Q1

<span class="hljs-comment">## Output: 49.04999999999999</span>
</code></pre>
<p>Now that you have a clear understanding of Gaussian distribution and common estimates of location and variability, you can summarize and interpret the data easily using these statistical methods.</p>
<h2 id="heading-data-science-with-harshithttpswwwyoutubecomcdatasciencewithharshitsubconfirmation1"><a target="_blank" href="https://www.youtube.com/c/DataSciencewithHarshit?sub_confirmation=1">Data Science with Harshit</a></h2>
<p><a target="_blank" href="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_ANbV9lVA-M%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_ANbV9lVA-M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_ANbV9lVA-M%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube">Embedded content</a></p>
<p>With this channel, I am planning to roll out a couple of <a target="_blank" href="https://towardsdatascience.com/hitchhikers-guide-to-learning-data-science-2cc3d963b1a2?source=---------8------------------">series covering the entire data science space</a>. Here is why you should be subscribing to the <a target="_blank" href="https://www.youtube.com/channel/UCH-xwLTKQaABNs2QmGxK2bQ">channel</a>:</p>
<ul>
<li><p>This series would cover all the required/demanded quality tutorials on each of the topics and subtopics like <a target="_blank" href="https://towardsdatascience.com/python-fundamentals-for-data-science-6c7f9901e1c8?source=---------5------------------">Python fundamentals for Data Science</a>.</p>
</li>
<li><p>Explained <a target="_blank" href="https://towardsdatascience.com/practical-reasons-to-learn-mathematics-for-data-science-1f6caec161ea?source=---------9------------------">Mathematics and derivations</a> of why we do what we do in ML and Deep Learning.</p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=a2pkZCleJwM&amp;t=2s">Podcasts with Data Scientists and Engineers</a> at Google, Microsoft, Amazon, and CEOs of big data-driven companies.</p>
</li>
<li><p><a target="_blank" href="https://towardsdatascience.com/building-covid-19-analysis-dashboard-using-python-and-voila-ee091f65dcbb?source=---------2------------------">Projects and instructions</a> to implement the topics learned so far. Learn about new certifications, Bootcamps, and resources to crack those certifications like this <a target="_blank" href="https://youtu.be/yapSsspJzAw"><strong>TensorFlow Developer Certificate Exam by Google</strong></a>.</p>
</li>
</ul>
<p>If this tutorial was helpful, you should check out my data science and machine learning courses on <a target="_blank" href="https://www.wiplane.com/">Wiplane Academy</a>. They are comprehensive yet compact and helps you build a solid foundation of work to showcase.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Statistics for Data Science — a Complete Guide for Aspiring ML Practitioners ]]>
                </title>
                <description>
                    <![CDATA[ In this hyper-connected world, data are being generated and consumed at an unprecedented pace. As much as we enjoy this superconductivity of data, it invites abuse as well. Data professionals need to be trained to use statistical methods not only to ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/statistics-for-data-science/</link>
                <guid isPermaLink="false">66d45f584a7504b7409c3421</guid>
                
                    <category>
                        <![CDATA[ Data Science ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ statistics ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Harshit Tyagi ]]>
                </dc:creator>
                <pubDate>Wed, 04 Nov 2020 19:07:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/11/bradley-dunn-eqbLoTqQKZs-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this hyper-connected world, data are being generated and consumed at an unprecedented pace.</p>
<p>As much as we enjoy this superconductivity of data, it invites abuse as well. Data professionals need to be trained to use statistical methods not only to interpret numbers but to uncover such abuse and protect us from being misled.</p>
<p>Not many data scientists are formally trained in statistics. There are also very few good books and courses that teach these statistical methods from a data science perspective.</p>
<p>Through this post, I intend to shed some light on the following:</p>
<ul>
<li><p><strong>What is Statistics?</strong></p>
</li>
<li><p><strong>Statistics in relation with machine learning.</strong></p>
</li>
<li><p><strong>Why</strong> you should master <strong>statistics</strong></p>
</li>
<li><p><strong>What c</strong>urriculum**** <strong>you should follow</strong> to master these topics</p>
</li>
<li><p><strong>How to s</strong>tudy statistics**** to become a practitioner rather than a test-taker</p>
</li>
<li><p><strong>P</strong>ractical tips**** <strong>and learning resources</strong></p>
</li>
</ul>
<h2 id="heading-what-is-statistics">What is Statistics?</h2>
<p>Statistics is a set of mathematical methods and tools that enable us to answer important questions about data. It is divided into two categories:</p>
<ol>
<li><p><strong>Descriptive Statistics</strong> - this offers methods to summarise data by transforming raw observations into meaningful information that is easy to interpret and share.</p>
</li>
<li><p><strong>Inferential Statistics</strong> - this offers methods to study experiments done on small samples of data and chalk out the inferences to the entire population (entire domain).</p>
</li>
</ol>
<p>Now, statistics and machine learning are two closely related areas of study. Statistics is an important prerequisite for applied machine learning, as it helps us select, evaluate and interpret predictive models.</p>
<h1 id="heading-statistics-and-machine-learning">Statistics and Machine Learning</h1>
<p>The core of machine learning is centered around statistics. You can’t solve real-world problems with machine learning if you don’t have a good grip of statistical fundamentals.</p>
<p>There are certainly some factors that make learning statistics hard. I'm talking about mathematical equations, greek notation, and meticulously defined concepts that make it difficult to develop an interest in the subject.</p>
<p>We can address these issues with simple and clear explanations, appropriately paced tutorials, and hands-on labs to solve problems with applied statistical methods.</p>
<p>From exploratory data analysis to designing hypothesis testing experiments, statistics play an integral role in solving problems across all major industries and domains.</p>
<p>Anyone who wishes to develop a deep understanding of machine learning should learn how statistical methods form the foundation for regression algorithms and classification algorithms, how statistics allow us to learn from data, and how it helps us extract meaning from unlabeled data.</p>
<h2 id="heading-why-should-you-master-statistics">Why should you master statistics?</h2>
<p>Every organisation is striving to become data-driven. This is why we are witnessing such an increase in demand for data scientists and analysts.</p>
<p>Now, to solve problems, answer questions, and map out a strategy, we need to make sense of the data. Luckily, statistics offers a collection of tools to produce those insights.</p>
<h3 id="heading-from-data-to-knowledge">From Data to Knowledge</h3>
<p>In isolation, raw observations are just data. We use <strong>descriptive statistics</strong> to transform these observations into insights that make sense.</p>
<p>Then we can use <strong>inferential statistics</strong> to study small samples of data and extrapolate our findings to the entire population.</p>
<h3 id="heading-statistics-helps-answer-questions-like">Statistics helps answer questions like...</h3>
<ul>
<li><p>What features are the most important?</p>
</li>
<li><p>How should we design the experiment to develop our product strategy?</p>
</li>
<li><p>What performance metrics should we measure?</p>
</li>
<li><p>What is the most common and expected outcome?</p>
</li>
<li><p>How do we differentiate between noise and valid data?</p>
</li>
</ul>
<p>All these are common and important questions that data teams have to answer on a daily basis.</p>
<p>The answers help us make decisions effectively. Statistical methods not only help us set up predictive modeling projects but also to interpret the results.</p>
<h2 id="heading-statistics-and-machine-learning-projects">Statistics and Machine Learning Projects</h2>
<p><a target="_blank" href="https://towardsdatascience.com/task-cheatsheet-for-almost-every-machine-learning-project-d0946861c6d0">Almost every machine learning project</a> consists of the following tasks. And statistics play a central role in all of them in some shape or form. Here’s how:</p>
<h3 id="heading-defining-a-problem-statement">Defining a Problem Statement</h3>
<p>The most crucial part of predictive modeling is the actual definition of the problem that gives us the real objective to pursue.</p>
<p>This helps us decide the type of problem we're dealing with (that is, regression or classification). And it also helps us decide the structure and types of the inputs, outputs and metrics with regards to the objective.</p>
<p>But problem framing is not always straightforward. If you're new to Machine Learning, it may require significant exploration of the observations in the domain. Two main concepts to master here are <strong>exploratory data analysis (EDA) and data mining</strong>.</p>
<h3 id="heading-initial-data-exploration">Initial Data Exploration</h3>
<p>Data exploration involves gaining a deep understanding of both the distributions of variables and the relationships between variables in your data.</p>
<p>In part, domain expertise helps you gain this mastery over a specific type of variable. Nevertheless, both experts and newcomers to the field benefit from actually handling real observations from the domain.</p>
<p>Important related concepts in statistics boil down to learning <strong>descriptive statistics and data visualization.</strong></p>
<h3 id="heading-data-cleaning">Data Cleaning</h3>
<p>Often, the data points you've collected from an experiment or a data repository are <strong>not</strong> pristine. The data may have been subjected to processes or manipulations that damaged its integrity. This further affects the downstream processes or models that use the data.</p>
<p>Common examples include missing values, data corruption, data errors (from a bad sensor), and unformatted data (observations with different scales).</p>
<p>If you want to master cleaning methods, you need to learn about <strong>outlier detection</strong> and <strong>missing value imputation.</strong></p>
<h3 id="heading-data-preparation-and-setting-up-transformation-pipelines">Data Preparation and setting up transformation pipelines</h3>
<p>If data contains errors and inconsistencies, you often can't use it directly for modeling.</p>
<p>First, the data might need to go through a set of transformations to change its shape or structure and make it more suitable for the problem you've defined or the learning algorithms you're using.</p>
<p>Then you can develop a pipeline of such transformations that you apply to the data to produce consistent and compatible input for the model.</p>
<p>You should master concepts like <strong>data sampling and feature selection methods, data transforms, scaling,</strong> and <strong>encoding.</strong></p>
<h3 id="heading-model-selection-amp-evaluation">Model Selection &amp; Evaluation</h3>
<p>A key step in solving a predictive problem is selecting and evaluating the learning method. Estimation statistics help you score model predictions on unseen data.</p>
<p>Experimental design is a subfield of statistics that drives the selection and evaluation process of a model. It demands a good understanding of <strong>statistical hypothesis tests</strong> and <strong>estimation statistics.</strong></p>
<h3 id="heading-fine-tuning-the-model">Fine-tuning the model</h3>
<p>Almost every machine learning algorithm has a suite of hyperparameters that allow you to customise the learning method for your chosen problem framing.</p>
<p>This hyperparameter tuning is often empirical in nature, rather than analytical. It requires large suites of experiments in order to evaluate the effect of different hyperparameter settings on the performance of the model.</p>
<h2 id="heading-statistics-curriculum-for-practitioners">Statistics Curriculum for Practitioners</h2>
<p>A good statistics curriculum for practitioners should not just cover the plethora of methods and tools I just discussed. It should also cover and explore the most commonly faced issues in the industry.</p>
<p>The following is a list of widely used skills you'll need to know to ace data science and ML interviews and get a job in the field.</p>
<h3 id="heading-general-statistics-skills">General Statistics Skills</h3>
<ul>
<li><p>How to define statistically answerable questions for effective decision making.</p>
</li>
<li><p>Calculating and interpreting common statistics and how to use standard data visualization techniques to communicate findings.</p>
</li>
<li><p>Understanding of how mathematical statistics is applied to the field, concepts such as the central limit theorem and the law of large numbers.</p>
</li>
<li><p>Making inferences from estimates of location and variability <strong>(ANOVA).</strong></p>
</li>
<li><p>How to identify the relationship between target variables and independent variables.</p>
</li>
<li><p>How to design statistical hypothesis testing experiments, A/B testing, and so on.</p>
</li>
<li><p>How to calculate and interpret performance metrics like p-value, alpha, type1 and type2 errors, and so on.</p>
</li>
</ul>
<h3 id="heading-important-statistics-concepts">Important Statistics Concepts</h3>
<ul>
<li><p><strong>Getting Started—</strong> Understanding types of data (rectangular and non-rectangular), estimate of location, estimate of variability, data distributions, binary and categorical data, correlation, relationship between different types of variables.</p>
</li>
<li><p><strong>Distribution of Statistic</strong> — random numbers, the law of large numbers, Central Limit Theorem, standard error, and so on.</p>
</li>
<li><p><strong>Data sampling and Distributions —</strong> random sampling, sampling bias, selection bias, sampling distribution, bootstrapping, confidence interval, normal distribution, t-distribution, binomial distribution, chi-square distribution, F-distribution, Poisson and exponential distribution.</p>
</li>
<li><p><strong>Statistical Experiments and Significance Testing—</strong> A/B testing, conducting hypothesis tests (Null/Alternate), resampling, statistical significance, confidence interval, p-value, alpha, t-tests, degree of freedom, ANOVA, critical values, covariance and correlation, effect size, statistical power.</p>
</li>
<li><p><strong>Nonparametric Statistical Methods —</strong> rank data, normality tests, normalization of data, rank correlation, rank significance tests, independence test</p>
</li>
</ul>
<h2 id="heading-practical-learning-tips">Practical Learning Tips</h2>
<p>Most universities have designed their statistics course curricula to test the student’s cramming power. They just check if students can solve equations, define terminologies, and identify plots deriving equations, rather than focusing on applying these methods to solve real-world problems.</p>
<p>Aspiring practitioners, however, should follow a step-by-step process of learning and implementing statistical methods on different problems using executable Python code.</p>
<p>Let's look at the two main approaches to studying statistics a bit more in depth:</p>
<h3 id="heading-top-down-approach">Top-down approach</h3>
<p>Let's say you are asked to design an experiment to test the efficiency of two versions of a product feature. This feature is supposed to increase the user engagement on an online portal.</p>
<p>With a top-down approach, you'll first learn more about the problem. Then once the objective is clear, you can learn to apply the appropriate statistical methods.</p>
<p>This keeps you engaged and offers a better practical learning experience.</p>
<h3 id="heading-bottom-up-approach">Bottom-up approach</h3>
<p>This approach is how most universities and online courses teach statistics. It focuses on learning the theoretical concepts with mathematical notation, the history of that concept, and how to implement it.</p>
<p>For people like me who tend to lose interest in theoretical learning, this is not the right way to learn applied statistics. It makes it too meta, which renders the subject dry and depressing without any direct link to problem solving.</p>
<p>As you can probably tell, I recommend a top-down approach to studying statistics.</p>
<p>So now let's look at some specific resources I recommend to get you started down the right path.</p>
<h3 id="heading-learning-resources">Learning Resources</h3>
<ul>
<li><a target="_blank" href="https://learning.oreilly.com/library/view/practical-statistics-for/9781491952955/"><strong>Book on Practical Statistics</strong></a> – This will teach you statistics from a Data Science standpoint. You should read at least the first 3 chapters of this book.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li><a target="_blank" href="https://www.khanacademy.org/math/statistics-probability"><strong>Statistics and Probability | Khan Academy</strong></a> – This course will prepare you well for all the statistics and probability related questions during the interview. A free course with a good compilation of video lectures and practice problems.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li><a target="_blank" href="https://wwnorton.com/books/Naked-Statistics/"><strong>Naked Statistics</strong></a> <strong>–</strong> For people who dread mathematics and prefer to understand practical examples, this is an amazing book that explains how statistics is applied in real-life scenarios.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/3.png" alt="Image" width="600" height="400" loading="lazy"></p>
<ul>
<li><strong>Statistical Methods for Machine Learning –</strong> This book serves as a crash course in statistical methods for machine learning practitioners. Ideally, those with a background as a developer.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/11/Screenshot-from-2020-11-03-22-39-45.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h1 id="heading-next-up">Next up…</h1>
<p>I will be creating a series of tutorials on each of the above-mentioned topics following a code-first approach so that we can understand and visualize the meaning and application of these concepts.</p>
<p>If I’ve missed any of the details or if you want me to cover any other aspect of statistics, respond to this story and I’ll add it to the curriculum.</p>
<h1 id="heading-data-science-with-harshithttpswwwyoutubecomcdatasciencewithharshitsubconfirmation1"><a target="_blank" href="https://www.youtube.com/c/DataSciencewithHarshit?sub_confirmation=1">Data Science with Harshit</a></h1>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/_ANbV9lVA-M" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>With this channel, I am planning to roll out a couple of <a target="_blank" href="https://towardsdatascience.com/hitchhikers-guide-to-learning-data-science-2cc3d963b1a2?source=---------8------------------">series covering the entire data science space</a>. Here is why you should be subscribing to the <a target="_blank" href="https://www.youtube.com/channel/UCH-xwLTKQaABNs2QmGxK2bQ">channel</a>:</p>
<ul>
<li><p>This series would cover all the required/demanded quality tutorials on each of the topics and subtopics like <a target="_blank" href="https://towardsdatascience.com/python-fundamentals-for-data-science-6c7f9901e1c8?source=---------5------------------">Python fundamentals for Data Science</a>.</p>
</li>
<li><p>Explained <a target="_blank" href="https://towardsdatascience.com/practical-reasons-to-learn-mathematics-for-data-science-1f6caec161ea?source=---------9------------------">Mathematics and derivations</a> of why we do what we do in ML and Deep Learning.</p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=a2pkZCleJwM&amp;t=2s">Podcasts with Data Scientists and Engineers</a> at Google, Microsoft, Amazon, etc, and CEOs of big data-driven companies.</p>
</li>
<li><p><a target="_blank" href="https://towardsdatascience.com/building-covid-19-analysis-dashboard-using-python-and-voila-ee091f65dcbb?source=---------2------------------">Projects and instructions</a> to implement the topics learned so far. Learn about new certifications, Bootcamp, and resources to crack those certifications like this <a target="_blank" href="https://youtu.be/yapSsspJzAw"><strong>TensorFlow Developer Certificate Exam by Google.</strong></a></p>
</li>
</ul>
<p>If this tutorial was helpful, you should check out my data science and machine learning courses on <a target="_blank" href="https://www.wiplane.com/">Wiplane Academy</a>. They are comprehensive yet compact and helps you build a solid foundation of work to showcase.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
