<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Akash Dugam on Medium]]></title>
        <description><![CDATA[Stories by Akash Dugam on Medium]]></description>
        <link>https://medium.com/@dugamakash?source=rss-19a974a0393------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*QFdhlh_wCF6CoaO6wuUqNw.jpeg</url>
            <title>Stories by Akash Dugam on Medium</title>
            <link>https://medium.com/@dugamakash?source=rss-19a974a0393------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 17:05:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dugamakash/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Descriptive Statistics: Mastering the Art of Description!]]></title>
            <link>https://dugamakash.medium.com/descriptive-statistics-mastering-the-art-of-description-c8a6ef41d474?source=rss-19a974a0393------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8a6ef41d474</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Akash Dugam]]></dc:creator>
            <pubDate>Wed, 20 Nov 2024 06:54:43 GMT</pubDate>
            <atom:updated>2024-11-20T06:54:43.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K5mt0ORmUmZEtOTW.png" /></figure><p>Imagine you’re a banker analyzing customer savings trends or a manager looking at sales performance. You’ve got mountains of numbers, but how do you make sense of it all? This is where descriptive statistics come in. They help you turn raw data into actionable insights, summarizing the essential details so you can make smarter decisions.</p><p>Think of descriptive statistics as a toolkit: measures like averages tell you what’s typical, while measures of spread show how much variation exists. By using these tools, you can quickly spot trends, compare different datasets, or pinpoint areas that need your attention. For example, you could identify the average account balance of your customers or understand the variability in loan repayments.</p><p>In this blog, we’ll break down key concepts like mean, median, standard deviation, and more — all with relatable examples you can apply directly to your work or everyday life. Ready to get practical and put your data to work? Let’s dive in!</p><p>Before we start, we should know the types of data that generally categorized in statistics.</p><h3>Types of Data in Statistics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/0*FB44FLJ4IQ8KY49J.png" /></figure><p><strong>Quantitative Data (Numerical)</strong></p><ul><li><strong>Definition</strong>: Data that can be measured numerically.</li><li><strong>Examples</strong>: Account balance, loan amount, interest rate.</li></ul><p><strong>Qualitative Data (Categorical)</strong></p><ul><li><strong>Definition</strong>: Data that describes qualities or characteristics.</li><li><strong>Examples</strong>: Account type (Savings, Checking), customer satisfaction level (Low, Medium, High).</li></ul><p><strong>Types of Quantitative Data</strong></p><ul><li><strong>Discrete Data</strong>: Countable values, e.g., number of loans taken.</li><li><strong>Continuous Data</strong>: Measurable values, e.g., account balances.</li></ul><p>That’s it. Hope you have understood the short introduction about the data. Now we can proceed with the types of statistics.</p><h3>Types of Statistics</h3><p>There are generally two types of statistics -</p><ul><li><strong>Descriptive Statistics:</strong> Descriptive statistics summarizes and organizes data in an informative way. Consider a dataset containing monthly account balances of 1,000 customers. Descriptive statistics would help summarize the average balance, the most frequently occurring balance range, and the overall distribution of account balances.</li><li><strong>Inferential Statistics: </strong>Inferential statistics uses a random sample of data taken from a population to make inferences or predictions about the population.</li></ul><p>Now let’s deep dive into descriptive statistics that we need to understand data in more meaningful way.</p><h3>What is Descriptive Statistics?</h3><blockquote>Descriptive statistics are methods used to summarize, organize, and present data in a clear and understandable way.</blockquote><p>Instead of drawing conclusions or making predictions, descriptive statistics focus on describing the main features of a dataset.</p><h3>Measure of Central Tendency</h3><blockquote>Central tendency is a statistical measure used to determine a single score that defines the center of a distribution. The purpose of central tendency is to provide a single value that represents the entire dataset, giving a sense of the “average” or “typical” value within the data.</blockquote><p>The three main measures of central tendency are:</p><ol><li><strong>Mean</strong> (Arithmetic Average)</li><li><strong>Median</strong></li><li><strong>Mode</strong></li></ol><p>Each measure has its own strengths and is used in different contexts, depending on the nature and distribution of the data.</p><h4><strong>Mean (Arithmetic Average)</strong></h4><p>The mean is the sum of all data points divided by the number of data points. It is one of the most common and widely used measures of central tendency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*SV445yzWrA6bShPuH0vrhg.png" /></figure><p>Suppose you want to calculate the average balance in savings accounts. If the balances are 1,000, 2,500, and 3,000, the mean balance is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*FwpiP-k5GYDCcynM7L_Fzg.png" /></figure><p><strong>Properties of the Mean</strong>:</p><ul><li><strong>Sensitive to Outliers</strong>: The mean can be heavily influenced by extremely high or low values. For instance, if one client has a very large bank account balance compared to others, it can distort the mean, making it less representative of the typical account balance.</li><li><strong>Use Case</strong>: The mean is suitable for datasets without extreme values and when every value in the data contributes equally to the final result, such as average transaction amounts.</li></ul><h4><strong>Median</strong></h4><p>The median is the middle value of a dataset when it is ordered from smallest to largest. If there is an even number of data points, the median is the average of the two middle values.</p><p><strong>How to Calculate</strong>:</p><ul><li>Arrange the data in ascending order.</li><li>Identify the middle value. If there are two middle values, calculate their mean.</li></ul><p>Suppose we have loan amounts of 5,000, 15,000, 20,000, 25,000, and 100,000. The median loan amount is 20,000, as it is the middle value in the ordered list.</p><p><strong>Properties of the Median</strong>:</p><ul><li><strong>Not Affected by Outliers</strong>: The median is robust to outliers and skewed data. It provides a better measure of central tendency when data is not symmetrically distributed.</li><li><strong>Use Case</strong>: The median is particularly useful when analyzing income data, property prices, or loan amounts, where a few very high or very low values can skew the mean.</li></ul><h4><strong>Mode</strong></h4><p>The mode is the value that appears most frequently in a dataset. A dataset may have one mode, more than one mode, or no mode at all.</p><p><strong>Types of Mode</strong>:</p><ul><li><strong>Unimodal</strong>: One mode</li><li><strong>Bimodal</strong>: Two modes</li><li><strong>Multimodal</strong>: More than two modes</li></ul><p>If a bank analyzes the number of times customers visit branches in a month, and most customers visit twice, then the mode is 2 visits.</p><p><strong>Properties of the Mode</strong>:</p><ul><li><strong>Useful for Categorical Data</strong>: The mode is the only measure of central tendency that can be used with nominal data, like the most common type of loan (e.g., personal loan, mortgage, auto loan).</li><li><strong>Use Case</strong>: Mode is useful for identifying the most common transaction type or the most frequent customer complaint.</li></ul><h4>Choosing the Right Measure of Central Tendency?</h4><p>Since there are 3 ways we can measure the central tendency. Which one is best?</p><p><strong>Mean is appropriate for:</strong></p><ul><li>Normally distributed data.</li><li>Financial metrics like average loan size, average account balance, etc., when outliers are not a concern.</li></ul><p><strong>Median is preferred for:</strong></p><ul><li>Skewed distributions or when outliers are present.</li><li>Income or wealth data analysis, where large variations exist.</li></ul><p><strong>Mode is useful for:</strong></p><ul><li>Analyzing categorical data.</li><li>Identifying the most common transaction types or services used.</li></ul><h3>Measures of Variability (Spread)</h3><p>Variability, or the spread of data, refers to how spread out or dispersed the values in a dataset are. Understanding the variability is crucial because it provides insights into the consistency, reliability, and predictability of data. In banking, variability can help identify risk, understand customer behavior, or assess the stability of financial metrics.</p><p><strong>Key Measures of Variability:</strong></p><ol><li><strong>Range</strong></li><li><strong>Interquartile Range (IQR)</strong></li><li><strong>Variance</strong></li><li><strong>Standard Deviation</strong></li></ol><h4>Range</h4><p>The range is the difference between the highest and lowest scores in a data set and is the simplest measure of spread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*qPEOen1tmRcGZ6HtuPPqDg.png" /></figure><p>If a bank’s loan amounts range from 5,000 to 100,000, the range is 100,000–5000 = 95000 Rs.</p><p><strong>Advantages</strong>:</p><ul><li>Simple to calculate and understand.</li><li>Provides a quick sense of the spread.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Very sensitive to outliers.</li><li>Doesn’t give any information about the distribution of values within the range.</li></ul><p><strong>Use Case</strong>: Useful for getting a quick idea of the spread in loan amounts or transaction values but not reliable for datasets with outliers.</p><h4><strong>Interquartile Range (IQR)</strong></h4><p>The <strong>interquartile range</strong> (IQR) is a measure of variability, based on dividing a data set into quartiles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7NmRRaHUbykTWzgHUDfsQ.png" /></figure><p><em>A </em><strong><em>quartile</em></strong><em> is a type of quantile. The first quartile (Q1) is defined as the middle number between the smallest number and the median of the data set. The second quartile (Q2) is the median of the data. The third quartile (Q3) is the middle value between the median and the highest value of the data set.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*PDJdTbEDxGaw3TSqJceUzQ.png" /></figure><p>Let’s take an example:</p><p>List = [25, 33, 14, 31, 54, 76, 57, 87, 81]</p><p>Let’s find the median first:</p><p>M<strong>edian</strong> = 54 , it separates the given data sets into to equal halves</p><p>So Q2=54(median of whole table)</p><p>Q1=14(median of upper half, from row 1 to 5)</p><p>Q3=57(median of lower half, from row 5 to 9)</p><p>For the above example :</p><p><strong>IQR(Inter Quartile Range ) = Q3 — Q1 = 57–14= 43</strong></p><blockquote>One of the application of IQR is → <em>The interquartile range is often used to find outliers in data.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*K7S7hYbQNRj_zLgk.png" /></figure><h4>Variance</h4><p>Variance measures the average squared deviation of each data point from the mean. It quantifies the overall spread of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*ILrZ99fhj0-0ZsaOgddrKQ.png" /></figure><p>If analyzing monthly customer deposits, a high variance indicates that deposit amounts are highly inconsistent.</p><p><strong>Advantages</strong>:</p><ul><li>Uses all data points, providing a comprehensive measure of spread.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Squared units make interpretation less intuitive.</li><li>Sensitive to outliers.</li></ul><h4>Standard Deviation</h4><p>The standard deviation is the square root of the variance, providing a measure of spread in the same units as the original data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*b-odHXgAzNkxGnnWiZODYw.png" /></figure><p>If the standard deviation of monthly transaction amounts is high, it means that customers have varying transaction behaviors.</p><p><strong>Advantages</strong>:</p><ul><li>Easier to interpret than variance because it’s in the same units as the data.</li><li>Widely used in statistical analysis.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Still sensitive to outliers.</li></ul><p><strong>Use Case</strong>: Standard deviation is crucial for assessing the risk associated with investment portfolios or analyzing customer spending variability.</p><h3>Sample Vs Population</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S1TFGVFi3vtlnvUx.jpg" /></figure><h4>Population</h4><p>In statistics, a <strong>population</strong> refers to the entire set of individuals or items of interest in a study. It is the complete group that you want to draw conclusions about.</p><p><strong>Examples</strong>:</p><ul><li>All bank account holders in your financial institution.</li><li>Every loan application submitted to the bank in a year.</li><li>The entire set of transactions made by customers over a specific period.</li></ul><p><strong>Characteristics</strong>:</p><ul><li>Populations are often very large and sometimes even infinite (e.g., all possible future transactions).</li><li>Describing or analyzing the entire population is often impractical or impossible due to constraints like time, cost, or accessibility.</li></ul><h4>Sample</h4><p>A <strong>sample</strong> is a subset of the population selected for analysis. It represents the population and is used to make inferences about the overall group.</p><p><strong>Examples</strong>:</p><ul><li>A selection of 1,000 bank account holders from a total of 100,000.</li><li>Analyzing 500 randomly selected loan applications to understand approval rates.</li><li>Studying 10,000 transactions out of a total of 1 million to detect patterns.</li></ul><p><strong>Characteristics</strong>:</p><ul><li>Samples are smaller and easier to analyze compared to the full population.</li><li>Proper sampling methods ensure that the sample represents the population well, reducing bias and increasing the reliability of inferences.</li></ul><h4>Key Differences Between Population and Sample</h4><ol><li><strong>Size</strong>: The population is the complete set, while the sample is a smaller, manageable subset.</li><li><strong>Notation</strong>: In statistics:</li></ol><ul><li>Parameters (values that describe the population) use Greek letters (e.g., μ for mean, σ for standard deviation).</li><li>Statistics (values that describe the sample) use Latin letters (e.g., x̄ for sample mean, s for sample standard deviation).</li></ul><p><strong>Example</strong>:</p><ul><li>If we measure the average account balance for all account holders, it’s a population mean (μ).</li><li>If we calculate the average from a sample of 1,000 account holders, it’s a sample mean (x̄).</li></ul><h4><strong>Why Do We Use Samples Instead of Populations?</strong></h4><ol><li><strong>Practicality</strong>: Analyzing an entire population is usually expensive, time-consuming, and sometimes impossible.</li><li><strong>Efficiency</strong>: With the right sampling techniques, we can draw reliable conclusions about the population using a sample.</li><li><strong>Resource Constraints</strong>: Limited resources, like time and money, make it more feasible to work with samples.</li></ol><h4>Sampling Techniques</h4><p>There are few sampling techniques that needs to be studied →</p><ol><li>Random Sampling</li><li>Stratified Sampling</li><li>Systematic Sampling</li><li>Cluster Sampling</li><li>Convenience Sampling</li></ol><p>Let’s understand each with examples:</p><p><strong>Random Sampling:</strong></p><ul><li>In random sampling, every member of the population has an equal chance of being selected. This method ensures that the sample is unbiased and represents the population accurately</li><li>Imagine a bank wants to analyze the average account balance of its customers. The bank randomly selects 1,000 customers from its entire customer base, giving each customer an equal chance of being chosen.</li></ul><p><strong>Stratified Sampling:</strong></p><ul><li>In stratified sampling, the population is divided into subgroups (strata) based on a specific characteristic. Samples are then taken from each stratum proportionally.</li><li>A bank wants to understand loan approval rates among different income groups. The population is divided into income brackets (e.g., low, middle, high income), and samples are taken from each group proportionally to ensure all income levels are represented.</li><li>It ensures all subgroups are represented.</li></ul><p><strong>Systematic Sampling:</strong></p><ul><li>In systematic sampling, every k-th item from the population list is selected after a random starting point.</li><li>A bank wants to review customer service satisfaction. If there are 10,000 surveys, the bank may select every 100th survey response to form a sample of 100 responses.</li></ul><p><strong>Cluster Sampling:</strong></p><ul><li>In cluster sampling, the population is divided into groups or “clusters,” which are often based on geographical or natural divisions. Instead of sampling individuals from all clusters, the researcher randomly selects entire clusters and then collects data from every individual within those selected clusters.</li><li>This method is particularly useful when dealing with large and geographically dispersed populations.</li></ul><p>Imagine a bank wants to analyze customer satisfaction across multiple branches in a large country. Instead of sampling customers from every branch, the bank can use cluster sampling by:</p><ol><li>Dividing all branches into clusters based on their locations (e.g., city or region).</li><li>Randomly selecting a few clusters (e.g., a few cities or region).</li><li>Surveying all customers in the selected clusters.</li></ol><p>This approach saves time and reduces costs compared to trying to sample individuals from each branch.</p><p><strong>Convenience Sampling:</strong></p><ul><li>Convenience sampling involves selecting individuals who are easiest to reach or sample.</li><li>A bank might use convenience sampling to gather feedback from customers visiting a specific branch because it’s easy and cost-effective.</li></ul><h3>Footnote →</h3><p>Descriptive statistics serve as a solid foundation before diving into more advanced statistical concepts. With this understanding, you can now extract meaningful insights from data. I’ve covered various topics in statistics across my other blogs, which you can explore for further learning. If you have any questions, don’t hesitate to reach out — I’m happy to help!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8a6ef41d474" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Measurement Models — (Part II)]]></title>
            <link>https://dugamakash.medium.com/performance-measurement-models-part-ii-869e7c8dccfb?source=rss-19a974a0393------2</link>
            <guid isPermaLink="false">https://medium.com/p/869e7c8dccfb</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Akash Dugam]]></dc:creator>
            <pubDate>Wed, 15 May 2024 10:31:22 GMT</pubDate>
            <atom:updated>2024-05-15T10:31:22.024Z</atom:updated>
            <content:encoded><![CDATA[<h3>Performance Measurement Models — (Part II)</h3><p>In Part-I of this series, we explored a variety of performance measurement models tailored for classification problems within the realm of Machine Learning. These metrics, including Accuracy, Confusion Matrix, Precision &amp; Recall, and others, play a crucial role in evaluating the effectiveness of classification algorithms. But as we transition from the discrete outcomes of classification to the continuous nature inherent in regression problems, our approach to performance measurement must evolve accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*8lGw2oBEEBORDd-g.png" /></figure><p>In Part II, we shift our focus to regression-related performance metrics. Regression tasks, which predict continuous outcomes based on input features, require distinct metrics for assessing model performance. Here, we will delve into critical metrics such as →</p><ul><li>SSE</li><li>MSE</li><li>RMSE</li><li>MAE</li><li>MAPE</li><li>MPE</li><li>R Squared &amp; Adjusted R Squared</li><li>MAD</li><li>Distribution of error.</li></ul><p>These performance metrics provides insight into the accuracy and efficiency of regression models. Understanding these metrics is essential for developing, evaluating, and refining predictive models that are crucial in countless applications from finance to healthcare.</p><blockquote><strong>Let’s get started, Shall we?</strong></blockquote><h3>SSE (Sum of Squared Error)</h3><p>It is defined as →</p><blockquote><strong><em>SSE is the summation of the squared differences between the predicted values and the actual values.</em></strong></blockquote><p>A lower SSE value indicates a better fit between the predicted and actual values. SSE is sensitive to outliers because squaring large deviations increases their impact on the total error.</p><h4>Example</h4><p>Let’s create a simple example to calculate the Sum of Squared Error (SSE) for a series of basketball game score predictions. We’ll assume we have predicted scores for five games and then compare these predictions to the actual scores of the games.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*lNMJLZmY-HyT0SwhgJMGvw.png" /></figure><ul><li>Error column shows the difference between the Predicted Score and the Actual Score. This represents how much our prediction deviated from the actual outcome.</li><li>Squared Error is the square of the Error. Squaring ensures that all errors are positive (since negative errors would indicate underestimation, but when squared, reflect the magnitude of the error just the same as overestimations).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*w73zMqXYZGhVLgd7bUReMA.png" /><figcaption>Formula to Calculate SSE</figcaption></figure><h4>What Does SSE Tell Us?</h4><p>The SSE of 95 is a way of aggregating all the errors our predictions made into a single metric. It gives us an idea of the total error magnitude across all our predictions. Here’s why SSE is important:</p><ul><li><strong>Total Error Measurement:</strong> SSE provides a cumulative measure of error across all predictions. A lower SSE suggests better model accuracy.</li><li><strong>Sensitivity to Large Errors:</strong> Because errors are squared, large deviations from actual values are given more weight, making SSE particularly sensitive to outliers. This can be both a strength and a weakness, depending on the context.</li><li><strong>Model Comparison:</strong> Within the same dataset, SSE allows for the comparison of different models or prediction methods. The model with the lowest SSE is typically considered more accurate or better fitting to the data.</li></ul><h4>Limitations of SSE:</h4><p>While SSE is useful for understanding and comparing model errors, it’s not without limitations. For instance, it doesn’t account for the number of data points or the variability of the data. Therefore, it’s often used in conjunction with other metrics, like Mean Squared Error (MSE), which normalizes SSE by the number of observations, making comparisons across datasets more meaningful.</p><h3>Mean Squared Error (MSE)</h3><p>One downside that we observed with SSE is that it is depend upon the number of data points.</p><p>Therefore, it is not easy to compare SSE between N = 100 and N = 1000. In case of N = 1000, the error will be bigger simply due to making more predictions.</p><blockquote><strong><em>MSE is the average of SSE; it scales the SSE to the sample size, providing a measure of the average deviation of the predictions.</em></strong></blockquote><p>It’s used to compare the accuracy of different models on the same dataset. MSE penalizes larger errors more than smaller ones due to the squaring process, making it useful when large errors are particularly undesirable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*8HcZ7Le5UOuJ8c_otQ6fyA.png" /></figure><h4>Example</h4><p>Let’s borrow the example from SSE → <strong><em>A Basketball score prediction!</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*j4xdHQyU58KKgA1LBpPZ8Q.png" /></figure><p>To find the MSE, we’ll take the sum of all the squared errors (which we found to be 95 when discussing SSE) and then divide by the number of observations (games) to calculate the average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*QL0tN7-G7zXn7jaUfqqeXg.png" /></figure><blockquote><strong><em>This means that, on average, the squared error per game is 19.</em></strong></blockquote><h4>Understanding MSE:</h4><ul><li>This metric provides a standardized way of looking at the error magnitude, allowing for easier comparison across models or datasets with the same scale.</li><li>MSE’s sensitivity to large errors makes it a useful tool for identifying models that might be making significant mistakes in some predictions, even if they perform well on average.</li><li>Remember, MSE is particularly useful because it puts the error metric back on a scale that is somewhat more interpretable, being in the squared units of the outcome variable. However, because it’s in squared units, direct comparisons to the original predictions or outcomes require taking the square root, which leads us to the RMSE for a more directly interpretable metric.</li></ul><h4>Limitations of MSE:</h4><ul><li>Scale Dependency: Because it’s an average of squared errors, MSE’s value is directly influenced by the scale of the dataset. Larger values in the data will typically lead to larger MSE values, making it challenging to compare performance across datasets with different scales.</li><li>Interpretation Difficulty: The squared term in MSE makes it a bit more difficult to interpret in the context of the original data units. This is why the root mean squared error (RMSE) is often preferred for its interpretability.</li></ul><h3>Root Mean Squared Error (RMSE)</h3><p>Up until now we have seen two performance metrics that is → SSE and MSE. The major disadvantage of these two metrics is that they don’t have intuitive units.</p><p>Imagine you are forecasting temperature in Degree Celsius, but using the squared error, we will get Celsius squared. You must understand that there is no such thing as Celsius squared or it has no meaning to it. Therefore one way to express this error metric in the unit that make sense is to take Squared Root of the Mean Squared Error. In short, calculate the RMSE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*vlsk7loi6vUnzjxCnObijg.png" /></figure><h4>Example</h4><p>Let’s borrow the example from MSE → <strong><em>A Basketball score prediction!</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*YZD9JYhOWW2j4KovUVcxSw.png" /></figure><p>This calculation tells us the average error (in the same units as the scores) that our model’s predictions have from the actual scores.</p><p>Given the square root of 19, the RMSE would provide a direct sense of the model’s prediction accuracy on an average per-game basis, emphasizing the magnitude of errors and penalizing larger errors more significantly than smaller ones. This makes RMSE a highly insightful and widely used metric for evaluating the performance of prediction models. ​</p><h4>Understanding RMSE:</h4><p>RMSE provides a measure of how well a model can predict the value of an outcome. Here’s why it’s valuable:</p><ul><li><strong>Scale Compatibility:</strong> RMSE is expressed in the same units as the predicted and actual values, making it easier to interpret than MSE.</li><li><strong>Sensitivity to Large Errors:</strong> Like MSE, RMSE emphasizes larger errors more significantly than smaller ones, due to the squaring of errors before averaging. The square root helps to moderate this effect but still retains the property of penalizing large errors more heavily.</li><li><strong>Model Comparison:</strong> RMSE is widely used for comparing forecasting accuracy of various models. A lower RMSE indicates a better fit to the data.</li></ul><h4>Limitations of RMSE:</h4><ul><li><strong>Still Sensitive to Outliers:</strong> While the square root helps moderate the impact of large errors, RMSE remains sensitive to outliers. This can sometimes lead to misleading interpretations if the dataset contains many outliers.</li><li>Not Normalized: RMSE does not normalize for the number of observations, so while it’s excellent for comparing models on the same dataset, it’s not as useful for comparing across datasets of different sizes or scales.</li></ul><h3>Mean Absolute Error (MAE)</h3><p>MAE measures the average magnitude of errors in a set of predictions, without considering their direction.</p><blockquote><strong><em>It is less sensitive to outliers than MSE and RMSE since it does not square the errors.</em></strong></blockquote><p>MAE provides a direct measure of average error magnitude and is interpreted as the average distance from the predicted values to the actual values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*CbNfNP1wT210yv4T9068kw.png" /></figure><h4>Example</h4><p>Let’s borrow the example from RMSE → <strong><em>A Basketball score prediction!</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*6q0n63ErepQQsh7uSehUJw.png" /></figure><ul><li>The MAE of 4.2 points tells us that, on average, our predictions were off by 4.2 points from the actual scores.</li><li>This metric is useful because it gives us a direct measure of prediction accuracy on the same scale as the original data, and it’s robust against outliers. The MAE doesn’t penalize large errors more than smaller ones, as each error contributes linearly to the total error measure.</li></ul><h3>Mean Absolute Percentage Error (MAPE)</h3><p>Imagine you’re guessing the price of several items. After all your guesses, you check the actual prices to see how off you were with each guess. MAPE helps you understand, on average, by what percentage you were wrong with your guesses. This makes MAPE very intuitive and easy to interpret, especially for non-technical stakeholders.</p><p>Let’s create a simple example to calculate the Mean Percentage Error (MPE) for a series of basketball game score predictions. We’ll assume we have predicted scores for five games and then compare these predictions to the actual scores of the games.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*YrdfMSSh764fywtMI2oXBg.png" /><figcaption><strong>The Mean Absolute Percentage Error (MAPE) across all games is approximately 3.99%.</strong></figcaption></figure><p>This means that, on average, the predictions were off by about 3.99% from the actual scores, without considering whether they were overestimations or underestimations. This percentage gives us a sense of the average size of the prediction errors in terms of their proportion to the actual scores, offering a straightforward way to understand prediction accuracy across the set of games. ​</p><p><strong>Here’s how it works:</strong></p><ol><li>Subtract your predicted score from the actual score to find the difference for each item. This difference tells you by how much you overestimated or underestimated.</li><li>Turn these differences (errors) into absolute value (absolute errors).</li><li>Turn these absolute errors into percentages by comparing them to the actual score. This tells you, for each item, by what percent your predicted score was too high or too low.</li><li>Finally, calculate the average of these percentages. This average is your MAPE. It gives you a single percentage that represents how accurate your guesses were across all items, without getting skewed by whether you consistently overestimated or underestimated.</li></ol><p>So, MAPE essentially tells you, <strong>“On average, your guesses were off by this percentage.”</strong> A lower MAPE means your guesses were closer to the actual prices, while a higher MAPE means they were further off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*gG-e1eFeLB69o77QxNr0lQ.png" /></figure><p><strong>Advantages:</strong></p><ul><li>Scale-independent, facilitating comparisons across different datasets.</li><li>Intuitive interpretation in terms of percentage errors.</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Can be heavily skewed or undefined when actual values are zero or close to zero.</li></ul><h3>Mean Percentage Error (MPE)</h3><p>Similar to MAPE, MPE calculates the average of percentage errors; however, unlike MAPE, MPE includes the sign, providing information on whether the model tends to under- or over-estimate.</p><p>MPE can be particularly informative when you’re interested in understanding the bias of the forecast errors.</p><p>Imagine you’re trying to predict the scores for a series of basketball games. After all the games, you compare your predicted scores to the actual scores to see how you did. MPE helps you figure out, on average, whether your predictions were too high or too low and by what percentage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*4ES4VjhA2fa9PlArTfExJg.png" /><figcaption><strong>The Mean Percentage Error (MPE) across all games is approximately 0.32%.</strong></figcaption></figure><p>What this tells us is that, on average, the predictions were very slightly overestimated by about 0.32%. The individual game calculations show us by what percentage each game’s score was over or under-predicted, while the MPE gives us an overall average of prediction accuracy across all the games.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*KTwXktQmLZvjHEL3TB0a-g.png" /></figure><h4>Understanding MPE:</h4><p>MPE is particularly useful for identifying bias in predictions. Here’s what it tells us:</p><ul><li><strong>Positive MPE:</strong> Indicates that, on average, the model overestimates the actual values. The model’s predictions are higher than they should be.</li><li><strong>Negative MPE:</strong> Indicates that, on average, the model underestimates the actual values. The model’s predictions are lower than they should be.</li><li><strong>MPE Close to 0%:</strong> Suggests that the model, on average, accurately predicts the actual values, although individual predictions may still be off.</li></ul><p>In practice, MPE can offer valuable insights into a model’s predictive performance, especially regarding systematic biases. However, it’s often used alongside other metrics to provide a more comprehensive view of model accuracy and reliability.</p><h3>R² (Coefficient of Determination)</h3><p>In regression related problems, the metric R² used to determine “How good is our regression model?”</p><blockquote><strong>R-squared, also known as the coefficient of determination, is a statistical measure that represents the proportion of the variance for a dependent variable that’s explained by an independent variable or variables in a regression model.</strong></blockquote><p>It provides an indication of the goodness of fit of a model and is often used to analyze how well the model predicts or fits the actual data.</p><p>Before explaining R², there are some prerequisite terms that we need to understand. Those are -</p><ol><li>Errors in the Regression</li><li>SSTotal (Mean Regression Model)</li><li>SSResiduals</li></ol><p>Let’s understand these concepts.</p><h4>Errors in the Regression:</h4><p>An error in regression model is defined as →</p><blockquote><strong><em>An error in regression is nothing but the difference between Actual Value &amp; Predicted Value.</em></strong></blockquote><blockquote><strong><em>Error = Actual — Predicted</em></strong></blockquote><p>Error is most important concept in regression problems. Hence we have revisited it once again.</p><h4>SSTotal (Mean Regression Model):</h4><ul><li>It is the differences between observed values and the mean of observed values</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*bFwMTTtRVmcLr3QnFzdAiQ.png" /></figure><ul><li>This is nothing but the most basic regression model called → Mean Regression Model.</li><li>Given any query point, the model predicts average value of Yi as Yq as shown in below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*AdlCBuZWl_qIP80guufRvw.png" /></figure><ul><li>Therefore it is nothing but the sum of squared error using simple mean model</li></ul><h4>SSResiduals:</h4><ul><li>It is the sum of squares of residuals (the differences between observed and predicted values).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*A0hfWmKXO9pKLiIPgnBlvQ.png" /></figure><ul><li>It represents the variations in the dependent variable that cannot be explained by the model.</li></ul><p>Now let’s proceed towards the calculation of R²</p><h4>Calculation &amp; Interpretation of R²</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*4EZP0nOHZywzRsvWekUFUg.png" /></figure><p>Let’s understand case by case.</p><p><strong>Case 1: When SSResiduals = 0</strong></p><ul><li>When SSResiduals is zero or close to zero which means Actual is equal predicted.</li><li>This is the best regression case when R² is 1 or close to 1</li></ul><p><strong>Case 2: When SSResiduals &lt; SSTotal</strong></p><ul><li>If SSResidual is less than SSTotal the R² lies between 0 &amp; 1.</li><li>This is the typical case</li></ul><p><strong>Case 3: When SSResiduals = SSTotal</strong></p><ul><li>It means sum of square of residuals is same as simple mean model.</li><li>In this case R² = 0</li></ul><p><strong>Case 4: When SSResiduals &gt; SSTotal</strong></p><ul><li>This is the worst case in regression.</li><li>In this case, R² is Negative.</li></ul><p><strong>Case 5: When SSTotal = 0</strong></p><ul><li>It indicates a special and very specific scenario in your data. This occurs when all of the observed values, <em>yi</em>​, are identical.</li><li>In other words, there is no variance in your dependent variable.</li><li>Each <em>yi</em>​ is equal to the mean of the dependent variable, <em>y</em>ˉ (y bar)​, resulting in each term of the SSTotal​ sum being zero.</li><li>Since each datapoint <em>yi</em> is <em>y</em>ˉ (y bar)​, the, just ere is no need of regression, just return <em>y</em>ˉ (y bar)​ for any new query point.</li></ul><h4>Examples</h4><p>Let’s consider a dataset where we’re trying to predict a person’s weight based on their height. In this scenario:</p><ul><li>If R² = 0.8, it suggests that 80% of the variance in weight can be explained by height, indicating a strong relationship.</li><li>If R² = 0.2, it suggests that only 20% of the variance in weight can be explained by height, indicating a weak relationship.</li></ul><h4>Limitations and Considerations</h4><ul><li><strong>Overfitting:</strong> A high R² value does not necessarily mean the model is good. A complex model might overfit the data, capturing noise rather than the underlying relationship.</li><li><strong>Not a measure of accuracy:</strong> R² does not indicate whether the predictions are close to the observations; it only measures the proportion of variance explained.</li><li><strong>Comparability:</strong> R² alone should not be used to compare models with different dependent variables or datasets.</li></ul><h3>Adjusted R²</h3><p>Adjusted R² is a refinement of the R² statistic, designed to provide a more accurate measure of the goodness of fit for regression models, especially when comparing models with a different number of predictors.</p><p>Let’s dive into the details.</p><h4>Definition and Formula</h4><blockquote>Adjusted R² adjusts the R² value to account for the number of predictors in the model. Unlike R², which always increases as you add more predictors, adjusted R² can decrease if the additional predictors don’t improve the model significantly.</blockquote><p>This makes it a more reliable statistic for comparing models with different numbers of independent variables. The formula for adjusted R² is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*YkEhgMKP5gnIv6GPNGo47Q.png" /></figure><p><strong>Where:</strong></p><ul><li><strong>R²</strong> is the original coefficient of determination.</li><li><strong>n</strong> is the sample size, i.e., the number of observations.</li><li><strong>p</strong> is the number of predictors (independent variables) in the model.</li></ul><h4>Interpretation</h4><p>The adjusted R² value provides a measure of how well the independent variables explain the variability of the dependent variable, adjusted for the number of predictors.</p><blockquote><em>It penalizes the addition of irrelevant predictors, which is a significant advantage over R².</em></blockquote><ul><li>A higher adjusted R² indicates a better model fit, taking into account the number of predictors.</li><li>Unlike R², the adjusted R² can decrease if the contribution of the new predictors does not outweigh the penalty for increasing the number of predictors</li></ul><h4>Why Use Adjusted R²?</h4><p><strong>1. Model Comparison:</strong> It is particularly useful when comparing models with a different number of independent variables. It helps in selecting the model that has the right balance between goodness of fit and model complexity.</p><p><strong>2. Penalty for Extra Predictors:</strong> Adjusted R² incorporates a penalty for adding predictors that do not contribute to an increase in R² commensurate with the loss of degrees of freedom. This discourages overfitting by penalizing complex models that don’t necessarily provide better explanatory power.</p><p><strong>3. More Accurate Measure of Fit:</strong> For models with many predictors, adjusted R² gives a more accurate measure of how well the model generalizes, potentially avoiding the misleading interpretation that adding more variables makes the model better.</p><h4>Example</h4><ul><li>Consider two models predicting house prices: Model A uses 2 predictors (square footage and number of bedrooms)</li><li>Model B uses 5 predictors (adding in age of the house, distance to the city center, and local crime rate).</li><li>If both models have similar R² values, Model A might be preferred due to its simplicity unless Model B has a significantly higher adjusted R², indicating that the additional complexity of the model is justified by a proportional increase in explanatory power.</li></ul><h3>Median Absolute Deviation (MAD)</h3><p>The main concern that a single large error (residual) can significantly affect the sum of squared residuals SSResiduals, which in turn affects the R² value. R² is not robust in the presence of outliers, as outliers will disproportionately influence the sum of squares due to the squaring of the residuals. This is where MAD can be particularly useful.</p><p>By using the median of the absolute deviations rather than the mean (which would be more influenced by outliers), the MAD provides a measure of dispersion that is more resistant to the influence of outliers.</p><p>Let’s take a look at the error (ei)given below →</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*Vq97kUcrZ2leCiH4X78HXw.png" /></figure><ul><li>If one of the ei is large (Let’s say e4 is large) then it has high chances that It will affect the R². As we have studied, R² isn’t robust and it is affected by outliers.</li><li>MAD can be used to tackle the problem as it is not easily gets affected by outliers.</li><li>If we think eq is random variable, we can compute it’s median and MAD as well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*h6iU3kwpWAV6EdbISziSuw.png" /></figure><ul><li>If we find out median (eq) and MAD (eq) are small then we understand our errors are also small.</li></ul><h3>Distribution of Errors</h3><p>In last chapter we’ve seen to get more information about errors with the help of mean, median, standard deviation and MAD. But we can also use probability distribution to get much more information about the errors. (We will see how to utilize PDF &amp; CDF)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JnANQcx7Zkp9EfJezuFcg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xprpFsTiAVmzumfiO4OaoA.png" /></figure><h4>Final Note</h4><p>That’s a wrap! I’ve thoroughly covered performance measurement techniques, with Part I focusing on classification performance measurements and Part II on regression performance techniques. I’ll keep updating this blog with new content as needed. If you enjoyed reading, please clap and consider following me.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=869e7c8dccfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Measurement Models — (Part I]]></title>
            <link>https://dugamakash.medium.com/performance-measurement-models-part-i-dbe457eb2098?source=rss-19a974a0393------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbe457eb2098</guid>
            <category><![CDATA[regression-modeling]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[confusion-matrix]]></category>
            <dc:creator><![CDATA[Akash Dugam]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 14:13:46 GMT</pubDate>
            <atom:updated>2024-03-26T14:13:46.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>Performance Measurement Models — (Part I)</h3><p>Doesn’t matter whether you are Data Scientist or not, you indulge in measuring the performance or (in short) measuring the quality of things you deal with. And that’s the ultimate truth. Remember, we used to get performance cards during school days to get them signed by parents? Even today, if we visit a supermarket for grocery shopping, we do quality checks many times before we put them in our carts.</p><p>We are 360⁰ involved in quality checks or performance measures. Similar fashion, as a data scientist, check the quality of the model that you built. And that’s where all performance measurement models come into the picture. In this section, we will discuss performance measures for a classification problem.</p><h3>Introduction</h3><p>In the Data Science life cycle, measuring the performance of the model you built comes at the end of the life cycle. Your task is to first understand the business problem, collect data as per the business problem. Once you wrap up the data collection phase, then you go with the data preparation and exploratory data analysis phase. Once we understand the data completely (regarding our problem), we build machine learning models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*gihM6dC-EyRUBfos.png" /><figcaption>Source — <a href="https://analyticsindiamag.com/a-complete-tour-of-data-science-project-life-cycle/">https://analyticsindiamag.com/a-complete-tour-of-data-science-project-life-cycle/</a></figcaption></figure><p>Once we have done with building machine learning models next step is to verify those models or measure the performance of those models to find out good performing models for our goal. This stage is nothing but the model evaluation stage, as shown in the above figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DcI_8Np-cBh4fKBm3FOG4w.png" /></figure><p>In this blog post, we will focus on metrics related to classification problems. There are metrics related to regression problems as well, but that we discuss that in Part-II of this blog post. For now, we will cover below performance metrics →.</p><ul><li>Accuracy</li><li>Confusion Matrix</li><li>Precision &amp; Recall</li><li>F Beta</li><li>Kohen’s Kappa</li><li>ROC Curve</li><li>Log Loss</li></ul><p>Let’s start with Accuracy.</p><h3>Accuracy</h3><p>Accuracy is one of the popular metrics for evaluating classification models. In classification problems, we calculate accuracy in two ways →.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_Jtb11Sq1woxs_IVNBmXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEitFPI449DPPsWzUkx0Kg.png" /></figure><h4>Problems with Accuracy Measure</h4><p>There are issues with accuracy measures and hence it is not a widely used performance metric in data science. Let’s discuss the problems faced by accuracy measures.</p><p><strong>Problem 1 → Imbalanced Data</strong></p><p>Accuracy is a good performance measure when you have perfectly balanced data. But that’s not the reality always. You may or may not have perfectly or somewhat balanced data to accept the accuracy as the performance metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIFEPsh-7qZfFmhKcINUjQ.png" /></figure><p>Let’s say, you have got a classification dataset about Xi and the class label of that dataset is (Yi) <strong>“Has cancer”</strong> or <strong>“No Cancer”</strong>. Basically, you are trying to classify whether a patient will be diagnosed with cancer or not?. Let’s look at the nitty-gritty details of the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrXWOYxAnCOPd7wJm3o9kg.png" /></figure><p>If your dataset is above mentioned one then given query point (Xq), the model will classify it to the “Negative” category with an accuracy of 90%. With such a faulty model, we get pretty good accuracy. This is a concerning thing regards to an accuracy performance metric.</p><blockquote>When there is a case of imbalanced data, never use accuracy as a model performance trait.</blockquote><p><strong>Problem 2 → Predicted Class Label Vs Probability Score</strong></p><p>Many algorithms can provide probability scores of their prediction as well as predict class labels. Let’s use this functionality of models to illustrate this concept.</p><p>Let’s say you have a dataset with two features is X &amp; Y. (Here we are predicting Y based on variable X). Let’s use two models (Let me call them M1 &amp; M2) to do the predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*op7I-GkHhX77QY5VUPRCIg.png" /></figure><p>Observations →</p><ul><li>Model M1 &amp; M2 return probability scores &amp; also, depending upon the probability score, we have labelled them in the above problem.</li><li>For X1, the original class label is 1. With the help of M1 (P (Y=1|X1) we got the probability of 0.93 and with M2, we got the probability of 0.62. Both model labelled Y as 1 due to (P (Y=1|X1) &gt; 0.50.</li><li>For X2, the original class label is 1. With the help of M1 (P (Y=1|X2) we got the probability of 0.82 and with M2, we got the probability of 0.74. Both model labelled Y as 1 due to (P (Y=1|X2) &gt; 0.50.</li><li>For X3, the original class label is 0. With the help of M1 (P (Y=1|X3) we got the probability of 0.12 and with M2, we got the probability of 0.45. Both the model labeled Y as 0 due to (P (Y=1|X3) &lt; 0.50.</li><li>For X4, the original class label is 0. With the help of M1 (P (Y=1|X4) we got the probability of 0.15 and with M2, we got the probability of 0.42. Both the model labeled Y as 0 due to (P (Y=1|X4) &lt; 0.50.</li></ul><p>Models M1 and M2 predicted class labels accurately as predicted and actual class labels are the same in all situations.</p><blockquote>By observing the table, we can conclude that model M1 is better performing model than model M2 by looking at their probability score. Unfortunately, performance measures like accuracy cannot use the probability score, it can only use the class labels. Model M1 and M2 has same accuracy, but looking at probability score, we know M1 is better than M2.</blockquote><h3>Confusion Matrix</h3><p>There is another classification performance metric known as the confusion matrix used widely in classification problems in statistics and machine learning. We define the confusion matrix as →.</p><blockquote>In machine learning or in statistical classification, a table of confusion (sometimes also called as Error Matrix) is a table with two rows and two columns shows the performance of the classification algorithm by comparing ‘Actual Vs Predicted Class Labels’.</blockquote><p>When we have a binary classification problem, then the grid of the confusion matrix is 2x2. (Confusion Matrix is mostly used in Binary Classification Problems)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nf1GAmG497TNOeMdnXdsDw.png" /></figure><blockquote><strong><em>Like Accuracy, the Confusion Matrix does not process the Probability Score!</em></strong></blockquote><p>If your model is sensible, all <strong>principle diagonal elements</strong> should be <strong>high</strong> and <strong>off-diagonal elements</strong> should be low.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZiX-o9XTqb0qpZTlVWUAQ.png" /></figure><h4>Understanding TN TP FN FP</h4><p>A confusion matrix is built with the help of the following concepts →</p><ul><li>TN (True Negative),</li><li>TP (True Positive),</li><li>FN (False Negative),</li><li>FP (False Positive)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8GwZ_Tx9OSQYncGAolibyA.png" /></figure><p>Now, let’s understand each of these concepts briefly.</p><h4>True Positive (TP)</h4><ul><li>The model has predicted positive and actual is positive too.</li><li>Ex → Model has predicted a woman is pregnant, and she actually is.</li></ul><h4>True Negative (TN)</h4><ul><li>The model has predicted negative, and actual is negative too.</li><li>Ex → Model has predicted that a man is not pregnant, and he actually isn&#39;t.</li></ul><h4>False Positive (FP)</h4><ul><li>The model has predicted positive but the actual is negative.</li><li>This is nothing but a Type-I error.</li><li>Ex → Model has predicted that a man is pregnant but actually he isn’t.</li></ul><h4>False Negative (FN)</h4><ul><li>The model has predicted negative but actually is positive.</li><li>This is the case of Type-II error.</li><li>Ex → Model has predicted woman is not pregnant, but she actually is.</li></ul><p>By using the above information, we can calculate the list of rates from the confusion matrix for a binary classifier. Let’s understand these rates now.</p><h4>Various Performance Metrics Derived From Confusion Matrix</h4><p>Let’s understand the various performance metrics that can be calculated from the confusion matrix itself with the help of a toy example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yreZh1OeDiDqJWzztSGzmg.png" /></figure><h4>Accuracy</h4><ul><li>Overall, how often is the classifier is correct?</li><li>Accuracy = (TN + TP) / (TN + TP + FN + FP) = 175 / 200 = 0.87</li></ul><h4>Misclassification Rate</h4><ul><li>Overall, how often your classifier is wrong?</li><li>Misclassification Rate = (FN + FP) / (TN + TP + FN + FP) = 25/200 = 0.125</li></ul><h4>True Positive Rate (TPR)</h4><ul><li>When it’s actually “Yes”, how often does your model predict “Yes”.</li><li>This is also known as “Sensitivity” or “Recall”</li><li>TPR = TP / P = TP / (FN + TP) = 100 / 105 = 0.95</li><li>It is equivalent to 1-FNR</li></ul><h4>True Negative Rate (TNR)</h4><ul><li>When it’s actually “No”, how often does your model predict “No”?</li><li>It is also known as “Specificity” or “Selectivity”</li><li>TNR = TN / N = TN / (TN + FP) = 75 / 95 = 0.78</li><li>It is equivalent to 1-FPR</li></ul><h4>False Positive Rate (FPR)</h4><ul><li>When it’s actually “No”, how often does your model predict “Yes”?</li><li>It is also known as “Type-I error” or “Fall-out”</li><li>FPR = FP / N = FP / (TN + FP) = 20 / 95 = 0.21</li><li>It is equivalent to 1-TNR</li></ul><h4>False Negative Rate (FNR)</h4><ul><li>When it’s actually “Yes”, how often does your model predict “No”?</li><li>It is also known as “Type-II error” or “Miss Rate”.</li><li>FNR = FN / P = FN / (FN + TP) = 5 / 105 = 0.04</li><li>It is equivalent to 1-TPR</li></ul><h4>Balanced Accuracy (BA)</h4><ul><li>It is a simple arithmetic mean of “Sensitivity” and “Specificity”.</li><li>BA = TPR + TNR / 2 = 0.95 + 0.78 / 2 = 0.86</li></ul><blockquote><strong><em>Your Model will be good, if TPR &amp; TNR is high and FNR &amp; FPR is low. In simple words, all the principle diagonal elements must be high and off-diagonal element must be low.</em></strong></blockquote><h3>Precision &amp; Recall — We Care About Your Positive Class!</h3><p>These are the metrics also calculated from the confusion matrix only. The reason I have kept them separate as topics is that they are highly important metrics in binary classification problems.</p><p>Let’s discuss them now.</p><h4>Precision</h4><ul><li>Precision is the concept is taken from Information Retrieval and Pattern Recognition.</li></ul><p>Precision, which is also known as <strong>Positive Predictive Value (PPV)</strong> defined as →</p><blockquote><strong><em>It is a fraction or percentage of relevant instances among the retrieved instances.</em></strong></blockquote><ul><li>In our binary classification problem, we can say precision is, “All the points that the model declared or predicted to be positive, what % of them are actually positive?”</li><li>Precision is actually the ratio of True Positive (TP) to True Positive &amp; False Positive.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tTvSAdeXCN9nK2OZPoasA.png" /></figure><p><strong>Example </strong>→</p><p>For fishing, you throw a fishing net into the river/pond/ocean. After some time you pull it back considering that you have trapped enough fish. But what you get is some fish and some plastic (Garbage). So in this case your precision would be →</p><blockquote><strong>“All the stuff that you caught, what % them are actually fish?”</strong></blockquote><h4>Recall</h4><ul><li>The recall is nothing but the True Positive Rate (TPR) is defined as →</li></ul><blockquote><strong>It is fraction, or percentage, of relevant instances that were retrieved from total relevant instances.</strong></blockquote><ul><li>In binary classification lingo, we can say, “When it’s actually ‘Yes’, how often does your model predict ‘Yes’?</li><li>It is also known as “Sensitivity”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2DJsMbsNmvj1jRJTvwpaA.png" /></figure><p>Example →</p><p>In the above fishing example, the recall would be →</p><blockquote><strong>“Out of all the fish in the ocean, what % of fish did you catch?”</strong></blockquote><p>Precision &amp; Recall are very much important when you care about positive class in classification problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40N74a6D3qIDqhjjUL3mSw.png" /></figure><h4>Example: <strong>Medical Diagnosis for a Disease</strong></h4><p>Imagine you have developed a machine learning model to diagnose a rare but serious disease, where:</p><ul><li><strong>“Positive”</strong> means the model predicts the disease is present.</li><li><strong>“Negative”</strong> means the model predicts the disease is not present.</li></ul><p>Now, consider the following outcomes from testing 1000 patients:</p><ul><li><strong>True Positives (TP):</strong> 80 patients truly have the disease, and the model correctly diagnoses them as having the disease.</li><li><strong>False Positives (FP):</strong> 20 patients do not have the disease, but the model incorrectly diagnoses them as having the disease.</li><li><strong>True Negatives (TN):</strong> 880 patients truly do not have the disease, and the model correctly identifies them as not having the disease.</li><li><strong>False Negatives (FN):</strong> 20 patients have the disease, but the model incorrectly identifies them as not having the disease.</li></ul><p><strong>Precision (Quality of Positive Predictions):</strong></p><p>In our example, precision represents how accurate the model is when it predicts that a patient has the disease:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*TjubPS79lq-iyxfENafhJA.png" /></figure><p>So, the precision of your model is 0.80 or 80%. This means that when the model predicts the disease, it is correct 80% of the time.</p><p><strong>Recall (Capturing Actual Positives):</strong></p><p>Recall, on the other hand, represents how well the model can identify patients who actually have the disease:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*Hx5WuAy1XGvLplZCRhi34g.png" /></figure><p>So, the recall of your model is also 0.80 or 80%. This means that out of all the patients who truly have the disease, the model correctly identifies 80% of them.</p><p><strong>Interpretation and Use-Case:</strong></p><ul><li><strong>Precision:</strong> If the disease is one where the treatment has severe side effects, you might prioritize precision. This is because you want to be very sure that patients diagnosed with the disease actually have it before subjecting them to the treatment. In our example, a precision of 80% is fairly high, which is good if the treatment has significant risks.</li><li><strong>Recall:</strong> If the disease is extremely dangerous or infectious, you might prioritize recall. This is because you want to ensure that nearly all individuals who have the disease are identified, even if that means some false positives. In our example, a recall of 80% means that we’re capturing a good proportion of actual cases, but we might want to improve this if the disease is severe and missing a case could be deadly.</li></ul><h3>F-βeta Score</h3><p>In the last topic, we’ve discussed the most important metrics in classification that is Precision &amp; Recall. If you could remember, we have stated also that →</p><ul><li>When we care more about the False Positive (FP) than False Negative (FN), we use Precision.</li><li>When we care more about the False Negative (FN) than False Positive (FP), we use Recall.</li></ul><p>But what if in the situation, you need both metrics at the same time? If yes, instead of stating each of these metrics separately, Is there any way to combine these two metrics? → Yes, and the answer lies in the F-βeta concept. Let’s discuss it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*3QQ-GAltGm6cWpEL1JuKOg.png" /></figure><p>With F-<em>β</em>eta, a usually most important task is to select the value of <em>β</em>eta. Let’s take various <em>β</em>eta values and discuss various cases.</p><h4>When <em>β</em>eta = 1</h4><ul><li>When we have <em>β</em>eta = 1 then the above F-<em>β</em>eta equation becomes F1-Score.</li><li>F1 Score is nothing but the <strong><em>Harmonic Mean</em></strong> between Precision &amp; Recall.</li><li>If Precision &amp; Recall both are equally important in the problem statement or aim, we use <em>β</em>eta = 1.</li></ul><h4>When βeta = 0.5</h4><ul><li>In some cases, False Positive (FP) has more impact than False Negative (FN) then we reduce the βeta value to 0.5</li><li>It is also known as the F0.5 Score.</li><li>Use βeta = 0.5 whenever a Type I error is more important than Type II.</li></ul><h4>When βeta = 2</h4><ul><li>In some cases, False Negative (FN) has more impact than False Positive (FP) then we increase our βeta value to 2.</li><li>It is known as the F2 Score.</li><li>Remember we use βeta value &gt; 1 when type II error has more impact than type I error on the model.</li></ul><h3>Cohen’s Kappa</h3><p>Cohen’s Kappa score is a famous evaluation metric for measuring the performance of classification problems in machine learning. It was proposed by a famous statistician, Jacob Cohen, and later it was accepted globally.</p><p>Cohen’s Kappa score is based on the principle called → <strong>“Agreement”.</strong></p><blockquote>Here Agreement is nothing but coming to the same opinion by two different human beings.</blockquote><p>For example, consider a conversation with 2 persons-</p><p><strong>James</strong>: “Titanic is an excellent movie. I like to watch it whenever it is getting telecasted on TV”.</p><p><strong>Sam</strong>: “Yes. Titanic is a gem. Especially the story and screenplay are outstanding”.</p><p>Here, Both James and Sam have the same opinion regarding the movie which means their agreement is strong.</p><blockquote>Similarly, the Chance of agreement is the probability of 2 people will have an opinion on a subject purely based on random chances but not because of any mathematical fact</blockquote><p>Thus Kappa coefficient (K) takes the agreement by chance into account. Now let’s see how do we calculate the value of the Kappa coefficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*GFqg5iBXK822TDVaC77qTA.png" /></figure><p>Here →</p><ul><li>a → The total number of instances coded as “correct” in both actual and predicted.</li><li>b → The total number of instances coded as “Incorrect’ in actual but “correct” in predicted.</li><li>c → The total number of instances coded as “Correct’ in actual but “Incorrect” in predicted.</li><li>d → The total number of instances coded as “Incorrect” in both actual and predicted.</li></ul><p>To calculate Kappa Coefficient, we need to calculate →</p><ol><li><strong>Total Frequency → </strong>It is nothing but the addition of TN + FP + FN + TP. That is a + b + c + d.</li><li><strong>Expected frequencies ( ef ) of a &amp; d →</strong> If we would have purely guessed, how many correct should be in that column?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*EcOFuHbC-knenwJvXgrfHw.png" /></figure><p>Now let’s calculate the Cohen’s Kappa Coefficient (K) with the help of the above-explained concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*XPu6uua0bgMVCk3K1tALXQ.png" /></figure><h4>Interpretation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*zQU1K1yDaSiv7M2M6rhZZg.png" /></figure><h3>Receiver Operating Characteristics (ROC) And Area Under The Curve (AUC)</h3><p>A ROC curve (Receiver Operating Characteristics Curve) is a graph showing the performance of the classification models at all classification thresholds.</p><p>This curve plots two parameters →</p><ul><li>True Positive Rate (TPR)</li><li>False Positive Rate (FPR)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*HVpjkWQHLeQQ62Y9x0y2fA.png" /></figure><p>ROC was designed by Electrical Engineers during WWII to find out how well their missiles are working. Well, Data Science is a combination of many areas, this might be taken from electrical engineers. Who knows? :D</p><p>ROC is designed to use in Binary Classification tasks. It is the probability curve that plots the TPR against the FPR at <strong>various</strong> <strong>threshold </strong>values (by doing this) and essentially separates signal from noise.</p><p>AUC represents the degree or measure of separability. It tells us how much your model is capable of separating two classes.</p><blockquote><strong>The higher the AUC, better is the performance of the model on separating two classes that is positive and negative.</strong></blockquote><h4>How to measure the performance of the model using AUC?</h4><p>It is important to interpret or understand the value of AUC. The Value of AUC varies from 0 to 1. Let’s take case by case to understand the interpretability of AUC.</p><p><strong>Case 1 →</strong></p><ul><li>When you’ve AUC values that are near 1 it means your model is performing well. The model has a good value of separability.</li><li>As we know that ROC is the curve of probabilities. Therefore, plotting those distributions would be a wise thing to do.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*Uc7yxlf4-6arHK4R0HLWew.png" /></figure><ul><li>In above picture, there are two classes ( +ve class = Orange &amp; -ve class = Blue) aren’t overlapping with each other. The model is excellent, as it shows the best separability between positive and negative classes.</li><li>We can perfectly distinguish between the class.</li><li>This is a rare scenario when we have AUC = 1.</li></ul><p><strong>Case 2 →</strong></p><ul><li>In the above case, we have seen the “Best Case” which you will never encounter in real life. (At least it never happened with me)</li><li>In real life, you will have AUC between 0.50 to 1.0. This would be a typical case where minor overlapping of classes can be seen.</li><li>With the presence of overlapping as well, these models show good class separability.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*a86uRi_5YZvxEUExcbLUPg.png" /></figure><ul><li>When there is possible overlap in distinguishing the two classes, we introduce something known as type-I and type-II errors.</li><li>We can move our threshold to minimize or maximize the type-I or type-II errors.</li><li>When AUC =0.75, it means there is a 75% chance model will distinguish between the positive class and the negative class.</li></ul><p><strong>Case 3 →</strong></p><ul><li>In machine learning, the worst situation is when the model cannot distinguish between the two classes.</li><li>This situation arises when we get AUC = 0.50, which literally means the model has no separation capabilities to distinguish between classes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*Z6LNYfWY1jdLYUWLtU6beQ.png" /></figure><ul><li>A model with AUC = 0.5 is nothing but a random model.</li></ul><p><strong>Case 4 </strong>→</p><ul><li>When AUC is approximately 0, the machine learning model interchanges the classes.</li><li>It means the model is predicting positive class as a negative class and negative class as a positive.</li><li>AUC of a model less than 0.5 can be improved by swapping the class labels.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*BwhUVxpKFWjjI6WEDvbpgA.png" /></figure><h4>How do we construct ROC Curve?</h4><p>The ROC (Receiver Operating Characteristic) curve is a graphical representation used to evaluate the performance of a binary classifier system as its discrimination threshold is varied.</p><blockquote>It is a plot of the true positive rate (sensitivity) against the false positive rate (1 — specificity) for the different possible cut points of a diagnostic test. (TPR Vs FPR)</blockquote><p>Here’s a step-by-step guide on how to calculate and interpret the ROC curve, using an example:</p><p><strong>1. Prepare Your Data:</strong></p><p>First, you need a set of observations (actual outcomes) and the corresponding predictions (usually probabilistic or score-based) from your binary classifier. For this example, assume we have the following data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*NXravo70Jw2uXxgXNzDUgg.png" /></figure><p><strong>2. Rank Predictions:</strong></p><p>Rank the individuals by their predicted probabilities (or scores), from highest to lowest.</p><p><strong>3. Determine Thresholds:</strong></p><p>For each unique predicted probability (which will act as a threshold), determine the True Positive Rate (TPR) and False Positive Rate (FPR):</p><ul><li><strong>Threshold:</strong> The predicted probability at which you decide to differentiate between the classes.</li><li><strong>True Positive Rate (TPR):</strong> TP / (TP + FN), where TP is the number of true positives and FN is the number of false negatives.</li><li><strong>False Positive Rate (FPR):</strong> FP / (FP + TN), where FP is the number of false positives and TN is the number of true negatives.</li></ul><p><strong>4. Calculate TPR and FPR at Each Threshold:</strong></p><p>The thresholds typically start from 1 (or the maximum predicted probability) and go down to 0, but they will be based on the unique values from the predictions in our example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*qNjveK_gYD_e2K2XwFIPEg.png" /><figcaption>TPR (Sensitivity) = TP / (TP + FN) &amp; FPR (1 — Specificity) = FP / (FP + TN)</figcaption></figure><p>Please Note →</p><ul><li>TPR (Sensitivity) = TP / (TP + FN)</li><li>FPR (1 — Specificity) = FP / (FP + TN)</li></ul><blockquote>At threshold 1, no predictions are positive, so TPR and FPR are 0. At threshold 0, all predictions are positive, so TPR and FPR are 1.</blockquote><p><strong>5. Plot the ROC Curve:</strong></p><p>Plot the FPR on the x-axis and the TPR on the y-axis for each threshold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7UzgpmJ2xS2Uqps5" /></figure><p>Here’s the ROC curve drawn based on the data from the table. This curve plots the True Positive Rate (TPR) against the False Positive Rate (FPR) at different threshold settings. The dashed line represents a classifier with no discriminative ability (random chance), and the curve demonstrates how well the classifier can distinguish between the two classes.</p><h3>Log Loss (Cross Entropy Loss)</h3><p>Log loss, also known as logistic loss or cross-entropy loss, is a performance metric used in statistical models, particularly for evaluating the outcomes of binary classification models like logistic regression.</p><p>Unlike other metrics such as accuracy or the ROC curve, log loss provides a measure of uncertainty for the predictions made by a model, penalizing false classifications.</p><p>A log loss is important classification metric based on probabilities that we get when we apply model. As already stated, a log loss function generally used in binary classification problems but we can further extend it to multiclass classification problems as well.</p><blockquote>Log loss measures the unpredictability of the probability estimates — meaning, it quantifies how much the predicted probabilities diverge from the actual class labels.</blockquote><p>It is a <strong>“cost”</strong> or <strong>“loss”</strong> because lower values are better and represent a model with better predictive accuracy.</p><p>The formula for log loss for a binary classification model is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*rEkrVdJQjTZsEL_hHOB8rQ.png" /></figure><h4>Key Characteristics of Log Loss:</h4><ul><li><strong>Penalizes Confidence:</strong> Log loss heavily penalizes being confident and wrong. For example, a prediction of 0.99 for the wrong class would incur a much higher loss compared to a less confident prediction, like 0.51.</li><li><strong>Sensitive to Probability Estimates:</strong> Unlike accuracy, which cares only about the final prediction, log loss evaluates how close the predicted probabilities are to the actual class labels.</li><li><strong>Range:</strong> The log loss is always non-negative, and a perfect model would have a log loss of 0. However, there is no upper bound, which means the worse the model’s predictions are, especially with high confidence in the wrong class, the higher the log loss.</li></ul><h4>Example:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*m8rjdz28MrM_mM7cIVom9g.png" /></figure><blockquote>Note → Log Loss function measures the uncertainty of probabilities of the model by comparing them to true labels.</blockquote><p>Let’s plug the values of above table in the log loss formula given above. Below table is resultant table —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*kIsouxV0D2wNLvGrwUZRaw.png" /></figure><p>Let me explain the above log loss values →</p><ul><li>The log loss values for X1 &amp; X3 are small because it has high probability and therefore low loss (As a probability is closer to 1)</li><li>The log loss values for X2 &amp; X4 are high because 0.6 and 0.4 is not closer to actual label 1 and 0 respectively. Therefore a log loss value for X2 and X4 will be higher compared to X1 and X3.</li></ul><h4>Key Takeaways</h4><ul><li><strong>A lower log loss (closer to 0)</strong> indicates a better model prediction. It means the predicted probability is very close to the actual label.</li><li><strong>A higher log loss</strong> indicates a poorer prediction, as the predicted probability diverges significantly from the actual label.</li></ul><h3>Final Note</h3><p>That’s it. These are mainly used performance measurements model for classification problems. As I have already stated, this blog post would serve as Part — I in the series of two. In the sequel, we will talk about performance classification models for regression problems. Stay tuned for further updates.</p><p>Best,</p><p><a href="https://www.linkedin.com/in/akash-dugam/">Akash Dugam</a></p><h4>TaDaaa!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbe457eb2098" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Learn KNN!]]></title>
            <link>https://dugamakash.medium.com/lets-learn-knn-182045ca1e00?source=rss-19a974a0393------2</link>
            <guid isPermaLink="false">https://medium.com/p/182045ca1e00</guid>
            <category><![CDATA[distance-measurement]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Akash Dugam]]></dc:creator>
            <pubDate>Thu, 07 Mar 2024 10:09:12 GMT</pubDate>
            <atom:updated>2024-03-07T10:09:12.897Z</atom:updated>
            <content:encoded><![CDATA[<p>K-Nearest Neighbors (KNN) is the simplest algorithm in machine learning with a lot of intuition to real words which actually make people understand the working procedure behind it. In this blog post, we are going to simplify the K-Nearest Neighbor (KNN) algorithm.</p><p>Let’s shed some light on what we will learn about this algorithm. In short, let’s check the agenda.</p><ul><li>Introduction to K Nearest Neighbour</li><li>Geometric Intuition of K-Nearest Neighbour (KNN)</li><li>How does K-Nearest Neighbour identify the neighbours?</li><li>Decision surfaces in K-Nearest Neighbour</li><li>Overfitting and Underfitting from the sense of K-Nearest Neighbour.</li><li>Pseudocode for K Nearest Neighbour</li><li>Weighted K Nearest Neighbour</li><li>Regression Using KNN</li><li>Probabilistic class labels using KNN</li></ul><h3>Introduction to K Nearest Neighbors (KNN)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*aCo-xekP6ovnkqxXPa5swA.png" /></figure><p>K Nearest Neighbors, KNN for short is one of the simplest and easy to learn algorithm in machine learning. It is a supervised machine learning algorithm which is mostly used to solve classification related problems. Most of the classification related algorithm can perform well in regression problems and K Nearest Neighbor is one of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*jXhP9E8MEbuTDUU96JDslQ.png" /></figure><p>Let’s say you have 10 dogs and your job is to classify them into ‘Puppies’ and ‘Adults’. If I ask you how’d you do it? Just looking at them you can tell us whether its puppy or adult. This has happened because you have stored characteristics of ‘Puppies’ and ‘Adult’ dogs in your mind. But how do you think the machine will classify them? For this purpose like your mind have been trained we need to train a machine to identify that. That is where machine learning algorithms come into the picture. We train the machine with the help of the K Nearest Neighbour algorithm which will help the machine to remember characteristics of ‘Puppies’ and ‘Adult Dog’. The similar example can be found here. Please do watch below video for a better understanding.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FcKxRvEZd3Mw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DcKxRvEZd3Mw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FcKxRvEZd3Mw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/36c6566136020a668e02ebc8dc636d0b/href">https://medium.com/media/36c6566136020a668e02ebc8dc636d0b/href</a></iframe><p>Now you might be wondering, how does one algorithm can make a machine learn? Don’t worry, we will learning that as we progress in this KNN tutorial. Now let’s understand how does KNN works from a geometric perspective.</p><h3>Geometric Intuition of K-Nearest Neighbour (KNN)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*WipAGChixQ3AWcgjI6ETWQ.png" /></figure><p>There are two classes shown in the above diagram. These classes could be anything.</p><ul><li>Data Points associated with class 1 are represented with Orange color.</li><li>Data points associated with class 2 are represented with Blue color.</li><li>There is a decision surface shown in the above figure used to divide two classes into the region.</li></ul><p>Let&#39;s assume we need to classify X (a white point shown in the above diagram) into its right category. <strong><em>In simple words, which class point X belongs to? So basically we are determining its class.</em></strong></p><p>Now let&#39;s understand step by step procedure to determine the class of the X that shown in the above diagram.</p><p><strong>Step 1: → Find k nearest points to X in the dataset.</strong></p><ul><li>‘K’ in K Nearest Neighbor algorithm is the number of neighbors of X that we need to evaluate before deciding its class.</li><li>Its just number. If we assume K = 5, the algorithm is going to check its nearest 5 neighbours or points.</li><li>‘K’ in KNN is hyperparameter, we can’t just assign it to any number we need to decide its value by doing cross-validation. Don’t worry for now we will see those concepts later.</li></ul><p><strong>Step 2: → Find Corresponding Classes of K Nearest Neighbors</strong></p><ul><li>Let say we have selected K = 5 in the above step that makes us investigate the properties or characteristics of 5 nearest neighbors.</li><li>If could observe in the above diagram we can clearly see 5 nearest neighbors are marked inside the circle.</li><li>In classification problems, every Xi comes with Yi. It means for every data points there is a class associate with the data point.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*bA2qtQ80j6J3XicyQ57JQg.png" /></figure><ul><li>As shown in the above diagram, for 5 neighbours there are 5 class labels associated with it.</li></ul><p><strong>Step 3: → Majority Vote</strong></p><ul><li>Now we will classify the given point either of the categories based on the majority.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*9tXAU4pVNWMi6iBWt5JJgg.png" /></figure><ul><li>Look at the table above, points X1 and X2 belongs to class 2 but rest of the points X3, X4, X5 belongs to class 1.</li><li>Now if we apply the majority vote concept what we get is the given point X is belongs to class 2 as there 3 class 2 points in the neighbors of X.</li></ul><h4><strong>Note: K value should be always odd or majority vote concept will not work.</strong></h4><ul><li>To demonstrate the above claim, let&#39;s take the K = 4 (Even number) for a moment. If we assign even value for K then the majority vote concept will fail as there could be the situation of a tie of votes between two classes. Look at the table below</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*0e_1y54yGQriVMX5b2ygSA.png" /></figure><ul><li>In the above case, we cannot classify the query point X into its class as there is no winner as its tie of votes between classes.</li></ul><h3>How does K Nearest Neighbour identify the neighbors of given query point?</h3><p>We have seen a bit part of this in the above concept. Finding K will help us to identify neighbors. But wait a minute! Have we discussed, how to find “Nearest” neighbor? I am emphasizing nearest here as we are only concern about the nearest neighbor of the query point. Let’s say ‘Arjun’ and ‘Abhimanyu’ two of my friends stay close to my house. If I want to determine which one is closest among these two? I would I determine that?</p><p>Its very simple. Take the distance between your house to your friend&#39;s house and compare it. You will have an answer. In a similar fashion, K nearest neighbour algorithms calculate the distance between query point to its neighbour and choose the lowest K points as the neighbour.</p><p>The following distance measure techniques that we are going to check</p><ul><li>Euclidean Distance</li><li>Manhattan Distance</li><li>Minkowski Distance</li><li>Hamming Distance</li><li>Cosine Distance</li></ul><p>Let&#39;s understand these concepts in brief as it is necessary to understand if you wish to know about the internal implementation details of K Nearest Neighbors.</p><h4>Euclidean Distance (L2):</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*T_8xL56zlqotqWyEarl_Ag.png" /></figure><p>Let X1 and X2 are two points in 2D space and “d” is the distance between them as shown in the above diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*jDqhFrc9hVBN-FZxsqfDnQ.png" /></figure><p>We can find this distance “d” with the help of Pythagoras theorem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*AtHaZaRsj5CZaj7IIy7XEQ.png" /></figure><p>This distance in statistics is known as Euclidean Distance between two points. As for understanding purpose, we took an example of 2D by considering only two features F1 and F2. But in real life, we might have many more features and it is not restricted to two. In such cases, the formula changes. Now we will see how does Euclidean distance behave in d-dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*PINBpTXJgnVnKiHNo0Bz_A.png" /></figure><p>Note: In both cases in above we have calculated the distance between two and d points. But how do we can represent the same in vector format? After all, every point in dimension can be represented as a vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*WK6QgEBe9n4qSNJxgr3GrQ.png" /></figure><p>In above equation 2 represents its norm (L2-Norm). As distance is always between two points and the norm is always between two vectors.</p><h4>Manhattan Distance (L1):</h4><p>The Manhattan distance between two vectors (or points) X1 and X2 is defined as : →</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*-GTOqvHNwgdkjDDHUgp0fA.png" /></figure><p>This is known as Manhattan distance because all paths from the bottom left to the top right of this idealized city have the same distance as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*flNrNmDmZhfhj0KsVj6aoQ.png" /></figure><p>This distance is also noted as L1 -Norm of a vector and it is represented as shown below : →</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*2g3O0A-B9RWV9bqDnpX-mA.png" /></figure><h4>Minkowski Distance (Lp):</h4><p>Minkowski Distance between d vectors or points is defined as</p><blockquote>The Minkowski distance is a metric in a normed vector space which can be considered as a generalization of both the Euclidean distance and the Manhattan distance.</blockquote><p>This distance metric is also known as Lp-Norm of vectors and it is given by the following formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*NSuzNTYPo9zlNrMVKNGt4g.png" /></figure><p>We made a big statement above as Lp norm is a generalization of L1 and L2 norms. How can we prove that?</p><p><strong>P = 1</strong></p><ul><li>When P = 1 it takes L1 norm of a vector which is also known as Manhatten Distance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*IiLExACQRiz_aw-yZMSgQA.png" /></figure><p><strong>P = 2</strong></p><ul><li>When P = 2, it takes L2 norm of a vector which is also known as Euclidean Distance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*3zFynqHMZ1EIK4A5ndCvbg.png" /></figure><h4>Hamming Distance:</h4><p>The concept of Hamming Distance is taken from the Information Theory. It generally used in Text Processing or when the problem statement deals with binary vector or Boolean vector.</p><p>We define Hamming Distance in the following way →</p><blockquote>Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.</blockquote><p>Let’s understand this concept with the help of an example shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*_el3s4bWzbH2FqXVki4BOw.png" /></figure><p>Thus</p><blockquote><strong>The Hamming Distance (X1, X2) is nothing but the number of location or dimensions where binary vector differs.</strong></blockquote><p>Therefore, Hamming Distance (X1, X2) = 3 as it differs in 3 location as shown in the above diagram.</p><h4>Cosine Distance &amp; Cosine Similarities</h4><p>Cosine Distance is based on Cosine Similarities. There is a relationship between cosine similarities and cosine distance that we need to understand first.</p><blockquote><strong>“As distance increases, similarity decreases and vice versa.”</strong></blockquote><p>So there is an inverse or opposite relationship between similarity and distance. If you think intuitively, as the distance between two points increases which means they are not close to each other which ultimately states these two points are dissimilar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*USSfO9QB268Tif2P7UUUEw.png" /></figure><p>Let cosine similarity lies between [-1, 1] then our cosine distance actually makes sense.</p><ul><li>-1: Dissimilar</li><li>1: Similar</li></ul><p>→ <strong>If cosine similarity = 1</strong> then, cosine distance = 1–1 = 0. This actually makes sense as similarity increases the distance reduces.</p><p>→ <strong>If cosine similarity = -1</strong> then, cosine distance = 1-(-1) = 2. This too make sense as similarity decreases; distance increases.</p><p>This is what the relationship between Similarity and Distance that we should aware of. Remember these concepts not just limited to KNN algorithms but these concepts are heavily used in other areas of machine learning. Now let&#39;s understand cosine similarity in details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*5RaBtbHQuFzMBytFj846ZA.png" /></figure><p>We can find the distance between two given vector i.e. X1 and X2 using Euclidean Distance. Cosine similarity says instead of taking geometrical distance, take an angular distance. In cosine similarity, we measure the degree of angle between two vectors.</p><p>Therefore,</p><p><strong>Cosine Similarity = Cos θ ….</strong>Here θ is the angle between X1 and X2 as shown in the above diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aSHSc5KGEE2WI-8EOFT0WA.png" /></figure><p>If X1 and X2 are unit vectors then ||X1|| = ||X2|| = 1</p><p>Therefore,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*pL_TZk6PVqoQBJyCQxe-Tg.png" /><figcaption>The formula for Cosine Similarity</figcaption></figure><p>If the angular distance between two vectors is more, those vectors are considered as less similar and vice versa. Now let&#39;s understand how does the cosine metric is different than Euclidean distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*VO8vptVq6zQDSrpA-YSQ9w.png" /></figure><p>From the above diagram, we can say that →</p><ul><li>Cosine Similarity (X1, X2) = Cos θ</li><li>Cosine Distance (X1, X2) = 1- Cos θ</li></ul><p>Similar way we can find the distance between X2 and X3 i.e. D13 as shown in the above diagram</p><ul><li>Cosine Similarity (X2, X3) = Cos θ = Cos 0 = 1</li><li>Cosine Distance (X2, X3) = 1 -1 = 0</li></ul><p>As X2 and X3 are two vectors are in the same direction therefore the angle between them is 0. That is Cos θ = Cos 0 = 1. In other words, It means they are very similar. But if you go with Euclidean distance then the result would be different.</p><p><strong>D13 &gt; D12</strong></p><p>But, <strong>Cosine Distance (X2, X3) &lt; Cosine Distance(X1, X2)</strong></p><p>Now let&#39;s understand the properties of Cosine Similarities with the help of below diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*1PAyWDzPmPEXdlmzc_4jeQ.png" /><figcaption>Properties of Cosine Similarities</figcaption></figure><ul><li>If X1 and X2 are in the same direction then cosine similarity = 1 and cosine distance = 0</li><li>If X2 lies perpendicular to X1 then cosine similarity (X1, X2) = 0 and cosine distance = 1-cosine similarity = 1</li><li>If X2 and X1 is completely opposite to each other hence cosine similarity = -1 and cosine distance = 1-(-1) = 2</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*NZIrBKa4czK--Z3gXVzvQA.png" /></figure><h3>Decision Surfaces in K Nearest Neighbors:</h3><p>Until now we’ve discussed how does KNN works and also looked at various distance measure techniques that KNN uses internally. In this tutorial, we will be understanding everything about the decision surfaces in KNN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*sw-5JhDuus0ThWkYtXntOw.png" /></figure><p>Remember we haven’t learned about how to find the right value of K yet. Don’t worry about that. We will be learning that concepts in the subsequent lesson. In this section, we will be understanding how does changing the value of K affects the decision surfaces in KNN.</p><p>Basically, if you think intuitively K in KNN is often referred to Hyperparameter. Its basically controls the learning process of machine learning algorithms.</p><p>In the above diagram,</p><ul><li>Fig 1 shows the dataset is divided by the smooth curve into two classes. That is ‘Class 1 and Class 2’. The decision surface in fig 1 caused two misclassifications of points.</li><li>Fig 2 shows the dataset is divided by a non-smooth curve into two classes. That is ‘Class 1 and Class 2’. The decision surface in fig 2 makes no mistakes and there is no misclassification error that can be seen.</li></ul><p>There are two curves here which separates dataset into two different classes as we have discussed. These curves are nothing but ‘Decision Surfaces’. We call it as decision surfaces as it decides something it belongs to class 1 and something belongs to class 2. Decision surface can be thought of as a model that we are building. It&#39;s the main crux in many machine learning algorithms as it decides or separates two or more classes.</p><p>Thus changing the value of K will defiantly change the structure of these decision surfaces. Let&#39;s understand these impact by observing below cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*Q6OqXDEknFLyOnkNXkhlGQ.png" /></figure><p><strong>Case 1:-</strong></p><ul><li>Let r1, r2 and r3 are the query points in our dataset. (Points with no color)</li><li>In case 1, we have K =1. Thus to classify the given query point its 1 nearest neighbour will be investigated.</li><li>Therefore, r1 will be classified into class 1, r2 will be classified into class 2 and r3 will be in class 1.</li></ul><p><strong>Case 2:-</strong></p><ul><li>Let r1 and r2 are the query points in case 2 scenario.</li><li>In case 2, we have K = 5. Thus to classify the given query point its 5 nearest neighbours will be investigated and majority voting concepts will be used to determine its class.</li><li>r1 → Majority of nearest neighbour is labelled as a class 1and hence the query point r1 will be labelled as class 1.</li><li>r2 → Majority of nearest neighbour is labelled as a class 2 and hence the query point r2 will be labelled as class 2</li></ul><blockquote><strong>As ‘K’ increases, the smoothness of curve also increases. It means higher the K value smoother the curve.</strong></blockquote><p><strong>Case 3:-</strong></p><ul><li>Since we have not decided the right value of K hence it can be any number. We can take K = n which is nothing but all the values of the dataset.</li><li>Let r1, r2 and r3 are the query points shown in the above diagram.</li><li>If we want to classify these query points then its “n” nearest neighbours will be investigated.</li><li>In case 3, we have the situation of an unbalanced dataset. There are more class 1 points then class 2.</li><li>Since the determining factor, K =n and we have the situation of unequal class weights, in such scenario majority class will be classifying query points into class 1.</li><li>Thus when K = n, it doesn’t matter where is the query point (Near to cluster of points belongs to class 1 or near to a cluster of points belongs to class 2) it will be classified according to where is the majority of points lies.</li></ul><p>This is how the value of K affects the decision surfaces in machine learning algorithms.</p><h4>Overfitting and Underfitting from the sense of K-Nearest Neighbour:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Q6OqXDEknFLyOnkNXkhlGQ.png" /></figure><p>In this section, we will understand how does the value of K cause the ‘Overfitting and ‘Underfitting’ problems in the machine learning algorithm.</p><p><strong>Case 1:- Overfitting</strong></p><ul><li>If you observe the above diagram there are two points that fall in the wrong category. The one class 2 point is in class 1 region and one class 1 point in class 2 region.</li><li>These points are away from the bunch of same category points. These points could be erroneous or noisy or an outlier. Since KNN with K=1 will try to classify them into the correct category. In other words, it tries to overfit every small error that exists in the dataset.</li><li>Thus we can say, this model works very hard to fit every point in the dataset. This way it makes no mistakes in Training Data.</li><li>Since it does not make any mistake on training data we can say overfitting works very accurately on training data but it works poorly on unseen data.</li><li>Overfitting always have extremely non-smoothing surfaces (As shown in Fig 1)</li></ul><p><strong>Case 2:- Underfitting</strong></p><ul><li>Underfitting scenario arises mostly when the K values in KNN is equal to ’n’. (Shown in 3rd diagram )</li><li>If K=n, then we can say every point belongs to the majority class. In this case, the algorithm is underwriting, it is not trying well to fit the dataset.</li><li>Generally, in the case of underfitting, the algorithm works poorly on training as well as test data.</li></ul><p><strong>Case 3:- Well-Fitting</strong></p><ul><li>In a well-fitting scenario, the algorithm tries to balance things between ‘Overfitting &amp; Underfitting’</li><li>It neither tries to accommodate every point in the dataset into its class nor it will fit every point into one class.</li><li>In a well-fit scenario, the algorithm performs well on training as well as unseen data.</li><li>In the above diagram, fig 2 shows, it is okay to make a few mistakes as long as the majority of points classifying into the correct category.</li><li>This is a robust case and less prone to an outlier.</li></ul><h4>How do we find the correct value of K?</h4><p>As we have seen in a couple of the above section that there are a lot of things that depend upon the value of K. Be it decision surfaces and scenarios of overfitting and underfitting etc. Let&#39;s find the right value of K that will free us from the issues that we discussed earlier.</p><p><strong>Case 1:- Comparing Accuracy on Different K-Level</strong></p><p>In this case, we assign multiple random values for K and fit a model. After fitting a model accuracy parameter will be considered for each model to determine the right value of K. Take a look at the table below →</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*vs-asBmfszbleGvU_wGs-Q.png" /></figure><p>In the above table, K=9 gives good result compared to other values of K. This is a trial and error method where we randomly select K’s value and compare them on the basis of each K’s accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*imApBPNBsN6FHBKakjufoQ.png" /></figure><p>By using K=9, we get the accuracy of 0.85 which good compared to other accuracies mentioned in the table. There is a problem with this methodology though. As the objective of any ML algorithm is to perform well on future unseen data points. When an algorithm performs well on future unseen data points then it is called ‘Generalization’. Thus the objective of any machine learning algorithm is to get good ‘Generalization Accuracy’. Above explained method will not hold true for generalization. As to determine ‘K’ we are using ‘Test Data’ and to determine ‘Nearest Neighbour’ we are using ‘Train Data’.</p><p>Since we are using test data to find the right value of K and train data to find the Nearest Neighbour we cannot generalize the accuracy that we got will hold true for unseen data points. This problem is pretty much common and we use something called ‘Cross-Validation’ to answer this issue.</p><p><strong>Case 2:- Using Cross-Validation to find the value of right K</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*kxqcAG80j3BBmBGI73WoYQ.png" /></figure><p>As shown in the above diagram, we use to train and test both the dataset to find the function of KNN. In such a case, we do not test the model on the completely unseen dataset as both train and test dataset are used to find the nearest neighbour and K value respectively. Now let’s check how to address this issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*XmIybs_91wtSB-ZFlFh1Fg.png" /></figure><p>In the above case, we used train data to find the nearest neighbour, we used CV data get information about right K value. In this case, we did not use test data and it is completely unseen for us. Once we find a function of KNN with the help of train and cv data then we apply it on test data to see how does it perform with the help of the accuracy parameter. Since in this case ‘Test Data’ is completely unseen for us so we can conclude → Given a future unseen point, the accuracy will remain the same. The accuracy that we get using test data is considered as ‘Generalization Accuracy’.</p><p>This is one of the best methods is available to find the correct value of ‘K’ in the KNN algorithm. But there is one issue with this method. Let’s discuss that in details.</p><p>In the cross-validation method, we break the dataset into 3 part instead of 2. You can imagine breaking dataset this way →</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*YLYQEF8PEagmBxNGSNLrEQ.png" /></figure><p>There are scenarios where the ML algorithm needs more data in the training phase. You can call it thumb rule but more training data, better is the trained model. Is there anything that we can modify and take a benefit of 80% of the training data?</p><p>Yeah! Certainly. This is where K-Fold Cross-Validation comes into the picture. Let’s understand it in the next section.</p><p><strong>Case 3:- k-Fold Cross-Validation</strong></p><p>This is the state of the art technology to carry out cross-validation. As we’ve discussed in case 2, more training data always beneficial for a machine-learning model to learn patterns from data. k-fold cross-validation is a special case of cross-validation where we iterate over a dataset set k times. In each round, we split the dataset into k parts: one part is used for validation, and the remaining k−1 parts are merged into a training subset for model evaluation.</p><p>Step 1 →</p><p>Instead of 3, break the dataset into Training Set and Testing Set only. Here we will be using train data to compute K’s value and nearest neighbours as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*ibwvQWb1RjjkZNY2PBiG3w.png" /></figure><p>Step 2 →</p><p>‘k’ in ‘k-Fold’ denotes the given training data set is split into a ‘k’ number of sections or folds where each fold is used as a testing set at some point. Let’s say you have training data and you decided to break it into 4 then it will be called ‘4-Fold’ cross-validation technique. The value of fold is up to the user but generally, ‘10-Fold’ is followed everywhere. For simplicity, we will use the 4-Fold CV to understand it easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*liRm61bd2PtTZRAFUwvbIQ.png" /></figure><p>Let’s break training data into 4 equal parts and name it D1, D2, D3, and D4 as shown in the above diagram. Each of these chunks constitutes 20% of the total training data.</p><p>Step 3 →</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*Jcd98j8fr53ygptewjXA9Q.png" /></figure><p>In this process, we are using a total of 80% of the data to train our model and 20% of data to test. We’ve used D1, D2, D3, and D4 chunks 3 times to train the model and 1 time test the model. Since we are repeating each K-Level 4 times, we can call this method as a 4-Fold CV.</p><p>On each K-Level we have taken the average of multiple accuracies to represent a single number. This is very important to get one value for all. Next step would be comparing the average of accuracies on each K-Level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*d_oaorcLegOyZ-cH2AriWg.png" /></figure><p>Let&#39;s consider X3 is highest among the rest of the accuracies. Thus K = 3 will be selected as ‘Best K’ for our model.</p><p><strong>Major Issue with k-fold CV:-</strong></p><p>In k-fold cross-validation, we repeat the process k times to get optimum accuracy. This process is expensive and it takes some load on your CPU.</p><h4>Pseudocode for K Nearest Neighbor</h4><p>If you are coming from the computer or IT background then you might have a habit of understanding any algorithm in the form of Pseudocode. It simplifies the understanding process. Let’s take benefit of this technique to understand the KNN algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*wpKtAb_5hGDH2s-lVaa1HQ.png" /></figure><h4>Weighted K-Nearest Neighbor</h4><p>The weighted K-Nearest Neighbor is considered a modified KNN algorithm which assigns a weight to nearest neighbors of a query point. These weights are taken into consideration while labelling the query points.</p><p>Let’s understand this with a simple example that illustrated below —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*QyRTXovYxIIVzKhncpoUqQ.png" /></figure><p>Given the query point Xq we want to determine its class label Yq. In other words, let’s categories this point in either of the class. We will take help of two method to classify this point</p><ul><li>KNN</li><li>Weighted KNN</li></ul><p><strong>KNN </strong>→</p><ul><li>Let’s consider K = 5</li><li>Let X1, X2, …., X5 nearest neighbour of Xq.</li></ul><p>Lets investigate the class labels of these nearest neighbors of Xq.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*BhCDtIKcyWHvKL1YiD458g.png" /></figure><p>As per KNN algorithm, the majority vote concept is taken into account and the point Xq will be classified into positive category.</p><p>Let’s try to solve same problem with the help of weighted KNN.</p><p><strong>Weighted KNN →</strong></p><ul><li>As we discussed, In weighted KNN we assign weights to nearest neighbours and depending upon the weights we decide its class labels.</li><li>Let K = 5 in this case as well and X1, X2, X3, …, X5 are the nearest neighbours of Xq.</li><li>In weighted KNN, depending upon the distance weight is assigned to the nearest neighbours of the query point.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpZ6djWoYCsVnBa9xwjxaw.png" /></figure><ul><li>In above table for sake of understanding the concepts we have assumed distance. Note that its not actual distance that we calculated.</li><li>If you look closely, the points X1 and X2 are closest to query point Xq than other points. If I ask you question → <strong>Is it valid to give more importance (weight) to the class which are closest?</strong></li><li>In weighted KNN we tends to give more importance to the neighbours which are closest. This is the main crux of weighted KNN.</li><li>There are more weighing scales that we could use but I simply prefer simple inverse relationship that’s why the equation became weight = inverse of di.</li><li>If we take sum of the distance separately for each class then its 15 for ‘Negative Class’ and 1.75 for ‘Positive Class’. (As shown in above table)</li><li>Since 15 &gt; 1.75, we can say Xq belongs to ‘Negative Class’. This is all about weighted KNN.</li></ul><h4>Regression Using KNN</h4><p>Most of the times classification problems can be easily converted into regression problems. Though, this completely depends upon the algorithm itself. In the case of KNN we can easily modify the algorithm and use it for regression analysis.</p><p>In regression analysis, given Xq we are not predicting it’s class. But we predicts real value. There are few useful steps are followed to achieve this. Let’s see one by one.</p><p><strong>Step 1 →</strong></p><ul><li>Given Xq we need to find its nearest neighbours.</li><li>(X1, Y1), (X2, Y2), …, (Xk, Yk)</li></ul><p><strong>Step 2 →</strong></p><ul><li>Once we have all Yq’s we need to one representative number.</li><li>Representative number can be found with the help of ‘Mean’ or ‘Median’ strategy.</li><li>We need to take mean or median of all Yq’s as its real number and not a class label.</li><li>Mostly prefer ‘Median’ as its less prone to outliers.</li></ul><h4>Probabilistic class labels using KNN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQoq-OkDFc8In8wka8cWBg.png" /></figure><ul><li>This is example of two class classification. Here <strong>yi</strong> belongs to <strong>{0, 1}</strong></li><li>Let’s assume the K value i.e. K = 7. With the help of K value, we need to classify the Xq.</li><li>If we simply apply the majority vote concept for this case, the query point Xq will fall into negative category. (As -ve: 4, +ve: 3)</li><li>Out of 7 points, we have 4 negative and 3 positive. Difference between those points is very small. Thus is fair to say that → <strong>Xq is negative point by simple majority vote concept? Does it make sense?</strong></li><li>In order to mitigate above issue, we can use something called ‘Probabilistic Class Labels’.</li><li>Let’s take the example (stated in image 2 above), Here in second scenario, there are 7 negative points and 0 positive points. Now if we go by majority vote concept, Xq’ will be classified to negative class.</li><li>If you observe both the scenario, Xq’ is more certain of being in negative class than Xq. <strong>Is there any way to quantify these uncertainty? Yes, by using probabilities. (Look at the equations below)</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*kO6vP5AuQNdGRZqK_5wWBA.png" /></figure><h3>Footnote →</h3><p>This blog post delves into the K-Nearest Neighbors (KNN) algorithm, a foundational technique in machine learning used for classification and regression tasks. KNN is highlighted for its simplicity and effectiveness, operating on the principle that similar things exist in close proximity.</p><p>The post begins by introducing the basics of the KNN algorithm, explaining how it classifies new data points based on the majority vote or average of its K nearest neighbors from the training dataset. It emphasizes the importance of choosing an appropriate value of K, as it significantly impacts the model’s performance, affecting its bias and variance.</p><p>We have also discussed different ways to measure distance between data points, a critical aspect of the KNN algorithm, including Euclidean, Manhattan, and Minkowski metrics. The post also covers the pros and cons of KNN, noting its ease of understanding and implementation as advantages, while pointing out its sensitivity to irrelevant or redundant features and the curse of dimensionality as drawbacks.</p><p>This is not the end of KNN but it is enough to have understanding of the nitty gritty details of the ML algorithm.</p><p>Signing off…!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=182045ca1e00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding Vector Databases: The Core of Generative AI’s Growth!]]></title>
            <link>https://dugamakash.medium.com/decoding-vector-databases-the-core-of-generative-ais-growth-b7d319d0931f?source=rss-19a974a0393------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7d319d0931f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Akash Dugam]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 10:11:35 GMT</pubDate>
            <atom:updated>2023-11-24T02:56:48.488Z</atom:updated>
            <content:encoded><![CDATA[<p>The field of Generative AI, a frontier in the artificial intelligence landscape, is rapidly evolving, continuously pushing the boundaries of what machines can create and comprehend. At the heart of this technological marvel lies an unsung hero — vector databases. These specialized databases are pivotal in managing the complex data structures that generative AI systems rely upon.</p><p>Unlike traditional databases, vector databases are designed to efficiently handle, store, and retrieve high-dimensional vector data, which is essential for powering advanced machine learning models. This article aims to shed light on the critical role of vector databases in Generative AI, exploring their foundational concepts, technological nuances, and the challenges they help overcome. As we delve into this topic, we will unravel how these databases are not just a backend utility but a driving force in the ongoing AI revolution.</p><h3>The ABCs of Vector Databases!</h3><p>In the ever-evolving world of technology, particularly in the field of artificial intelligence (AI), there’s a growing need to understand and manage complex data. This is where vector databases come into play. But what exactly are vector databases?</p><p>Imagine you have a large collection of photos, and you want a computer to sort and understand them just like a human would. Traditional databases are like meticulously organized photo albums, with each picture neatly labelled and categorized. However, when it comes to AI, particularly Generative AI, things get a bit more complex.</p><blockquote>Generative AI doesn’t just sort data; it tries to understand patterns, create new content, and make decisions. For this, it needs to understand data in a way that’s more like how our brains perceive things, not just as simple labels or categories. This is where vector databases shine.</blockquote><p>A vector database stores data in a format that AI can easily understand and use. Let’s go back to the photo example.</p><p><strong><em>In a vector database, each photo is transformed into a “vector” — a list of numbers that represent all the intricate details and features of that photo, much like a unique fingerprint.</em></strong></p><p>These vectors help AI to not only recognize photos quickly but also to understand subtle patterns and similarities between them.</p><p>In essence, vector databases translate complex, real-world data into a language that AI can efficiently process and analyze. They are essential for advanced AI tasks like image recognition, language processing, and creating new content, which is the heart of Generative AI. By using vector databases, AI systems can operate more intuitively and effectively, mimicking the human ability to understand and interpret complex information.</p><p><strong>Here is the quick summary →</strong></p><ul><li>A vector database is a type of database designed to efficiently store and manage vector data.</li><li>Vector data, in the context of computer science and artificial intelligence, refers to data represented as arrays of numbers, often known as vectors.</li><li>These vectors are mathematical constructs that can encode various forms of complex information, such as the features of an image, the semantics of a piece of text, or the characteristics of audio.</li><li>Therefore we can say, vector databases are specialized databases optimized for storing, managing, and retrieving vector data, which is essential in various AI and machine learning applications. They provide a way to efficiently handle the complex and high-dimensional data that these applications rely on.</li></ul><h3>Vector DB Vs Relational DB Vs Non Relational DB</h3><p>It is vital to understand the difference between various DB’s that are available in the field of computer science. Below table distinguishes vector databases with other available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*_Re4RvwuiRa_PyQwouGnKg.png" /><figcaption>Image By Author</figcaption></figure><h3>Vector Embeddings</h3><p>Let’s start with the basics. First, I’ll explain what a vector is, and then we’ll talk about Vector Embeddings.</p><p>A vector is a math concept that has both size and direction. You can think of it like a point in space, with the direction being like an arrow going from the starting point (0,0,0) to where the point is in space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*WUV07U5gmJrRUTtZePx3jA.png" /><figcaption>Vectors — Image By Author</figcaption></figure><p>When we look at a bunch of vectors in one space, we can say that some are closer to one another, while others are far apart. Some vectors can seem to cluster together, while others could be sparsely distributed in the space.</p><p>Hope you have understood the concept of vector. Now let’s proceed towards understanding the concept of → “Vector Embeddings”</p><p>In the field of machine learning (ML), a fundamental concept often encountered is Vector Embeddings, especially when dealing with non-numeric data. These embeddings are crucial for ML engineers as they form the foundational elements of numerous ML and deep learning (DL) algorithms. In this discussion, we will explore what Vector Embeddings are and how they are utilized in artificial intelligence (AI).</p><blockquote><strong>Vector embeddings are a way to convert words and sentences and other data like images or audio into numbers that capture their meaning and relationships.</strong></blockquote><p>Let’s take a look at below example -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*BfeX3rS9brMbe-PdX9rk-w.png" /><figcaption>Image By Author</figcaption></figure><p>In simpler terms, when we deal with text data, different words like “cat” and “kitty” might have similar meanings, but they are made up of different letters, so they look very different to a computer. To help a computer understand that these words are similar in meaning, we use something called vectors. Vectors are a way to represent things in the computer. They help to show the computer that “cat” and “kitty” are similar, even though they are spelled differently.</p><h4>How Vectors are Embedded?</h4><ul><li><strong>For Text:</strong> Words or phrases are converted into vectors using algorithms like Word2Vec, GloVe, or BERT. These algorithms analyze a large corpus of text and learn to represent each word by a vector such that words with similar meanings have similar vectors.</li><li><strong>For Images:</strong> Techniques like Convolutional Neural Networks (CNNs) can be used to transform pixel data into vectors, capturing features like edges, textures, or more complex patterns.</li></ul><p><strong>Example —</strong></p><p>Let’s walk through the process of converting a sentence into a vector embedding using a machine learning approach. We’ll use a simplified example to make the concept clear.</p><p><strong>Sentence:</strong> <strong><em>“The cat sat on the mat.”</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*EzlB5Y1pgGsEckbGQfMs8Q.png" /><figcaption>Roadmap (Process) for creating Vector Embeddings! (Image By Author)</figcaption></figure><p>The above image illustrate the process of the creating vectors through the sentences. In similar fashion (with few changes here and there), the vectors will be created for image, audio etc.</p><h4>Type of Vector Embeddings</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*zh4V2-2URB20VbQ2fS7Rzw.png" /><figcaption>Types of vector embedding (Image By Author)</figcaption></figure><h4>Use-cases of Vector Embeddings</h4><p>Vector embeddings are used in many domains. Let’s look at few example where vector embeddings are useful.</p><ul><li><strong>Semantic Search: </strong>Traditional search engines match keywords, but with vector embeddings, semantic search understands and finds results based on the real meaning behind a query.</li><li><strong>Question-Answering Apps:</strong> By training a model with question-answer pairs, we can make an app that answers new questions it’s never seen before.</li><li><strong>Image Search: </strong>Vector embeddings are great for image search tasks. There are many ready-to-use models like CLIP and ResNet, each good for different tasks like finding similar images or detecting objects.</li><li><strong>Audio Search:</strong> We turn audio into a visual representation (audio spectrogram) and use vector embeddings to find similar sounds.</li><li><strong>Recommender Systems:</strong> We can make embeddings from structured data about things like products or articles. These are often custom-made for your specific needs. Sometimes, they can also include unstructured data like images or text descriptions.</li><li><strong>Anomaly Detection:</strong> By using large datasets of labelled sensor data, we can make embeddings to spot unusual or abnormal events.</li></ul><h3>Similarity Measures (Distance Metrics)</h3><p>Similarity measures, also known as distance metrics, in vector embeddings are crucial for many applications in machine learning and data science. They provide a way to quantify how similar or dissimilar two data points are in the vector space. Understanding these measures is essential for tasks such as clustering, classification, recommendation systems, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*RiweouJvmTQOKfnay37VMw.png" /><figcaption>Vector Embedding → Clustering Similar Objects! (Image By Author)</figcaption></figure><p>Here each of these datapoints are mapped into the 2D vector space as illustrated in above image. If you observe carefully, fruits like Apple, Banana and Orange falls within the same region as they belongs to fruit category. Look at their embeddings, they are very close to each other as well. Same goes with category like Veggies and Flowers.</p><p>Since human understand these are fruits and needs to be clustered into fruit category. In order comprehend same things by computer / AI we need to measure the distance or similarity of vectors. Now you may ask, how do we measure the similarity or distance between datapoints / vectors? Take a look at below —</p><ul><li>Euclidian Distance</li><li>Manhattan Distance</li><li>Hamming Distance</li><li>Cosine Similarity</li></ul><p>These are the commonly used similarity or distance metrics in vector embeddings.</p><h4><strong>Euclidean Distance (L2):</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*T_8xL56zlqotqWyEarl_Ag.png" /></figure><p>Let X1 and X2 are two points in 2D space and “d” is the distance between them as shown in the above diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*jDqhFrc9hVBN-FZxsqfDnQ.png" /></figure><p>We can find this distance “d” with the help of Pythagoras theorem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*AtHaZaRsj5CZaj7IIy7XEQ.png" /></figure><p>This distance in statistics is known as Euclidean Distance between two points. As for understanding purpose, we took an example of 2D by considering only two features F1 and F2. But in real life, we might have many more features and it is not restricted to two. In such cases, the formula changes. Now we will see how does Euclidean distance behave in d-dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*PINBpTXJgnVnKiHNo0Bz_A.png" /></figure><p>Note: In both cases in above we have calculated the distance between two and d points. But how do we can represent the same in vector format? After all, every point in dimension can be represented as a vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*WK6QgEBe9n4qSNJxgr3GrQ.png" /></figure><p>In above equation 2 represents its norm (L2-Norm). As distance is always between two points and the norm is always between two vectors.</p><h4><strong>Manhattan Distance (L1):</strong></h4><p>The Manhattan distance between two vectors (or points) X1 and X2 is defined as : →</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*-GTOqvHNwgdkjDDHUgp0fA.png" /></figure><p>This is known as Manhattan distance because all paths from the bottom left to the top right of this idealized city have the same distance as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*flNrNmDmZhfhj0KsVj6aoQ.png" /></figure><p>Imagine you are in a city where the streets are laid out in a perfect grid, and you want to travel from the bottom left corner of the city to the top right corner. Unlike in a diagonal straight line (which would be the Euclidean distance), in a grid system like Manhattan, you must travel along the streets, which means moving either horizontally or vertically.</p><p>In such a grid, all paths from the bottom left to the top right corner (assuming you only move right or up, without backtracking) have the same length in terms of distance traveled. This is because you’re simply switching the order in which you travel across the grid’s horizontal and vertical lines, but the total number of lines crossed remains constant.</p><p>This distance is also noted as L1 -Norm of a vector and it is represented as shown below : →</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*2g3O0A-B9RWV9bqDnpX-mA.png" /></figure><h4>Hamming Distance:</h4><p>The concept of Hamming Distance is taken from the Information Theory. It generally used in Text Processing or when the problem statement deals with binary vector or Boolean vector.</p><p>We define Hamming Distance in the following way →</p><blockquote>Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.</blockquote><p>Let’s understand this concept with the help of an example shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*_el3s4bWzbH2FqXVki4BOw.png" /></figure><p>Thus the hamming distance (X1, X2) is nothing but the number of location or dimensions where binary vector differs.</p><p>Therefore, Hamming Distance (X1, X2) = 3 as it differs in 3 location as shown in the above diagram.</p><h4><strong>Cosine Distance &amp; Cosine Similarities:</strong></h4><p>Cosine Distance is based on Cosine Similarities. There is a relationship between cosine similarities and cosine distance that we need to understand first.</p><blockquote>“As distance increases, similarity decreases and vice versa.”</blockquote><p>So there is an inverse or opposite relationship between similarity and distance. If you think intuitively, as the distance between two points increases which means they are not close to each other which ultimately states these two points are dissimilar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*USSfO9QB268Tif2P7UUUEw.png" /></figure><p>Let cosine similarity lies between [-1, 1] then our cosine distance actually makes sense.</p><ul><li>-1: Dissimilar</li><li>1: Similar</li></ul><p>→ If cosine similarity = 1 then, cosine distance = 1–1 = 0. This actually makes sense as similarity increases the distance reduces.</p><p>→ If cosine similarity = -1 then, cosine distance = 1-(-1) = 2. This too make sense as similarity decreases; distance increases.</p><p>This is what the relationship between Similarity and Distance that we should aware of. Remember these concepts not just limited to Vector databases but these concepts are heavily used in other areas of machine learning. Now let’s understand cosine similarity in details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*5RaBtbHQuFzMBytFj846ZA.png" /></figure><p>We can find the distance between two given vector i.e. X1 and X2 using Euclidean Distance. Cosine similarity says instead of taking geometrical distance, take an angular distance. In cosine similarity, we measure the degree of angle between two vectors.</p><p>Therefore,</p><p><strong>Cosine Similarity = Cos θ ….</strong>Here θ is the angle between X1 and X2 as shown in the above diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*aSHSc5KGEE2WI-8EOFT0WA.png" /></figure><p>If X1 and X2 are unit vectors then ||X1|| = ||X2|| = 1</p><p>Therefore,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*pL_TZk6PVqoQBJyCQxe-Tg.png" /><figcaption>The formula for Cosine Similarity</figcaption></figure><p>If the angular distance between two vectors is more, those vectors are considered as less similar and vice versa.</p><h3>Vector Indexing</h3><p>Vector is the method of organizing and managing vector embeddings to enable efficient retrieval, search, or comparison operations.</p><blockquote><strong>In short, we can say → Vector indexing is nothing but organizing the similar vectors together.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*XK5LZ1L6f5Qf3I1nz0YaXg.png" /><figcaption>Indexing Process (Image By Author)</figcaption></figure><h4>How Vector Indexing Works</h4><ol><li><strong>Storing Vectors: </strong>Initially, vector embeddings are created from data (like text, images, etc.). These vectors are multi-dimensional and represent the features of the data.</li><li><strong>Index Creation:</strong> An index is built to organize these vectors in a way that optimizes search and retrieval operations. This index can be thought of as a specialized database for vectors.</li><li><strong>Searching the Index:</strong> When a query is made (which is also converted into a vector), the indexing system efficiently searches through the vectors to find the most relevant or similar ones.</li></ol><p>Now let’s take an example to explain this concept thoroughly.</p><p><strong>Example</strong></p><p>Let’s consider an example with a text search application:</p><p><strong>Dataset:</strong></p><p>Suppose we have a large collection of documents. Each document is converted into a vector embedding using techniques like TF-IDF, Word2Vec, or BERT.</p><p><strong>Building the Index:</strong></p><ul><li>The vectors from all documents are stored in an index.</li><li>The index might use algorithms like k-Nearest Neighbors (k-NN) or more complex structures like trees or hash tables to organize these vectors.</li></ul><p><strong>Performing a Search:</strong></p><ul><li>A user inputs a search query, like “machine learning.”</li><li>The query is also converted into a vector using the same method used for the documents.</li><li>The index quickly searches for and retrieves document vectors that are closest to the query vector in terms of cosine similarity or another similarity metric.</li></ul><p><strong>Retrieving Results:</strong></p><ul><li>The documents corresponding to the top matching vectors are retrieved and presented to the user.</li><li>This process is much faster than comparing the query vector to every document vector individually.</li></ul><h4>Importance of Vector Indexing</h4><ul><li><strong>Efficiency:</strong> Vector indexing allows for efficient retrieval in large datasets, reducing the search space and computational load.</li><li><strong>Scalability:</strong> It makes it feasible to work with very large datasets that would otherwise be impractical to handle.</li><li><strong>Accuracy:</strong> By using sophisticated indexing algorithms, the accuracy of retrieval can be enhanced, ensuring more relevant results for queries.</li></ul><h3>Architecture of Vector Database</h3><p>The architecture of a vector database is designed to efficiently store, manage, and retrieve high-dimensional vector data, often used in machine learning and data science applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h3QVXKD32AzndIVf.png" /><figcaption>Source → <a href="https://www.pinecone.io/learn/vector-database/">https://www.pinecone.io/learn/vector-database/</a></figcaption></figure><p>Let’s understand this with the help of below pointers →</p><ul><li>Regardless of the content type such as images, emails or text documents, we utilize the embedding model to convert them to vector embeddings.</li><li>These embeddings are then loaded into vector databases where they are efficiently clustered &amp; indexed based on their similarity.</li><li>When the application issues a query, we use the same embedding model to create embeddings for the query and use those embeddings to query the database for similar vector embeddings.</li><li>The vector database performs a search based on the query vector and retrieves the relevant results for the application.</li></ul><p>In order to illustrate further consider the below example in IT threat detection application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*99jdTI_WTj3imB0oEnz5UA.png" /><figcaption>Web Traffic Anomaly Detection (Image By Author)</figcaption></figure><p>We have the activities represented as → Regular, Suspicious and Malicious in vector dimension space. By querying the vector database, we can determine if activity close to regular activity or suspicious activity or malicious activity. This allows us to classify the web traffic based on the proximity to vector space.</p><p>If we take the distance between query vector (?) with regular, suspicious and malicious it is evident that the query vector is near to malicious vector. Here query vector is the web traffic. Therefore we can consider the query vector (a web traffic) is malicious one. Therefore, it is like classification or anomaly detection.</p><p>So by using the vector database, we can establish common ground a common ground for managing different types of unstructured data and this is why vector database is needed and indeed it is solving the fundamental problem of unstructured data.</p><h3>How does a vector database work?</h3><p>In traditional databases, the queries typically aim to find rows where the values exactly match the specified query criteria. On the other hand, in vector databases, the approach is different: we use a similarity metric to identify a vector that most closely resembles our query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_n5v5OgWly3tfMqN.png" /><figcaption>Source → <a href="https://www.pinecone.io/learn/vector-database/">https://www.pinecone.io/learn/vector-database/</a></figcaption></figure><p>A vector database works by efficiently storing, indexing, and retrieving high-dimensional vector data, which is often used in applications involving machine learning, AI, and big data analytics. Here’s an overview of how it operates.</p><h4>Step 1 → Data Conversion to Vectors</h4><ul><li><strong>Input Data:</strong> The data can be of various types like text, images, audio, etc.</li><li><strong>Conversion Process:</strong> This data is transformed into vectors using machine learning models. For instance, text can be converted using models like BERT or Word2Vec, images with CNNs, etc. Each vector is a numeric representation of the data, capturing its essential features.</li></ul><h4>Step 2 → Indexing the Vectors</h4><p>The main purpose of the indexing is to enable efficient searching within the vector databases. To do this, various algorithm is used to index these vectors which includes —</p><ul><li><strong>k-Nearest Neighbours (k-NN):</strong> For finding vectors closest to a query vector.</li><li><strong>Locality-Sensitive Hashing (LSH):</strong> For grouping similar vectors.</li><li><strong>Hierarchical Navigable Small World (HNSW):</strong> A graph-based approach for indexing.</li></ul><p>The indexing creates a structure that makes it easier and faster to search through a large number of vectors.</p><h4>Step 3 → Query Processing</h4><ul><li><strong>Query as a Vector:</strong> When a user has a query (like a text query or an image), it is also converted into a vector using the same method as the database vectors.</li><li><strong>Searching:</strong> The vector database uses the index to quickly find vectors that are most similar to the query vector.</li><li><strong>Similarity Metrics:</strong> The search relies on similarity metrics like cosine similarity, Euclidean distance, etc., to determine the ‘closeness’ of vectors.</li></ul><h4>Step 4 → Retrieving Results</h4><ul><li><strong>Matching Vectors:</strong> The database retrieves the data items corresponding to the vectors that closely match the query vector.</li><li><strong>Use Cases:</strong> This could be, for example, finding similar images, recommending products, or searching for similar documents.</li></ul><h4>Step 5 → Post-Processing (Optional)</h4><ul><li><strong>Refinement:</strong> The initially retrieved results might undergo further processing like re-ranking based on additional criteria or filters.</li><li><strong>Accuracy vs. Speed</strong>: There’s often a trade-off between the accuracy of the results and the speed of retrieval. More accurate results might take longer to retrieve.</li></ul><h4>Example</h4><p>Imagine a vector database used for a photo search application:</p><ul><li><strong>User Uploads an Image:</strong> The image is converted into a vector.</li><li><strong>Database Search:</strong> The vector database quickly scans through its indexed vectors to find images whose vectors are most similar to the uploaded image’s vector.</li><li><strong>Result:</strong> The user is presented with images that are visually similar to the uploaded image.</li></ul><p>In essence, a vector database is specialized in handling complex, high-dimensional data that traditional databases aren’t equipped to manage efficiently. Its ability to rapidly process and retrieve similar items based on vector proximity makes it invaluable in fields like AI and data science.</p><p>Enough of the theory now. Let’s get our hands dirty with some practical’s / coding.</p><h3>Journey of Vector Databases with Pinecone!</h3><p>Pinecone is a specialized database service designed to efficiently handle vector data, which is commonly used in machine learning applications. This service is particularly useful for tasks that involve searching and comparing vectors, such as in recommendation systems, image recognition, and natural language processing tasks.</p><p>Vector databases like Pinecone are crucial in the field of machine learning because they enable quick and accurate retrieval of similar items from large datasets. For instance, in a recommendation system, Pinecone can quickly find products or content similar to a user’s interests by comparing their preference vectors with those in the database.</p><p>Pinecone stands out for its scalability and performance, offering high-speed vector search capabilities. This is essential for real-time applications where rapid data retrieval is critical. Additionally, its user-friendly interface and integration capabilities make it accessible for both experienced developers and those new to vector databases.</p><h4>Environment Setup &amp; Installation</h4><p>To begin incorporating Pinecone into your GenAI project, the initial step is to set up an account with Pinecone. This can be done by visiting their official website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*j09CpIl0DU_yAeR4vezEIA.png" /><figcaption><a href="https://www.pinecone.io/">https://www.pinecone.io/</a></figcaption></figure><p>After establishing your account with Pinecone, you can proceed to configure your projects and generate the necessary API keys. These keys will be essential for performing various operations and implementing use cases with Pinecone.</p><p>As we are utilizing Python to execute operations in Pinecone, it’s necessary to install Pinecone using the ‘pip’ command.</p><pre>&gt; pip install pinecone-client</pre><p>Follow official guide on installation → <a href="https://docs.pinecone.io/docs/python-client">https://docs.pinecone.io/docs/python-client</a></p><h4>Hello World with Pinecone</h4><p>Let’s play with Pinecone database through Python.</p><pre># Import Pinecone Library<br>import pinecone<br><br># Initialize API Key<br>pinecone.init(api_key=&quot;a4345490-b8s9-48e7-8f95-1bce784d353d&quot;,<br>              environment=&quot;gcp-starter&quot;)<br><br># Create an index<br>pinecone.create_index(name=&quot;hello-world&quot;,<br>                      dimension=3,<br>                      metric=&quot;cosine&quot;) # cosine is default<br><br># check on all the indexes<br>pinecone.list_indexes()<br><br># This will return [&#39;hello-world&#39;] as output.</pre><h4>CRUD with Pinecone!</h4><p>CRUD operations, which stand for Create, Read, Update, and Delete, are fundamental in managing data in databases or data storage services. When working with Pinecone, a vector database that’s often used for machine learning applications, these operations are adapted to handle vector data. Let’s get started with Create.</p><p><strong>Create:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*ctJeMJq4bLJ3bEAZuBxJjg.png" /><figcaption>Create Operation (Image by Author)</figcaption></figure><p><strong>Read:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*qmejExnRmE6_CU_bVHsiPQ.png" /><figcaption>Read Operation (Image by Author)</figcaption></figure><p><strong>Update:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*U4cih88phhiDoUtyLuJZ9w.png" /><figcaption>Update Operation (Image by Author)</figcaption></figure><p><strong>Delete:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*udgvakgnU8BBcQ3HgaHIPA.png" /><figcaption>Delete Operation (Image by Author)</figcaption></figure><h4>Concept of Index &amp; Collections</h4><p>Let’s delve into the crucial concept on an index and collection.</p><blockquote>An index in Pinecone is a named collection of vectors. These vectors are essentially high-dimensional data points, typically generated as outputs from machine learning models.</blockquote><p><strong>Functionality</strong></p><ul><li><strong>Storing Vectors:</strong> An index holds a set of vectors. For example, in an index named ‘test’, which has three dimensions, there are multiple vectors stored within these dimensions.</li><li><strong>Querying:</strong> The primary function of an index is to allow querying. You can search through the vectors in an index to find matches or similar vectors based on specific criteria or algorithms.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*AU90a_r59BeFy4gpmhyqmQ.png" /><figcaption>Index &amp; Collection (Image By Author)</figcaption></figure><blockquote>A collection is a static copy of an index in Pinecone. It’s a snapshot or a backup of the state of an index at a given point in time.</blockquote><p><strong>Characteristics and Use:</strong></p><ul><li><strong>Static Nature:</strong> Unlike an index, a collection is static. You cannot query a collection like you can with an index. It’s essentially a read-only copy of the index data.</li><li><strong>Purpose:</strong> The main purpose of a collection is for backing up an index. It serves as a means to preserve the state of an index before making changes.</li></ul><h4>Managing Index and Collection</h4><p>We have already seen the concept of Index and Collection above. Let’s get some idea on → <strong>How to manage them?</strong></p><p><strong>Creating an Index:</strong></p><p>You start by creating an index (e.g., ‘test’) where vectors are stored and can be queried.</p><p><strong>Modifications and Backup:</strong></p><ul><li>When you need to modify the index (like changing the index type or distance metrics), you first create a static copy of the current index as a collection.</li><li>This backup ensures that the original data is not lost during the transition.</li></ul><p><strong>Creating a New Index from Collection:</strong></p><ul><li>You can create a new index with the desired changes (e.g., different index type or distance metrics).</li><li>This new index can be populated with vectors from the collection.</li><li>Multiple indexes can be created from the same collection if needed.</li></ul><p><strong>Querying New Index:</strong></p><p>Once the new index is set up and populated, it’s ready for querying. The collection remains as a static backup.</p><p>Let’s see how index can be managed with Python!</p><pre>### Import Pinecone Library<br>import pinecone<br><br>### Pinecone Initialization<br>pinecone.init(api_key=&quot;a4345490-b8s8-48e7-8f95-1bce784d353d&quot;,<br>              environment=&quot;gcp-starter&quot;)<br><br>### 1. Create an Index<br>pinecone.create_index(name=&quot;crud&quot;,<br>                      dimension=3,<br>                      metric=&quot;cosine&quot;,  # cosine is default<br>                      pod_type=&quot;s1&quot;)<br><br>### 2. Retrieve List of Pinecone Database Indexes<br>pinecone.list_indexes() # --&gt; This will return [&#39;crud&#39;]<br><br>### 3. Connect to Index<br>con = pinecone.Index(&#39;crud&#39;) #We need to describe pointer to connect with Indexes<br><br>### 4. Describe the Index<br>pinecone.describe_index(name=&#39;crud&#39;)<br><br>### This will return below output. Its information about index that you created.<br>&quot;&quot;&quot; IndexDescription(name=&#39;crud&#39;, metric=&#39;cosine&#39;, replicas=1, dimension=3.0, <br>shards=1, pods=1, pod_type=&#39;starter&#39;, status={&#39;ready&#39;: True, &#39;state&#39;: &#39;Ready&#39;}, metadata_config=None, source_collection=&#39;&#39;)&quot;&quot;&quot;<br><br>### 5. Delete an Index<br>pinecone.delete_index(name=&#39;crud&#39;)</pre><h4>Backing Up Indexes with Collections</h4><p>As described above, we need Collections to have backup of Indexes. Let’s create Collection first then will move towards creating the backup.</p><pre>### Step 1 - Let’s create an index<br>pinecone.create_index(‘test’, dimension=3,<br>                       metric=’dotproduct’, pod_type = ‘s1’)<br><br>### Step 2 - Lets Create Collection from Index<br>pinecone.create_collection(name = &quot;my-collection&quot;, source = &quot;test&quot;)<br><br># You can list all collections from database<br>pinecone.list_collections() # --&gt; This will return [my-collection]<br><br># Describe the Collection<br>res = pinecone.describe_collection(&quot;my-collection&quot;)<br>res.dimensions # --&gt; It will return 3 as dimension<br><br># Delete the Collection<br>pinecone.delete_collection(&quot;my-collection&quot;) <br><br>### Step 3 - Continue from Step 2<br># Now once you create an collection, you can visit the WebApp to <br># create the index from collections.</pre><p>Now once you create an collection, you can visit the dashboard in pinecone WebApp to create index from the created collections.</p><h4>Vector Partitioning</h4><p>Vector partitioning is a technique used in database management, especially in systems dealing with large-scale, high-dimensional data such as those found in machine learning applications. It’s particularly relevant for databases that store and manage vectors, which are arrays of numbers representing various features or attributes.</p><p><strong>Why Partition Vectors?</strong></p><p>Partitioning helps manage large datasets by dividing them into smaller, more manageable segments. This division can improve query performance, enhance scalability, and facilitate better load balancing across the database system.</p><p>Consider a database containing emails where each email is represented as vectors for its subject, body, and other metadata.</p><ul><li><strong>Without Partitioning:</strong> Searching through this unpartitioned data might be slow and inefficient, especially as the database grows.</li><li><strong>With Partitioning:</strong> By partitioning these vectors into different categories (e.g., subjects, bodies), the database can quickly access and search through specific types of data, improving performance.</li></ul><p><strong>Methods of Partitioning</strong></p><ol><li><strong>Namespaces:</strong></li></ol><ul><li>Different types of vectors are stored under the same index but categorized into different namespaces.</li><li>With email data, each email is converted into vectors representing the subject, body, and other information. These vectors are then categorized into different namespaces (e.g., subject, body, other) within the same index</li></ul><p><strong>2. Separate Indexes:</strong></p><ul><li>Each category of vectors has its own dedicated index.</li><li>Instead of a single index for all email vectors, separate indexes are created for subjects, bodies, and other information.</li></ul><p><strong>3. Metadata Tagging:</strong></p><ul><li>Vectors are tagged with metadata to indicate their type or category, still residing in the same index.</li><li>In the e-commerce example, a vector for a shirt might have metadata tags like “category: clothing” and “color: blue.”</li><li>A vector from an email’s subject might have metadata like “data type: subject”, while a body vector might have “data type: body”.</li></ul><p><strong>Benefits of Vector Partitioning</strong></p><ul><li><strong>Improved Query Performance:</strong> By organizing data into relevant partitions, the system can quickly access the necessary subset of data, speeding up search and retrieval processes.</li><li><strong>Scalability:</strong> As data grows, partitioning makes it easier to manage and scale the database across multiple nodes or servers.</li><li><strong>Load Balancing:</strong> Distributing data across different partitions or nodes allows for more efficient use of resources and prevents any single node from becoming a bottleneck.</li><li><strong>Fault Tolerance:</strong> Partitioning can enhance the robustness of the database by isolating issues within a single partition, preventing them from affecting the entire database.</li><li><strong>Optimized Resource Utilization:</strong> Partitioning can lead to more efficient use of storage and processing resources. By organizing data into partitions based on similarity, related data is stored and processed together, optimizing resource use.</li></ul><h3>Final Note</h3><p>This extensive article explores vector databases, which are at the core of Generative AI’s growth. we have emphasized the critical role of vector databases in managing complex data structures essential for advanced machine learning models. The article delves into foundational concepts, technological nuances, and the challenges overcome by vector databases.</p><p>Key concepts discussed include:</p><ol><li><strong>Vector Databases:</strong> These are specialized databases optimized for handling, storing, and retrieving high-dimensional vector data. Unlike traditional databases, vector databases efficiently manage data represented as arrays of numbers (vectors), crucial for AI and machine learning applications.</li><li><strong>Vector Embeddings:</strong> This section explains how non-numeric data, like text or images, is converted into vectors that capture meaning and relationships, using algorithms like Word2Vec, GloVe, or BERT for text, and Convolutional Neural Networks for images.</li><li><strong>Similarity Measures (Distance Metrics):</strong> The article discusses various metrics like Euclidean Distance, Manhattan Distance, Hamming Distance, and Cosine Similarity, which are used to measure the similarity or dissimilarity between vectors.</li><li><strong>Vector Indexing:</strong> It covers how vector embeddings are organized and managed for efficient retrieval, highlighting processes like storing vectors, creating indexes, and searching the index.</li><li><strong>Architecture of Vector Database:</strong> The architecture is designed for efficient management and retrieval of high-dimensional vector data, with applications in machine learning and data science.</li><li><strong>Practical Applications with Pinecone:</strong> Pinecone is introduced as a specialized database service for handling vector data. The article guides through environment setup, installation, and practical operations in Pinecone, including CRUD operations, managing indexes and collections, and vector partitioning.</li><li><strong>Benefits of Vector Partitioning:</strong> The article explains the advantages of partitioning vectors, such as improved query performance, scalability, load balancing, and fault tolerance.</li></ol><p>Overall, the article provides a comprehensive understanding of vector databases, their importance in AI and machine learning, and practical insights into using a vector database service like Pinecone.</p><p>Please follow me on Medium as more Generative AI content is coming on your way. :)</p><h3><strong>TaaDaaa!</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7d319d0931f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The ABCs of DevOps (Part I)]]></title>
            <link>https://dugamakash.medium.com/the-abcs-of-devops-part-i-27617e9be3b8?source=rss-19a974a0393------2</link>
            <guid isPermaLink="false">https://medium.com/p/27617e9be3b8</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Akash Dugam]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 02:12:40 GMT</pubDate>
            <atom:updated>2023-02-24T02:12:40.696Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever come across the terms DevOps or MLOps while working on a software development or data science project? If so, you may have wondered what they are and why they’re important. You might also be curious about how to use DevOps in your current project.</p><p>This blog is designed to increase your understanding of the DevOps and MLOps domains and how large companies effectively use them in their projects. Also, the blog is written in easy-to-understand language, making it beginner-friendly. I have included examples wherever necessary, and the contents are structured to help you quickly find what you’re looking for. Let’s take a quick look at what this blog covers.</p><ol><li>Introduction to DevOps</li><li>DevOps Pipeline</li><li>Continuity Matters</li></ol><p>As this is an introductory blog post, I will keep it brief and straightforward. The more complex topics will be covered in subsequent parts or series of this blog. Follow me <a href="https://dugamakash.medium.com/">here</a> to stay tuned for future updates. :)</p><h3>Introduction to DevOps!</h3><p>The main idea behind DevOps is to improve the collaboration and communication between the development and operations teams in software development. Traditionally, the development team would create the software, and then the operations team would deploy and maintain it. However, this approach can lead to delays, errors, and miscommunication between the two teams.</p><blockquote>DevOps = Software Development + Operations</blockquote><p>DevOps brings together the development and operations teams to work together throughout the entire software development process. This collaboration helps to streamline the process and ensure that everyone is working towards a common goal.</p><p>Let me give you an example to help you understand better -</p><p>Imagine a small software development team working on a new mobile app for a startup company. The developers are working quickly to build out the features and functionality of the app, while the operations team is focused on setting up the infrastructure for deployment. However, the two teams are working in isolation, without communicating or collaborating effectively.</p><p>When the app is launched, it becomes immediately clear that there are performance issues and user complaints about slow loading times and crashes. The development team identifies some bugs and makes fixes, but deploying the updated version is a slow and difficult process due to a lack of coordination and automated deployment processes.</p><p>As a result, the updated app is not delivered to users for several days, leading to further frustration and lost revenue for the startup.</p><h3>DevOps Pipeline</h3><blockquote>A DevOps pipeline, also known as a continuous delivery pipeline or release pipeline, is a series of automated steps that a software application goes through, from development to deployment.</blockquote><p>The DevOps pipeline is designed to ensure that each change to the application is thoroughly tested and validated before it is deployed to production.</p><p>As I have described already, DevOps is a practice that brings together software development and operations. During the development stage, software developers write, test, and debug code. On the other hand, in the operations stage, the developed software is deployed to production and monitored to ensure efficient performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4tEed7bUAcJMZcS-.jpg" /><figcaption>DevOps Life Cycle (Image Source:<a href="https://crestere.io/devops">https://crestere.io/devops</a>)</figcaption></figure><p>Let’s now talk about the various pipeline stages of DevOps!</p><h4><strong>Plan Phase (Dev)</strong></h4><p>The Plan phase is the initial stage of the DevOps lifecycle, during which teams plan and prioritize the work that needs to be done. It’s the phase where a Product Manager or Project Manager proves their worth.</p><p>The requirements related to development will be extracted from the stakeholders and customers to build the product roadmap which will serve as a guide for future development activities.</p><p>In short, this phase includes the →</p><ul><li>Defining the project scope,</li><li>Determining the requirements,</li><li>Setting the goals and objectives</li><li>Creating a roadmap to guide the development process.</li></ul><p>Some of the activities that take place during the Plan phase include:</p><ol><li><strong>Defining the project scope:</strong> The project scope outlines the boundaries and constraints of the project, including the features and functionality that will be included.</li><li><strong>Determining the requirements:</strong> The requirements specify the functional and non-functional requirements of the software, including user stories, use cases, and acceptance criteria.</li><li><strong>Setting goals and objectives:</strong> The goals and objectives define what the project is intended to achieve, including business outcomes, customer satisfaction, and other key performance indicators (KPIs).</li><li><strong>Creating a roadmap:</strong> The roadmap provides a high-level view of the development process, including the timeline, milestones, and key deliverables.</li></ol><p><strong>Example:</strong></p><p>One example of the Plan phase in action might involve a team developing a new e-commerce platform.</p><p>During the Plan phase, the team might work on defining the project scope by specifying the features that the platform should include, such as a shopping cart, product search functionality, and secure checkout.</p><p>They might also determine the requirements for the platform, such as the need to support multiple payment options and integrations with third-party services.</p><p><strong>Required Tools:</strong></p><ul><li>Microsoft Office, Google Documents</li><li>Microsoft Project (Project Management Tools)</li><li>JIRA, Asana, Mantis (Task Management tool)</li></ul><p>During the Plan stage, the product roadmap is created by gathering feedback and requirements from stakeholders and customers. The product roadmap is then broken down into smaller units such as Epics, Features, User Stories, and Backlogs of tasks based on the requirements.</p><p>A ticket management system such as Jira, Azure DevOps, or Asana can be used to record and track the product roadmap. These tools offer a variety of features that aid in monitoring project progress, milestones, and issues. The tasks listed in the Backlog are used to plan the sprint and allocate them to teams to kickstart the development.</p><p>Before the development team starts writing code, the tasks are prioritized and organized into sprints. A sprint is a short, time-boxed period during which a team works to complete the tasks allocated to them. Typically, a sprint lasts between one and four weeks, and each sprint is focused on delivering a specific set of features or improvements.</p><p>During the sprint planning, the development team will evaluate each task in the Backlog, estimate the time and resources required to complete it, and prioritize it based on its importance. The team will then allocate the tasks to individual team members, considering their skills, expertise, and workload.</p><p>Once the sprint has begun, daily meetings or stand-ups are conducted to track progress, identify and address any obstacles or issues, and ensure that the project is on track. This allows the team to stay in sync and adapt quickly to any changes or challenges that arise during the development process.</p><p>In summary, the Plan stage is critical in establishing the roadmap for the project, breaking it down into manageable tasks, and prioritizing them for allocation to the development team during the sprint planning.</p><h4>Code Phase (Dev)</h4><p>The Code phase is an essential stage in the DevOps lifecycle where development teams write and build the code for the software application. This stage involves designing, coding, testing, and integrating the application code.</p><p>During the Code phase, the development team uses various coding languages and tools to write the application code that meets the requirements defined in the Plan phase.</p><p>Once the code is written, the team will test it thoroughly to ensure it is functional and free of bugs before moving on to the next stage.</p><p>The Code phase may involve the following activities:</p><ol><li><strong>Designing the application architecture:</strong> The team needs to design the application architecture, including the framework and the software stack required to run the application.</li><li><strong>Writing code:</strong> Once the application architecture is designed, the development team starts writing the code for the application.</li><li><strong>Code testing:</strong> The team tests the code to ensure it is functional and free of bugs. This includes unit testing, functional testing, integration testing, and performance testing.</li><li><strong>Code review:</strong> The team performs code reviews to ensure code quality and maintainability.</li><li><strong>Integration:</strong> Once the code is tested and reviewed, the team integrates it with other components of the software application.</li></ol><p><strong>Example:</strong></p><p>Let’s say a development team is building a mobile app for a new ride-sharing service. In the Code phase, the team would use programming languages such as Java or Swift, as well as tools and frameworks such as Android Studio or Xcode, to write the code for the app. They would also use development methodologies such as Agile or Scrum to manage their work and ensure that the code is delivered on time.</p><p>Once the team has written the code, they would then move on to testing it. They would use testing frameworks such as Appium or Espresso to perform unit tests, integration tests, and end-to-end tests to ensure that the app functions as intended and is free of bugs.</p><p>After the testing phase, the team would then perform code reviews to ensure the quality and maintainability of the code. They would use code review tools such as GitHub or Bitbucket to collaborate with other team members and ensure that the code is clean, efficient, and adheres to best practices.</p><p><strong>Required Tools:</strong></p><p>Some tools that can be used during the Code phase are:</p><ul><li>Code editors such as Visual Studio Code, Atom, or Sublime Text</li><li>Version control systems such as Git, SVN, or Mercurial</li><li>Code review tools such as GitHub, Bitbucket, or GitLab</li><li>Testing frameworks such as JUnit, Selenium, or Jest</li><li>Continuous integration and delivery (CI/CD) tools such as Jenkins, Travis CI, or CircleCI</li></ul><h4>Build Phase (Dev)</h4><p>The Build phase in the DevOps lifecycle is where the development team actually starts building the software. The software code is written, tested, and prepared for deployment in this phase.</p><p>The first step in the Build phase is committing the code to a shared repository. The developer writes the code and commits it to a code repository like Git or SVN. Once the code is committed, the developer creates a pull request to merge the new code with the shared codebase.</p><p>Then, another developer reviews the code changes to ensure that there are no issues. The review process is quick and lightweight, but it’s effective in identifying potential issues early. If the reviewer approves the code changes, the code is merged with the shared codebase. If there are issues, the reviewer rejects the code changes, and the developer is notified to resolve the issue.</p><p>In parallel, an automated build process is triggered, which builds the codebase and runs a series of tests to identify any issues. These tests include end-to-end, integration, and unit tests. If the build fails or any of the tests fail, the pull request fails, and the developer is notified to fix the issues.</p><p>By continuously checking code changes into a shared repository and running builds and tests, integration issues can be minimized, and breaking bugs can be identified early in the development lifecycle. This approach ensures that the software is always in a deployable state, and the team can deploy it to production with confidence.</p><p><strong>Example:</strong></p><p>In the previous Code phase example, the development team built a ride-sharing app. During the Build phase, the team would use build tools such as Gradle or Xcode to compile the source code and create an executable version of the app that can be installed on a mobile device.</p><p>Additionally, the team may also use tools to automate the build process, such as Continuous Integration and Delivery (CI/CD) tools like Jenkins or CircleCI. These tools can automatically compile the code and create new builds of the app whenever changes are pushed to the source code repository.</p><p><strong>Required Tools:</strong></p><p>Some tools that can be used during the Build phase are:</p><ul><li>Build automation tools such as Apache Maven, Gradle, and Ant</li><li>Continuous Integration and Delivery (CI/CD) tools such as Jenkins, Travis CI, or CircleCI</li><li>Containerization tools such as Docker and Kubernetes</li><li>Artifact repository tools such as Nexus and JFrog</li></ul><h4>Test Phase (Dev)</h4><p>After a successful build, the code is automatically deployed to a test environment where it undergoes more thorough testing outside of the development environment.</p><blockquote>The Test phase in the DevOps lifecycle is where the application is tested thoroughly to ensure that it meets the desired quality and functional requirements. The primary goal of this phase is to identify and fix any issues or bugs before the application is deployed to production environments.</blockquote><p>After the application is deployed to the testing environment, a series of tests are conducted to ensure the software meets the necessary requirements and works as expected.</p><p>These tests can be both automated and manual. In manual testing, the application is used by individuals in a way that simulates how a customer would use it (UAT). This allows for any issues or improvements to be identified before the software is deployed to production.</p><p>These tests ensure that the application is performing as expected, that all features are working as intended, and that the application is stable and secure.</p><p><strong>Required Tools:</strong></p><ul><li>Selenium</li><li>Load testing tools such as Apache JMeter or Gatling for performance testing.</li><li>Bug tracking and management tools such as JIRA or Trello to manage and track bugs and issues during testing.</li><li>Emulators or real devices for testing the application on different platforms and devices.</li></ul><h4>Release Phase (Ops)</h4><p>Once the testing has been successfully completed, the build is released as RC (Release Candidate) which is ready for being deployed in production.</p><p>In this phase mostly automation kicks in. Sometimes the organization may choose to automate the deployment of any build that passes the build phase. Additionally, developers can leverage feature flags to disable new features that are not yet ready for release to customers. This approach represents the pinnacle of DevOps and enables organizations to deploy numerous releases of their products daily, resulting in rapid time-to-market and continuous improvement of their products.</p><p><strong>Required Tools:</strong></p><p>Some tools that can be used in the Release phase include:</p><ul><li>Release Management tools such as JIRA or Trello to manage the release process and track any issues or bugs.</li><li>Monitoring tools such as Prometheus or Grafana to monitor the application’s performance and usage.</li></ul><h4>Deployment Phase (Ops)</h4><p>The Deploy phase is the phase where the application is actually deployed to the production environment, making it available to the end-users. This phase is closely tied to the Release phase, which is where the application is packaged and prepared for deployment.</p><p><strong>Example:</strong></p><p>Here’s an example of the Deploy phase for a ride-sharing app:</p><ol><li><strong>Build the Deployment Package:</strong> Before deploying the application, the development team will build a deployment package that contains all the necessary files and configurations for the application to run. This package may be a Docker container or a package created with tools like Ansible, Chef, or Puppet.</li><li><strong>Configure the Environment:</strong> The development team will ensure that the production environment is configured correctly to run the application. This may involve setting up load balancers, configuring network settings, and installing any necessary software.</li><li><strong>Deploy the Application:</strong> Once the deployment package is built and the environment is configured, the development team can deploy the application. They may use tools like Kubernetes, Docker Swarm, or AWS Elastic Beanstalk to manage the deployment.</li><li><strong>Rollout Strategy:</strong> To ensure that the deployment is successful, the development team will follow a rollout strategy. This may involve deploying the application to a small group of users initially and gradually increasing the user base as the application stability is confirmed.</li><li><strong>Monitoring and Feedback:</strong> After the deployment, the development team will monitor the application and gather feedback from end users to identify any issues or bugs that may arise. They may use monitoring tools such as Prometheus or Grafana to monitor the application’s performance and usage. They will also gather feedback from end-users through feedback channels such as in-app feedback, social media, or customer support.</li></ol><p>By using these tools and techniques, the development team can ensure that the ride-sharing app is deployed to end-users in a controlled and efficient manner. They can also ensure that any issues or bugs that may arise during the deployment are identified and addressed promptly, leading to a better user experience and improved adoption of the application.</p><p><strong>Required Tools:</strong></p><p>Some tools that can be used in the Deploy phase include:</p><ul><li>Configuration Management tools like Ansible, Chef, or Puppet to configure the environment.</li><li>Containerization tools like Docker to build and deploy the application.</li><li>Container orchestration tools like Kubernetes or Docker Swarm to manage the deployment.</li><li>Monitoring tools like Prometheus or Grafana to monitor the application’s performance and usage.</li></ul><h4>Operate Phase (Ops)</h4><p>In this stage, we know that the build is deployed and it is ready to be used. In this phase, the operation teams make sure that things run smoothly as expected. They also take care of server configuring and provisioning using tools like Chef.</p><h4>Monitor Phase (Ops)</h4><p>The Monitor phase of DevOps is the final stage in the DevOps cycle, but it is by no means the least important. In fact, monitoring is crucial for ensuring that the application runs smoothly in production and that any issues are identified and addressed as quickly as possible.</p><p>During this phase, the operations team is responsible for monitoring the application and the infrastructure that supports it. This includes monitoring the servers, databases, network, and any other components that the application relies on. By monitoring these components, the operations team can identify any potential issues before they impact the end users.</p><p>To achieve effective monitoring, it is essential to have the right tools in place.</p><p>These tools can include:</p><ol><li><strong>Monitoring Tools:</strong> There are a variety of monitoring tools available that can be used to monitor the application and infrastructure. These tools can range from essential tools like Nagios, Zabbix, and Prometheus to more advanced tools like Datadog, New Relic, and Dynatrace.</li><li><strong>Logging and Analytics Tools:</strong> Logging and analytics tools can be used to gather data on the application and infrastructure. This data can then be used to identify trends and patterns that can help to identify issues before they become critical. Examples of logging and analytics tools include ELK Stack, Splunk, and Graylog.</li><li><strong>Alerting and Notification Tools: </strong>Alerting and notification tools can be used to notify the operations team when issues arise. These tools can be configured to send notifications via email, SMS, or other messaging systems. Examples of alerting and notification tools include PagerDuty, OpsGenie, and VictorOps.</li><li><strong>Dashboard and Visualization Tools:</strong> Dashboard and visualization tools can be used to provide a real-time view of the application and infrastructure. These tools can be used to monitor key metrics such as CPU usage, memory usage, network traffic, and more. Examples of dashboard and visualization tools include Grafana, Kibana, and Tableau.</li></ol><p>During the monitoring phase, it is important to define and monitor key performance indicators (KPIs) relevant to the application and business goals. These KPIs can include metrics such as uptime, response time, error rate, and user engagement. By monitoring these KPIs, the operations team can identify any issues that may be impacting the end users and take action to resolve them.</p><h3>Continuity Matters!</h3><p>You probably heard about these words somewhere → “Continuous Integration / Continuous Delivery / Continuous Deployment / Continuous Feedback” etc. These concepts float around the DevOps pipeline. Therefore I thought you should be familiar with these concepts.</p><h4>Continuous Integration</h4><p>Continuous Integration (CI) is a software development practice where developers frequently merge their code changes into a central repository, and automated builds and tests are run to check for any integration errors.</p><p>This is how it works →</p><ol><li>Developers write and save their code changes to a shared code repository, like GitHub or Bitbucket.</li><li>A CI tool (such as Jenkins, Travis CI, or CircleCI) monitors the code repository for any changes. When it detects new code changes, it pulls the latest code from the repository.</li><li>The CI tool builds the code by compiling it into an executable program. This ensures that the code is free of syntax errors and other common mistakes.</li><li>The CI tool runs a suite of automated tests to verify that the code works as intended and does not introduce any new bugs or errors.</li><li>If any errors or bugs are found, the CI tool reports them back to the developers, who can then fix them and repeat the process until the code is working properly.</li><li>Once the code passes all tests, it is considered “clean” and can be deployed to production.</li></ol><p>In summary, CI helps to improve software quality and accelerate the development process by automating the process of building and testing code changes. By catching errors early on and ensuring that code is always in a stable, working state, CI makes it easier and faster to deliver high-quality software to end-users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M0k2WqdwMPlDtn-D.png" /><figcaption>Source: <a href="https://www.element61.be/en/competence/continuous-integration-deployment">https://www.element61.be/en/competence/continuous-integration-deployment</a></figcaption></figure><h4>Continuous Delivery</h4><p>Continuous Delivery (CD) is the practice of automating the entire software delivery process so that code changes can be delivered to production quickly and reliably. Consider it an extension of Continuous Integration (CI).</p><p>Here’s an example to help explain how it works:</p><p>Let’s say you’re part of a team working on an e-commerce website. You’ve made some code changes to the checkout process to make it more user-friendly. Now you want to deliver those changes to production so that customers can start using them.</p><p>Here’s how Continuous Delivery can help:</p><ol><li>You commit your code changes to the shared code repository.</li><li>The Continuous Integration (CI) system runs tests on your code changes to ensure that they’re stable and error-free.</li><li>If the tests pass, the CD system kicks in and automatically packages your code changes into a release candidate.</li><li>The CD system then deploys the release candidate to a staging environment, which is a production-like environment used for testing.</li><li>Automated tests are run on the staging environment to ensure that everything works as expected.</li><li>If the tests pass on the staging environment, the CD system deploys the release candidate to production.</li><li>The CD system then monitors the production environment for any errors or issues and rolls back the changes if any issues are detected.</li></ol><p>In this example, Continuous Delivery ensures that your code changes are delivered to production quickly and reliably, while also minimizing the risk of errors or issues. It also enables your team to release changes to production more frequently, allowing you to deliver value to your customers faster.</p><h4>Continuous Deployment</h4><p>Continuous Delivery (CD) and Continuous Deployment (CD) are both practices that are often used in conjunction with Continuous Integration (CI) to automate software delivery. While they are similar in some ways, there is a key difference between the two:</p><p>Continuous Delivery (CD) is the practice of automating the entire software delivery process so that code changes can be delivered to production quickly and reliably, but it still requires a human decision to be made to deploy the code changes to production.</p><p>In contrast, Continuous Deployment (CD) is the practice of automatically deploying code changes to production as soon as they pass all tests in the CD pipeline. In other words, the CD takes automation one step further by eliminating the need for a human decision to deploy the code changes.</p><p>To illustrate the difference, let’s take the example of an e-commerce website where a team has made some code changes to the checkout process. With Continuous Delivery, the CD system packages and deploys the code changes to a staging environment where automated tests are run. If the tests pass, a human makes a decision to deploy the changes to production. With Continuous Deployment, however, the CD system automatically deploys the changes to production without the need for a human decision.</p><p>In summary, the key difference between Continuous Delivery and Continuous Deployment is that Continuous Delivery still requires a human decision to be made to deploy the code changes to production, whereas Continuous Deployment automatically deploys the changes without human intervention once they pass all tests in the pipeline.</p><h4>Continuous Feedback</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pmcFn5DL79SK1ugAqkTeYw.png" /><figcaption>Source: <a href="https://morioh.com/p/289a89e21fdd">https://morioh.com/p/289a89e21fdd</a></figcaption></figure><p>Continuous Feedback is a key component of the DevOps process that involves continuously gathering and analyzing feedback from users and systems to inform ongoing software development efforts.</p><p>Here’s an example to help explain how it works:</p><p>Imagine that you’re part of a team working on a mobile app that helps people track their fitness goals. Here’s how Continuous Feedback can help improve the app:</p><ol><li>The team releases a new version of the app that includes a feature to track water intake.</li><li>The app is released to a subset of users, who are asked to provide feedback on the new feature.</li><li>The team uses analytics tools to track how users are interacting with the app, including how often they use the new water-tracking feature.</li><li>Based on user feedback and analytics data, the team identifies areas for improvement and makes changes to the app, such as adding more intuitive controls for the water tracking feature.</li><li>The team releases a new version of the app that includes the changes, and the process starts again with gathering feedback on the updated version.</li></ol><p>By continually gathering and analyzing feedback from users and systems, the team is able to make data-driven decisions about how to improve the app. This process helps ensure that the app meets the needs of its users and stays relevant over time.</p><p>Continuous Feedback is not just limited to user feedback. It can also involve gathering feedback from systems, such as monitoring tools that track the performance and stability of the app. This feedback can help the team identify and address issues before they impact users.</p><p>Overall, Continuous Feedback is a crucial part of the DevOps process that helps teams deliver high-quality software that meets the needs of its users. It enables teams to continually learn and improve based on feedback from users and systems, leading to better software and happier users.</p><h3>Footnote</h3><p>I am grateful for your interest in perusing this introductory blog post and trust that it has proven to be both captivating and enlightening. It gives me great pleasure to have been able to provide you with valuable educational content.</p><p>It is essential to note that this blog post serves as a precursor to an upcoming series of blogs that explore more intricate topics such as Dockers, Jenkins, and Travis CI. These topics hold a central position in the realm of DevOps and possess the potential to make a significant impact on software development and delivery processes.</p><p>I encourage you to follow me closely so that you may stay informed of any new updates or releases in the series. My unwavering commitment to presenting content that is informative and accessible ensures that this series will appeal to both beginners and experienced professionals alike.</p><p>Let’s get acquainted with each other on <a href="https://www.linkedin.com/in/akash-dugam/">LinkedIn</a>.</p><p>Tadaaa!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27617e9be3b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Top 5 Pandas Optimization Methods You Should Know!]]></title>
            <link>https://dugamakash.medium.com/the-top-5-pandas-optimization-methods-you-should-know-1f4acdaa120a?source=rss-19a974a0393------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f4acdaa120a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[pandas-tutorial]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Akash Dugam]]></dc:creator>
            <pubDate>Sun, 11 Sep 2022 08:01:51 GMT</pubDate>
            <atom:updated>2022-09-11T14:17:06.648Z</atom:updated>
            <content:encoded><![CDATA[<p>Things get messy if we don’t employ memory optimization techniques when dealing with high-dimensional data. You don&#39;t want the pop-up sighting the ‘Memory Error’ on your screen, do you? Therefore we need to be careful about how we utilize memory.</p><p>I have used the techniques below to optimize memory use and speed up the computations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*akHuLrDUvuMsXmTIY-BPpQ.png" /></figure><p><strong>But, wait. How do we find out the memory uses in the first place? </strong>This is very simpler than you think. We can use <strong>info()</strong> or <strong>memory_usage()</strong>. The main difference between the two is info() doesn’t show a detailed report on memory uses whereas the memory_uses() method showcases a detailed view of the memory usage.</p><p>Now let’s talk about the methods that will help in optimizing memory usage.</p><ol><li>Use of inplace assignment</li><li>Read what you require</li><li>Change the data type of the column</li><li>Parallelize your operation</li><li>Read in chunks!</li></ol><p>Let’s talk about each of these techniques in brief.</p><h3>Use of inplace assignment</h3><p>Most of the time we tend to use standard assignment in data manipulation. We manipulate the data and save that manipulation in a separate copy of the dataframe which is exactly what standard assignment means. Take a look at the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pinMPwjS7C57NjM-p6zUKA.png" /></figure><p>Due to the use of the standard assignment technique, two distinct dataframe lies in the same environment causing an increase in the memory. Intuitively, the DF (original dataframe) is no use when we have decided to go with DF2 (manipulated dataframe). This very problem gets solved when you decide to use the ‘inplace assignment’ technique than a standard one.</p><p>In the inplace assignment technique, multiple copies of the dataframe won’t be created avoiding the increase in memory with a useless dataframe.</p><h3>Read what you require</h3><p>The name itself means, accepting the columns that you required and abandoning the least interesting columns. Sometimes, you might be in a situation where you have high-dimensional data but your interest lies in certain (let&#39;s say 2 or 3) columns. In such cases, reading all irrelevant columns cause heavy memory use than reading the interesting columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WRvNw49khHSvNo2OzYpHTQ.png" /></figure><p>Let me elaborate with one example, let’s say you have medical data of many patients. Your job is to calculate the BMI. Your dataset is high dimensional (Think of 3M rows and 300 columns). But you required only the information of the patient&#39;s name, height, and weight. That’s it. Therefore instead of reading the entire data, it’s advisable to read what you required.</p><h3>Change the data type of the column</h3><p>We all know how pandas work in assigning data types. By default, pandas assign the highest memory datatype to columns. But the question is do we required to have the highest memory type every time? Let’s find out.</p><h4><strong>Inspecting numerical columns:</strong></h4><p>Let me be honest with you, you don’t require to have int64 or float64 datatype every time. Refer to the below table to understand why I am saying this to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*I3p8xGFDNL84Gm4JAWbssA.png" /><figcaption>This range is applicable for numerical columns</figcaption></figure><p>As we discussed already when you have an <strong>int or float column</strong> by default the pandas will assign an int64 or float64 data type. But we need to inspect the column and find the <strong>minimum </strong>and <strong>maximum </strong>value of the integer column to decide the <strong>range</strong>. Once we have the range we can identify and specify the correct data type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3DHe7LrBYB1s37KDHZugtA.png" /><figcaption>This table shows the % of reduction of the memory after applying the optimized datatype.</figcaption></figure><h4><strong>Inspecting Object columns:</strong></h4><p>Apart from numeric (int or float) you will see another most important datatype known as ‘Object’. This data type represents the categorical data which has some unique values repeated over and over again. We can convert ‘object’ datatype to ‘category’ with the help of astype method.</p><p>I generally use the below logic to optimize the categorical column.</p><pre>If (unique_value (of Column) / Total Value (of column) &lt; 0.5):<br>            data[col] = data[col].astype(&#39;category&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwl6U6uDc6gAo_VbQC0Ixw.png" /></figure><p>Look at the above table, the name column has more unique values than Cabin or Embarked, therefore as per our criteria if the ratio between unique values and total values is less than 50% then it will be optimized. In the above case, the name column does not meet the criteria (which is obvious!) and hence optimization doesn’t happen.</p><h3>Parallelize your operations</h3><p>Have you ever thought of parallelizing the program execution? Your laptop or system has multiple cores. Let’s not keep them idle. Let’s put them to work by using the multicore functionality with the help of pandarallel.</p><blockquote><strong>Note :-</strong> Pandarallel is alternative to Dask</blockquote><p>First thing first, you need to install the library called — Pandarallel.</p><pre>pip install pandarallel</pre><p>Let me show you the difference in execution → With and Without Parallelization!</p><blockquote>This is without parallelization:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/0*PRCkW-HSrvxlqzCj" /></figure><blockquote>This is with parallelization:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*HyYMZH-xBU25I1Bj" /></figure><blockquote><strong>Note:-</strong> By modifying only one line of code, it offers a quick solution to parallelize your pandas operations over all of your CPUs. Additionally, progress bars are shown.</blockquote><p>Let me show you how what changes you need to make to utilize the capabilities of the Pandarallel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3flcWITocF83Ck2xiCYJxg.png" /><figcaption><a href="https://github.com/nalepae/pandarallel">https://github.com/nalepae/pandarallel</a></figcaption></figure><h3>Read in chunks!</h3><p>There are times when you face high-dimensional data. All other techniques mentioned above will be useless if you cannot read the data in the first place in the memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8FLlY_z12adFK_c8he1aA.gif" /></figure><p>One interesting thing about Pandas is serialization. Pandas read data sequentially row-by-row at a time. We can leverage this and command pandas to read data by chunk size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fW_PRb3-Ic9swEyOD2p_FA.gif" /></figure><p>We can easily achieve this with the following python code -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VsSGPrh5ikvSrQ7H2pJ6Hw.png" /></figure><blockquote>Note that, every chunk is dataframe. You can add type(chunk_data) to check the type of the dataframe.</blockquote><h3>Footnote</h3><p>These are the ways I generally employ in projects to optimize memory. This has a very much impact on the process when you are dealing with high-dimensional data.</p><p>Above mentioned subtle ways to optimize memory are not exhaustive in nature. There could be many ways to enhance memory optimization in pandas. I will be adding those in future updates.</p><p>Stay updated with all the content I post -</p><ul><li>Follow me on → <a href="https://dugamakash.medium.com/"><strong>Medium</strong></a></li><li>Follow me on → <a href="https://www.linkedin.com/in/akash-dugam/"><strong>Linkedin</strong></a></li></ul><p>More content is in the draft and will be ready to post. Until then, stay tuned. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f4acdaa120a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Collinearity of Features]]></title>
            <link>https://dugamakash.medium.com/the-collinearity-of-features-9bc34a3e3efd?source=rss-19a974a0393------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bc34a3e3efd</guid>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Akash Dugam]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 15:17:21 GMT</pubDate>
            <atom:updated>2022-08-29T15:17:21.591Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s wise to understand the stuff related to ‘collinearity’ or ‘multicollinearity’ to excel in the field of data science. Though both of these concepts explain the same thing with a subtle difference. (Don’t worry, I will be explaining the difference in naïve language)</p><p>Let’s check the agenda for this blog post.</p><ol><li>Collinearity Vs Multicollinearity</li><li>How does the weight vector of features get corrupted in the presence of collinearity?</li><li>Why Multicollinearity could be dangerous to your regression model?</li><li>Ways to detect multicollinearity among the features?</li><li>How to remove Multicollinearity?</li></ol><p>Let’s start with understanding the difference between collinearity and multicollinearity.</p><h3><strong>Collinearity Vs Multicollinearity</strong></h3><p>These are the two most overlapping concepts from statistics. Collinearity is when there is a linear relationship or association between <strong>two </strong>variables or features. The term multicollinearity is formed for the linear association between <strong>two or more</strong> variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nx6eFXNlI_NcTRqN_1q1bg.png" /></figure><h3>How does the weight vector of features get corruptted in the presence of collinearity?</h3><p>Let’s say you have a 3 features F = {F1, F2, F3} with corresponding weights are W* = {1, 2, 3}.</p><p>Let’s say you have a new query point (row vector) Xq = {Xq1, Xq2, Xq3} then the weights of the features will align it this way -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*BSQkY_ESjOyn8INhiv2WOg.png" /></figure><p>Let’s rewrite the above sentence and label it as Equation (1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*LwiDiIOTNWfEmbh-pqY61g.png" /></figure><p>Now as I have explained above, there must be some linear association between features or variables before we term them as multicollinear. To demonstrate this, let’s say,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*q6GGd0rYb1qfX6_4JL0Nvg.png" /></figure><p>Now let’s plug this value into our equation (1) and solve the equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*WrNEkNcNutpZiI9eOJPQWg.png" /></figure><p>Since we have two equations ready, let’s compare weight vectors corresponding to these two equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*prEEyief6fjwlxL_x7kBAQ.png" /></figure><p><strong>Note:-</strong></p><p>Due to the presence of collinearity, weight vectors or weight associated with each feature could change. Many algorithms use the weight vector to do feature selection internally. Take the example of Logistic Regression, it uses |Wi| for feature importance. Therefore we must check if there is multicollinearity exists among the features.</p><h3>Why Multicollinearity could be dangerous to your regression model?</h3><p>Until now, I have explained how problematic it could be to model-based feature selection. Now let’s discuss the potential problems that may arise when we build regression models by ignoring multicollinearity.</p><p>Having multicollinearity in the regression model can change the interpretation of the regression coefficient. The regression coefficient is the value that represents the relationship when a meaningful change in the dependent variable for each unit change in the independent variable by keeping all other independent variables constant. That’s the problem. When you have independent variables correlated then it’s difficult to fulfill the criteria of “keeping other independent variables constant”. As a result, if we change 1 unit in the independent variable there might be an ‘X’ unit change in other independent variables due to collinearity between features. This makes the model difficult to understand the true relationship between dependent and independent variables.</p><h3>Ways to detect multicollinearity among the features?</h3><p>There are multiple methods to capture the multicollinearity among the features. In this blog post, let’s try to cover these methods!</p><ol><li>Correlation Matrix</li><li>VIF</li></ol><p>Let’s explore each of these above.</p><h4><strong>Correlation Matrix</strong></h4><p>You can be a Sherlock Holmes and plot the correlation matrix where you can spot multicollinearity very easily. This is the easiest way that I could think of for now.</p><p>Let me take you to a practical example. Here is the data that I am using to demonstrate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*47Bltf98B5ggk6Lcn7ffrQ.png" /></figure><p>The objective of the problem is to predict the sales price based on the mentioned variables. I know, I know, you don’t require much information on the objective of the dataset as we aren’t going to accomplish that in this blog. :)</p><p>Once we have the dataset ready, all you need to do is to load and exclude the target variable and run bunch of lines of Python code to print the correlation matrix like below. (Don’t worry, the code will be shared with you by the end of this blog post)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*VeFU8CxOBwOQSR1B6c9_fg.png" /></figure><p>The couple of observations that I would like to add,</p><ol><li>The variable ‘Interior’ is highly correlated with # of Beds, the # Of Rooms, and # of Bath.</li><li>There is a high correlation between # of Rooms and # of Beds which is oblivious!</li><li>There is also a high correlation between ‘Condo Fee’ and ‘Tax’</li></ol><p>As we have already seen the problem pertains to the high correlation and how it changes the weight vector. Hence building a model with these variables (without treating the problem) wouldn’t be advisable.</p><h4><strong>Variance Inflation Factor (</strong>VIF)</h4><p>It’s better to have one metric to understand the multicollinearity than the correlation interpretation. There is one popular metric known as Variance Inflation Factor or shortly known as VIF which does the same thing. But what do you mean by VIF?</p><blockquote>It’s ratio of the variance of the model to the variance of the model which include only that one independent variable.</blockquote><p>In other words, we can say that the VIF is the measure of the strength of correlation between independent variables. It is predicted by taking a variable and regressing it with every other variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*N-AXuDrf-j7iKoZeJb9IDQ.png" /><figcaption><strong>VIF Formula</strong></figcaption></figure><p>Let’s calculate the VIF for our dataset and showcase it here in the form of a table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*psgA3CAKuhGr1Bkp-IyAuw.png" /></figure><p>Look at the table carefully, the <strong># of Beds</strong> and <strong># of Rooms</strong> have a high VIF score which indicates that there is strong collinearity between these features. In real life, this is so oblivious and the above table does make sense. But what exactly those scores are?</p><p>The score of each independent variable represents how well is the variable explained by other independent variables. In order to accomplish this, each independent variable acted as the dependent variable. The R2 (R-squared) score will be generated. Higher the R2 score more that variable correlated with other variables. This is what VIF returns as a score (See the table above)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*hcnKoLsIJ6JZm3_Db1bRyg.png" /><figcaption><strong>VIF Interpretation</strong></figcaption></figure><p>The main problem that I found with VIF is that there is no upper limit. It starts with 1 and goes towards infinity. The above table is a mere thumb rule as there are no hard and set rules for their interpretation. For example, some companies accept the VIF values till 7 and some want to have VIF below 4.</p><h3>How to Fix Multicollinearity?</h3><p>Since are multiple ways to detect multicollinearity, Likewise, there are multiple ways to fix it. Let me make life easier by jotting down some of these methods to fix the multicollinearity issue.</p><ul><li>Dropping the Correlated Variables</li><li>Combining the Variables</li><li>Life savior → PCA</li></ul><p>Let’s start exploring each of the above techniques to understand more about it.</p><h4>Dropping the Correlated Variables</h4><p>This would be the easiest method to cut down the multicollinearity of the data. When there is high multicollinearity between two independent variables would mean that each variable is capable of explaining the other variables. Therefore we can keep one and remove other variables from the dataset without affecting much variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*aw7IXLQTRe09Vok7OwL6Qg.png" /><figcaption>VIF (Before removing variables)</figcaption></figure><p>If you look at the above table, the variables like ‘Interior (Sq Ft) and # of Rooms are well explained by the other variables like # of Bed and # of Bath, etc. Therefore we can remove those variables from the dataset and check whether it brings down the multicollinearity or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xFs8R-fYIMXpy9BplcDPfQ.png" /></figure><p>One thing to remember is that dropping variables and checking VIF is an iterative process. Even though we have the information about two variables that need to be removed, we have not immediately removed them. Here, we have removed the ‘Interior(Sq Ft)’ first as it has the highest VIF value. As soon as we removed it and again checked for VIF values, the VIF values of other variables changed. Therefore we have to remove variables in an iterative fashion.</p><h4>Combining the Variables</h4><p>Yes, we can combine multiple variables together and create one variable which has capabilities to represent the other variables. In more technical terms, the representative variable should capture the variance of other variables.</p><p>In our case, we can combine ‘# of Beds’ and ‘# of Bath’ and form a new variable as ‘Total Rooms (Space)’ which can serve as a representative of both of these variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*WxYzxREi5tVGaY4VPpMjJA.png" /><figcaption>Total Rooms (Space)</figcaption></figure><p>Let’s validate our assumptions with the VIF table. (We will be calling our VIF function on the modified data)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P-JKSIFyxztz8paHVLe3_g.png" /></figure><p>These two methods are used most in the industry to remove the effect of multicollinearity. There is one other method that we have yet to discuss is on, how PCA would be a life savior when you have a multicollinearity issue. …</p><h4>Life savior → PCA</h4><p>Principal Component Analysis (Short, PCA) is a dimensional reduction technique used to reduce the dimensions of the data. In the dimensionality reduction process, we reduce the dimensions of data with the help of % of variance required to build sensible ML models.</p><p>Most of us get confused easily about PCA being a feature selection technique. But in reality, it’s not. It rather features extraction techniques where features new features get extracted in the form of the components which capture most of the variance in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*bzlJYr8WoX64pP3RyyLTaw.png" /></figure><p>The above table shows the number of principal components and variance captured by each of these. You can completely neglect the last 2 and be happy with 94% of variance or you can neglect the last 1 and can have 98% of captured variance by model. In both cases, you are reducing the dimensions. But here, we are not for ‘dimensionality reduction, we are here for ‘multicollinearity reduction’. Thus, for now, let’s keep all the components as it is and run the VIF model to check the VIF score for each of these components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LChJU2LUiPfw5yTJnGpUYA.png" /></figure><p>I don’t recommend using this method when you want to build a model with interpretability. We lose the identity of the variables as soon as we implement PCA. You must forget the interpretability when you use the PCA.</p><h3>Final words</h3><p>Having multicollinearity in the data can corrupt the model-building process. The multicollinearity can be problematic to your regression model as well as your classification models. A simple technique like a correlation matrix can be used for the identification of multicollinearity and as simple as dropping or combining the variables can be employed to fix the issue. Selection of the right variables (domain-specific) can make life easier, therefore special attention needs to be given while doing feature selection. We also talked about techniques like PCA to reduce multicollinearity but the red flag is for the interpretability. The moment we use PCA we lose the identity of the variables. As I always say, there are no right or wrong techniques, there are only techniques that can be used based on the situation.</p><h3>Footnote</h3><p>I have written numerous articles on Quora &amp; Medium. There are articles lying in draft waiting for me to finish and publish. Follow me on <a href="https://dugamakash.medium.com/">Medium</a> as well as on <a href="https://www.linkedin.com/in/akash-dugam/">Linkedin </a>to stay in touch with me. See you around. :)</p><blockquote><strong>Credits where it’s due -</strong></blockquote><p><a href="https://www.instagram.com/p/ChpUW7cKjKS/">https://www.instagram.com/p/ChpUW7cKjKS/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bc34a3e3efd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Certified Cloud Practitioner Study Guide!]]></title>
            <link>https://dugamakash.medium.com/aws-certified-cloud-practitioner-study-guide-1f9e427ed392?source=rss-19a974a0393------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f9e427ed392</guid>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-ccp]]></category>
            <dc:creator><![CDATA[Akash Dugam]]></dc:creator>
            <pubDate>Wed, 09 Mar 2022 16:21:11 GMT</pubDate>
            <atom:updated>2022-03-09T17:38:05.953Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Disclaimers:</em></strong></p><blockquote>I have created this blog to consolidate best material available on internet to one place. I have given the credits where it’s due in the credit section at the end of this blog posts. Please do check that out.</blockquote><h3>The Cloud: Foundation</h3><p>It is very important to understand the basics of cloud computing, why do we even use it, etc.? There are many companies that provide cloud services to end-users, businesses, etc to carry out the daily essential needs.</p><p>Here is a list of the top 10 cloud service providers:</p><ul><li>Amazon Web Services (AWS)</li><li>Microsoft Azure.</li><li>Google Cloud.</li><li>Alibaba Cloud.</li><li>IBM Cloud.</li><li>Oracle.</li><li>Salesforce.</li><li>SAP.</li></ul><p>Now let’s understand, what exactly cloud computing is -</p><h4>What Is Cloud Computing?</h4><p>If you ask me the definition of cloud computing, I would simply term this concept as → It is a delivery of computing services through the internet. Now you must be thinking about what could be those computing services that are being offered by cloud computing providers?</p><ul><li>Servers</li><li>Cloud Storage</li><li>Networking</li><li>Databases</li><li>Softwares</li></ul><h4>But, why cloud computing is the requirement?</h4><p>To understand this, we need to go back and look at the traditional IT setup which was the last thing for many users or businesses before adopting the cloud computing technology.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QFVFdVBq17wNRpl1CTqChQ.png" /></figure><p>This setup is mostly known as start-up setup where most of the big giants of today had started their office journey through Home or Garage. Later, moved to office space and subsequently maintained the required data centers. But if you look at the problems of maintaining data centers, for a moment, we might feel why should we maintain the data center in the first place?</p><ul><li>Rent → For required space</li><li>Pay → For power supply, cooling equipment, maintenance, etc.</li><li>Limited in Scaling</li><li>Hardware / Software Limitation</li><li>Hire a 24/7 team to monitor the infrastructure</li><li>Lack of disaster management etc.</li></ul><p>In the traditional setup, you have to look after everything that is related to data centers. This is risky thing to do. This is where cloud services comes into the picture. They will help you to move your data service into the virtual location than the physical location. Therefore problems pertaining to physical presence of your data centers will go automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*PItlCFUzr8DEgmmT913XGg.png" /></figure><h4>Benefits of Cloud Computing?</h4><p>There are many benefits of cloud computing. Few of them have been listed here.</p><p><strong>Pay as you go Pricing Model:</strong></p><p>It is possible to pay for the services that you use only. Oftentimes in a traditional setup, we buy expensive equipment thinking that it will suffice our requirements. In business, requirements are not always fixed but they are variable in nature. To avoid this pitfall, with cloud computing services, we pay for what we use.</p><p><strong>No Upfront Cost:</strong></p><p>There are no upfront costs like setting up the data centers and servers or buying up some hardware etc.</p><p><strong>Benefit from massive economies of scale:</strong></p><p>Usage from hundreds of thousands of customers aggregated in the cloud. Therefore we are sharing the costs with other customers and hence it will be economical and cheaper than handling the data centers on your own.</p><p><strong>Unlimited Storage &amp; Processing Power:</strong></p><p>As per requirements businesses can scale up or scale down their storage and processing powers.</p><p><strong>Speed and Agility:</strong></p><p>Launch resources within a few clicks in minutes instead of days or weeks on data centers.</p><p><strong>No maintenance costs:</strong></p><p>Since the central authority (Businesses that are providing cloud services) are looking after the maintenance and hence customers need not spend their time, energy and money looking after the maintenance.</p><p><strong>High performance and lower latency:</strong></p><p>With cloud computing services, we can deploy services around multiple regions in minutes with lower latency and high performance.</p><p>After understanding the application, we can define the cloud computing services as -</p><blockquote>Cloud computing is the on-demand delivery of compute power, database storage, applications, and other IT resources</blockquote><h4>Types of Cloud Computing:</h4><p>After understanding the basics of cloud computing, it’s necessary for users to know various types of cloud computing before adopting it for personal use or business use.</p><p><strong>Public Cloud:</strong></p><ul><li>In the public cloud, the cloud resources are managed by cloud service providers (CSP) and delivered to end-users via the internet.</li><li>This type of cloud is created from the IT infrastructure and it is not owned by end-users.</li><li>Some of the largest public cloud providers include Alibaba Cloud, Amazon Web Services (AWS), Google Cloud, IBM Cloud, and Microsoft Azure.</li><li>Public clouds are cheaper than Private cloud services as it comes under shared cloud services.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*EIuavYUAgad79sX4.png" /></figure><p><strong>Private Cloud:</strong></p><ul><li>These cloud services are used by a single organization and not exposed to the public.</li><li>Private cloud is also known as Internal Cloud or Corporate Cloud. It is used by an organization that wants to control their data centers in the cloud.</li><li>Most of the time private cloud is used when security or data protection is most important.</li><li>Private cloud provides a high level of security and privacy to the users.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*5eda5fqJe7O3oKGw.png" /></figure><p><strong>Hybrid Cloud:</strong></p><p><em>Hybrid Cloud = Public Cloud + Private Cloud</em></p><ul><li>This cloud service is semi secured. Because it offers two types of services. Services that are running on public cloud can be accessed by anyone while the services that are running on the private clouds can only be accessed by the organization.</li><li>Hybrid cloud offers flexible resources because of the public cloud and secure resources because of the private cloud.</li><li>Managing a hybrid cloud is complex because it is difficult to manage more than one type of deployment model.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*0YwFqxEZOUNPTei7.png" /></figure><p><strong>Community Cloud:</strong></p><ul><li>Community cloud allows systems and services to be accessible by a group of several organizations to share the information between the organization and a specific community</li><li>It is owned, managed, and operated by one or more organizations in the community, a third party, or a combination of them.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*jz6FpC-7Si5VagxY.png" /></figure><h4>Cloud Platform Models:</h4><p>There are 3 types of cloud computing service models -</p><ol><li>Infrastructure as a Service (Iaas)</li><li>Platform as a Service (Paas)</li><li>Software as a Service (SaaS)</li></ol><p>Let’s look at them one by one.</p><p><strong>Infrastructure as a Service (IaaS):</strong></p><ul><li>IaaS is also known as ‘Hardware as a Service (HaaS)’</li><li>Actually, IaaS means a cloud service provider manages infrastructure for you. Like the actual servers, network, virtualization, and data storage.</li><li>The main advantage of the IaaS is it won’t let users or organizations buy expensive servers or other physical equipment but provide them as a service.</li><li>The user has access through an API or dashboard, and essentially rents the infrastructure.</li><li>The user manages things like the operating system, apps, and middleware while the provider takes care of any hardware, networking, hard drives, data storage, and servers.</li><li><strong>Example:</strong> DigitalOcean, Linode, Amazon Web Services (AWS), Microsoft Azure, Google Compute Engine (GCE), Rackspace, and Cisco Metacloud</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*8FwmIoa4p7VHOa2E" /></figure><p><strong>Platform as a Service (Paas):</strong></p><ul><li>In PaaS, hardware, as well as the applications/software platform, is provided and managed by the outside cloud service provider, but the user handles the apps running on top of the platform and the data the app relies on.</li><li>Primarily it is created for the programmer to develop, test, run, and manage the applications.</li><li><strong>Example:</strong> AWS Elastic Beanstalk, Windows Azure, Heroku, Force.com, Google App Engine, Apache Stratos, Magento Commerce Cloud, and OpenShift.</li></ul><p><strong>Software as a Service (SaaS):</strong></p><ul><li>SaaS is also known as “On-Demand Software”.</li><li>It is a service that delivers a software application — which the cloud service provider manages — to its users.</li><li>Typically, SaaS apps are web applications or mobile apps that users can access via a web browser.</li><li>Software updates, bug fixes, and other general software maintenance are taken care of for the user.</li><li>Think, it is a completed product that is run and managed by the service provider.</li><li>SaaS also eliminates the need to have an app installed locally on each individual user’s computer, allowing greater methods of a group or team access to the software.</li><li><strong>Example:</strong> BigCommerce, Google Apps, Salesforce, Dropbox, ZenDesk, Cisco WebEx, ZenDesk, Slack, and GoToMeeting.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0i7AdGsTIbbOozEa3BKNA.png" /><figcaption><a href="https://www.javatpoint.com/cloud-service-models">https://www.javatpoint.com/cloud-service-models</a></figcaption></figure><h4>Server Virtualization:</h4><p>The secret sauce that lets cloud providers give their customers on-demand compute resources in such a wide range of configurations is virtualization. When you request a virtual machine (VM) with a particular processor speed, memory capacity, and storage size, AWS doesn’t send some poor engineer running through the halls of its data center looking for an available machine with exactly that profile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*3NBWbQo2sk_Ncxf2hZuoag.png" /></figure><p>Rather, as you can see illustrated in Figure 1.1, AWS carves the necessary resources from larger existing devices.</p><h4>Serverless Workloads:</h4><ul><li>Build and run applications without thinking about servers</li><li>Now don’t be fooled by the name. You can’t run a compute function without a computer environment (a “server”) somewhere that’ll host it. What “serverless” does allow is for individual developers to run their code for seconds or minutes at a time on someone else’s cloud servers.</li><li>Serverless technologies feature automatic scaling, built-in high availability, and a pay-for-use billing model to increase agility and optimize costs.</li><li>These technologies also eliminate infrastructure management tasks like capacity provisioning and patching, so you can focus on writing code that serves your customers.</li><li>The serverless model — as provided by services like AWS Lambda — makes it possible to design code that reacts to external events.</li></ul><h4>Scalability and Elasticity: Two Key Principles</h4><p>The world’s largest public cloud providers can accomplish a great deal by combining the wonders of server virtualization with the power that comes from owning vast data centers filled with racks upon racks of hardware resources. Elasticity and scalability are the two key principles through which a lot of this happens, and understanding exactly what they mean can help you optimize your design choices so you’ll get the most bang for your cloud buck.</p><p><strong>Scalability:</strong></p><ul><li>A scalable service will automatically grow in capacity to seamlessly meet any changes in demand.</li><li>A well-designed cloud-based operation will constantly monitor the health of its application stack and respond whenever preset performance metrics might soon go unmet.</li><li>The response might include automatically launching new server instances to add extra computing power to your existing cluster.</li><li>Note that, a large cloud provider like AWS will, for all practical purposes, have endless available capacity so the only practical limit to the maximum size of your application is your organization’s budget</li></ul><blockquote><em>Just how big is AWS? Well, if it can handle the capacity stresses required to keep millions of Netflix customers happy — and if you’ve ever watched a movie on the AWS-hosted Netflix, then you know it can — then AWS will surely be able to keep up with whatever trouble your applications send its way.</em></blockquote><p><strong>Elasticity:</strong></p><p>You can stretch an elastic band far beyond its resting state. But part of what makes it truly elastic is the fact that, when you let go of it, it immediately returns to its original size.</p><p>The reason the word elastic is used in the names of so many AWS services (Elastic Compute Cloud, Elastic Load Balancing, Elastic Beanstalk, and so on) is that those services are built to be easily and automatically resized.</p><p>Generally, you set the maximum and minimum performance levels you want for your application, and the AWS service(s) you’re using will automatically add or remove resources to meet changing user demands.</p><p>For an instance, a scalable eCommerce website could be configured to function using just a single server during low-demand periods, but any number of additional servers could be automatically brought online as demand spikes. When demand drops back down, unused servers will be shut down automatically. This is what the elasticity means.</p><h4>AWS Cloud History</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3lNq-Zt0mdZ_2J_Ljfjsw.png" /></figure><h4>AWS Cloud Number Facts</h4><ul><li>In 2019, AWS had $35.02 billion in annual revenue</li><li>AWS accounts for 47% of the market in 2019 (Microsoft is 2nd with 22%)</li><li>Pioneer and Leader of the AWS Cloud Market for the 9th consecutive year</li><li>Over 1,000,000 active users</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*W-oPZo4Uj7Hkhqk6-ZmBXQ.png" /></figure><h4>AWS Global Infrastructure</h4><p>The AWS Global Cloud Infrastructure is the most secure, extensive, and reliable cloud platform, offering over 200 fully-featured services from data centers globally.</p><p>Whether you need to deploy your application workloads across the globe in a single click, or you want to build and deploy specific applications closer to your end-users with single-digit millisecond latency, AWS provides you the cloud infrastructure where and when you need it.</p><p>The AWS Cloud spans <strong>84 Availability Zones (AZ)</strong> within <strong>26 geographic regions</strong> around the world, with announced plans for 24 more Availability Zones and 8 more AWS Regions in Australia, Canada, India, Israel, New Zealand, Spain, Switzerland, and United Arab Emirates (UAE).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YDjAuXfHH8dMiRKuDu5bw.png" /><figcaption><a href="https://aws.amazon.com/about-aws/global-infrastructure/">https://aws.amazon.com/about-aws/global-infrastructure/</a></figcaption></figure><p>The AWS infrastructure consists of following things →</p><ul><li>Region</li><li>Availability Zones (AZ)</li><li>Data Centers</li><li>Edge Locations / Points of Presence</li></ul><p>Let’s look at them one-by-one.</p><p><strong>Region</strong>:</p><ul><li>AWS has the concept of a Region, which is a physical location around the world where they cluster multiple data centers.</li><li>We call each group of logical data centers an Availability Zone. (AZ)</li><li>It is a<strong> geographically distinct</strong> location with <strong>multiple AZs</strong> (data centers)</li><li>Every region is <strong>physically isolated </strong>from and independent of every other region in terms of location, power, and water supply</li><li>Each region has <strong>at least 2</strong> AZs</li><li>Not all services are available in all regions</li><li>AWS maintains multiple geographic Regions, including Regions in North America, South America, Europe, China, Asia Pacific, South Africa, and the Middle East.</li></ul><p><strong>How to choose an AWS Region?</strong></p><p>If you wish to launch a new application, where you should do it? There are multiple factors associated with it. Let’s look at them</p><ul><li>Compliance with data governance: Most of the country with their data never leaves a region without govt. explicit permission. Therefore if you are doing business in India, your data center must be located in India.</li><li>Proximity matters: Proximity matters as it reduces the latency. If you have business in India and you are targeting Indian customers then what’s the point of choosing North America as your region?</li><li>Localization: New services and new features aren’t available in every Region</li><li>Pricing: Pricing varies from region to region and is transparent in the <strong>Service Pricing Page</strong></li></ul><p><strong>Availability Zones (AZ):</strong></p><ul><li>An Availability Zone (AZ) is one or more discrete data centers with redundant power, networking, and connectivity in an AWS Region</li><li>Each region has many AZs ( At least 2, Usually 3, Max 6)</li><li>They’re separate from each other, so that they’re isolated from disasters</li><li>They’re connected with high bandwidth, ultra-low latency networking</li><li>AZs are physically separated by a meaningful distance, many kilometers, from any other AZ, although all are within 100 km (60 miles) of each other.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*RBfL_dOtGk5_HoEDJUg9-A.png" /></figure><p><strong>Points of Presence (Edge Locations):</strong></p><ul><li>It is used for getting data out or uploading data fast to AWS</li><li>EL is a data center owned by a trusted partner of AWS and has a <strong>direct connection </strong>to the AWS network.</li><li>These locations serve requests for <strong>CloudFront </strong>and <strong>Route53. </strong>Requests going to either of these services will be routed to the nearest EL automatically.</li><li><strong>S3 Transfer Acceleratio</strong>n traffic and <strong>API Gateway</strong> endpoint traffic also use the AWS Edge Network</li><li>Content is delivered to end-users with lower latency</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*L76hQSzILMMy1lFKg7pcgQ.png" /></figure><h4>Tour of the AWS Console</h4><p>AWS has Global Services:</p><ul><li>Identity and Access Management (IAM)</li><li>Route 53 (DNS service)</li><li>CloudFront (Content Delivery Network)</li><li>WAF (Web Application Firewall)\</li></ul><p>Most AWS services are Region-scoped:</p><ul><li>Amazon EC2 (Infrastructure as a Service)</li><li>Elastic Beanstalk (Platform as a Service)</li><li>Lambda (Function as a Service)</li><li>Rekognition (Software as a Service)</li></ul><h4>Shared Responsibility Model diagram</h4><ul><li>CUSTOMER = RESPONSIBILITY FOR THE SECURITY <strong>IN</strong> THE CLOUD</li><li>AWS = RESPONSIBILITY FOR THE SECURITY <strong>OF </strong>THE CLOUD</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*iSwLRmCcF014sEbN9FfU1Q.png" /></figure><h4>AWS Acceptable Use Policy</h4><ul><li>No Illegal, Harmful, or Offensive Use or Content</li><li>No Security Violations</li><li>No Network Abuse</li><li>No E-Mail or Other Message Abuse</li></ul><h3>Understanding Your AWS Account</h3><p>Amazon Web Services is a really big place. Each account has access to more than 100 distinct services, which can each be deployed in hundreds or even thousands of permutations.</p><p>Anyone with the right account credentials can — legitimately or otherwise — launch new service instances without anyone else knowing.</p><p>With all that going on all the time, there are going to be two account-level things you want to be clear about:</p><p><strong>Costs:</strong></p><p>What’s it all going to cost you? Because cloud services are scalable, there’s virtually no limit to how much of them you can purchase, or to how much they can cost you. If something isn’t going according to plan, you’ll want to know what it is and how to pull its plug as soon as possible.</p><p><strong>Administration:</strong></p><p>Who’s running the show? In other words, who has the authority to make the big decisions about firing up and shutting down account resources? In addition to the fact that those decisions will have significant <strong>financial implications</strong>, they’ll also define your organization’s public presence.</p><p>In this section, we will be mostly discussing monitoring and keeping a lid on costs. If it is not controlled, it will affect you financially.</p><h4>The Free Tier</h4><p>Human tendency is to take trial first before purchasing the goods or services. AWS has taken this into account. AWS figures that the more comfortable you feel working with its services, the more likely you’ll eventually start moving serious workloads to its cloud. So, <strong>AWS offers a generous Free Tier for the first 12 months</strong> after opening a new account.</p><p>Under the Free Tier, you can freely experiment with light versions of most AWS services without being billed.</p><p><strong>What you get in Free Tier?</strong></p><ul><li>It’s remarkable how much you can do with the Free Tier. Since, for instance, you’re allowed to run a t2.micro Elastic Cloud Compute (EC2) instance — powered by either Linux or Windows — for up to 750 hours per month</li><li>You can run multiple concurrent EC2 resources for an experimental purpose. You won’t be billed as long as the total monthly hours of run time don’t exceed 750</li><li>You can run low demand website without interruption for 12 months.</li><li>You can run lightweight relational database workload under Amazon’s Relational Database Service (RDS) for 750 hours per month.</li><li>You can also utilize storage services. You can store up to 5GB of data within the Storage Services (S3) bucket.</li><li>We can utilize 25 GB of storage in Amazon DynamoDB (NoSQL Database)</li><li>We can utilize Amazon SageMaker (Tool for ML and Data Scientist) for 2 months.</li><li>AWS Lambda allows you to send 1M requests per month. (AWS Lambda is a serverless compute service that runs your code in response to events and automatically manages the underlying compute resources for you)</li><li>You get 2 months of free trial in Amazon Redshift (Data Warehousing )</li><li>You get 1M publishes for Amazon’s fast push messaging service called Amazon SNS</li></ul><p>There are more to this but you get my point. You can have that checked right from <a href="https://aws.amazon.com/free">AWS website</a>.</p><p><strong>Tracking Your Free Tier Usage</strong></p><p>Note that, the free tier is much like the free trial which comes with some limitations. Once you have completed checking something or you are done with utilizing the services, it is necessary to stop them. Leaving those services running can cost you. Therefore you definitely want to keep an eye or two on your account.</p><ul><li>AWS sents you email notification as soon as you are near to end of free tier usages. It’s important to keep eye on the emails.</li><li>The second tracking tool will appear toward the <strong>bottom of the Billing Dashboard</strong> for any account that’s still Free Tier–eligible.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*5wEjvIxjJNV1HgaDE5ma7g.png" /></figure><p><strong>What’s Available Under the Free Tier?</strong></p><p>There are actually two kinds of free services:</p><p>■ Light implementations of most AWS services that are available through the first 12 months of a new AWS account</p><p>■ Light usage of certain AWS services that are always available — even after your initial 12 months are up</p><p><strong>Permanently Free Services</strong></p><p>There are few services from Amazon AWS are permanently free. It includes following services:</p><ul><li>10 GB of data retrievals from Amazon Glacier per month. Glacier is a low-cost storage service that’s ideal for long-term storage where you’re not likely to require quick access to your data.</li><li>62,000 outbound email messages per month using Amazon Simple Email Service (SES). SES is an enterprise-scale email service geared to organizations that regularly send large volumes of emails.</li><li>One million requests and 3.2 million seconds of compute time for AWS Lambda functions. Lambda lets you run code in response to network-based triggers without having to worry about provisioning any underlying server infrastructure.</li><li>10 custom monitoring metrics and 10 alarms on Amazon CloudWatch active at any given time. You use CloudWatch either directly or in combination with other tools to track resource performance and costs.</li></ul><p><strong>Note:- </strong>AWS Free Tier benefits do not apply to resources launched in the GovCloud (US) region or through an AWS Organizations member account</p><p><strong>Online Calculators for Calculating the Costs</strong></p><p>There are various calculator available to visualize the total costs that will incurred if you use the services for particular duration.</p><ul><li>AWS Simple Monthly Calculator</li><li>AWS Total Costs Ownership Calculator (TCO Calculator)</li></ul><p>In the monthly calculator, you can add the required services and check for the estimated uses and costs that will be incurred for users.</p><p>In the TCO calculator, it will return the services that costs you on Amazon AWS and it will also show you, how much costs would’ve occurred to you if you have selected “on-premises” resources than AWS cloud. (Kind of comparison)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*uAlkMCbWXpjVKIPev5x7eA.png" /></figure><h4>Service Quotas (Service Limits)</h4><p>The total scope of the AWS cloud is vast. It’s hard to even visualize just how much compute and storage capacity is available for its customers. And the scalability of its design means that there shouldn’t be a practical ceiling on how much infrastructure any customer is able to access on demand</p><p>AWS maintains service quotas (formerly called service limits) for each account to help guarantee the availability of AWS resources and prevent accidental provisioning of more resources than needed. Some service quotas are raised automatically over time as you use AWS. However, most AWS services require that you request quota increases manually.</p><p>You can use <a href="https://console.aws.amazon.com/servicequotas">AWS Service Quotas console</a> to view and request increases for most AWS quotas.</p><h4>Billing and Cost Management</h4><p>No doubt that AWS provides great services for various applications. Along with performance of the AWS, the organization also needs to keep eye on the billing and usages details. There are various tools that could help any organization or customer to overlook their account.</p><p><strong>The AWS Billing Dashboard</strong></p><ul><li>It contains spend summary is visual way (Past &amp; Present Spend Summary)</li><li>It also contains forecast for current or future months so we can plan accordingly</li><li>There’s also a Month-to-Date Spend By Service display from which choosing the Bill Details button will take you to an itemized breakdown of your current spending.</li><li>The Billing Dashboard also includes links to pages where you can set payment methods and enter your organization’s tax information.</li><li>The Payment History link provides records of your previous transactions.</li></ul><p><strong>AWS Budgets</strong></p><p>An AWS budget is a tool for tracking a specified set of events so that when a preset threshold is approached or passed, an alert — perhaps an email — is triggered.</p><p>You can create one of three budget types:</p><ul><li>Cost budget to monitor costs being incurred against your account</li><li>Usage budget to track particular categories of resource consumption</li><li>Reservation budget to help you understand the status of any active EC2, RDS, Redshift, or Elasticache reserve instances you might have</li></ul><h4>Monitoring Your Costs</h4><p>We can monitor the costs for services through following tools</p><p><strong>Cost Explorer:</strong></p><ul><li><a href="https://aws.amazon.com/aws-cost-management/aws-cost-explorer">Cost Explorer</a> lets you build graphs to visualize your account’s historical and current costs.</li><li>It allows you to filter account cost events by date, region, Availability Zone, instance type, platform (Linux, Windows, and so on), and others. CSV-formatted files based on customized views can also be downloaded.</li></ul><p><strong>Cost and Usage Reports:</strong></p><ul><li>Cost and usage reports are (right now, at least) accessed from the Reports link on the Billing Dashboard.</li><li>You can configure reports to be created that include the full range of activity on your account, including what resources you have running and how much they’re costing you.</li><li>The reports, once generated at preset intervals, are compressed, saved using the CSV format</li></ul><p><strong>Cost Allocation Tags:</strong></p><p>Tags are <strong>metadata identification elements</strong> representing a resource and its actions. Tags can be used to organize and track your resources, allowing you to visualize and better understand how resources are being used.</p><p>AWS offers two distinct kinds of tags that actually have nothing to do with each other.</p><ul><li>Resource tags: Resource tags are often used in busy accounts to help administrators quickly identify the purpose and owner of a particular running resource.</li><li>Cost allocation tags: Cost tags are only meant to interact with billing tools and won’t show up in the context of any other AWS resource or process. Like resource tags, cost allocation tags help you efficiently identify your resources, but only for the purpose of tracking your account spending.</li></ul><h4>AWS Organizations</h4><ul><li>Formerly known as Consolidated Billing</li><li>AWS Organizations allows you to centralize the administration of multiple AWS accounts owned or controlled by a single company.</li><li>This can make a lot of sense, since many companies will own more than one account — or might share AWS resources with vendors and clients</li><li>Being able to control the allocation of resource permissions, security, and spending from a single pane of glass is a big deal. It’s also a convenient way to manage payments</li></ul><h3>Getting Support on AWS</h3><p>AWS provides layers of support designed to help you as you take your first confusing steps on the platform, learn about the many ways you can use AWS services, and struggle to optimize and secure your increasingly complex resources.</p><p>In this section we will learn about -</p><ul><li>What kinds of AWS support that are available and how to find them.</li><li>You’ll learn about the four AWS support plans</li><li>what professional services are available, what kinds of online documentation and forums are out there?</li><li>what Amazon’s Trusted Advisor tool is?</li></ul><h4>Support Plans</h4><p>When you create a new AWS account, you’re required to select a support plan. Depending on the kinds of projects you plan to run with your account, the <strong>$15,000/month and up</strong> that you’ll pay for the <strong>Enterprise Support plan</strong> which might feel a bit excessive, so the free Basic Support plan is always an option while you’re getting started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*2RI4QBSG-2vJDdr8192IIg.png" /></figure><p>Let’s look at the benefits of having AWS supports →</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*u7atJt4ERP1nlR8wOVhEzA.png" /></figure><p>There are total 4 types of support plans and we will look at them one by one.</p><p><strong>The Basic Support Plan:</strong></p><ul><li>On the Basic plan, you’re not paying anything beyond the regular costs of consuming AWS resources.</li><li>However, for the most part, you’re given access only to publicly available documentation, including white papers, tutorials, and support forums.</li><li>In addition, you’ll be able to contact customer service at any time of the day or night for account-related issues (such as bill payment).</li><li>You also get limited access to the Trusted Advisor tool.</li></ul><p><strong>The Developer Support Plan:</strong></p><ul><li>AWS recommends the Developer Support plan for organizations running non-production workloads. (Things that organization currently developing but not pushed to the production)</li><li>Developer plan is not suitable for critical applications. Because your direct access to AWS cloud support associates is limited to emails during business hours and to asking their advice on general information about AWS use cases.</li><li>The associates you contact when you open a support ticket won’t be able to discuss specific problems you’re having or details about the way your particular application should be deployed.</li><li>So if you are running infrastructure that simply must remain active, then you should seriously consider signing up for a higher support level.</li></ul><p><strong>The Business Support Plan:</strong></p><ul><li>The Business Support plan can meet the needs of many organizations by offering relatively fast and detailed answers to your technical questions.</li><li>For help, a cloud support engineer is available by email, call, chat within one hour.</li><li>Less severe issues can take longer — up to 24 hours.</li><li>This level of support can include help troubleshooting interoperability between AWS resources and third-party software and operating systems.</li></ul><p><strong>The Enterprise Support Plan:</strong></p><ul><li>As you can easily tell from the price tag (starting at $15,000/month), the Enterprise plan is appropriate only for large operations whose scope is global and for whom downtime is simply unthinkable.</li><li>For example, can you imagine an evening without Netflix (which is, after all, a key AWS customer)?</li><li>It includes the technical account manager (TAM) who is assigned as a dedicated “guide and advocate” for your account.</li><li>Your TAM is more than just a technical resource; the TAM becomes closely involved in your deployment, guiding your team through planning, launches, and proactive reviews — all optimized using best practices.</li><li>Your TAM can provide you innovative solutions as well.</li><li>Besides a TAM, Enterprise customers get 24/7 access to senior cloud support engineers and a 15-minute response time for business-critical troubleshooting</li></ul><h4>Documentation and Online Help</h4><p>Even if you decide not to sign up for a paid support plan, there are still many places to look for help — it’s just that, for the most part, it’ll be <strong>self-help</strong>.</p><p><strong>Documentation:</strong></p><ul><li>AWS provides a lot of documentation resources. By “a lot” we mean there’s so much of it that you’ll probably never have enough time to read through the whole thing.</li><li>On the AWS documentation page you’ll find links to more than 100 AWS services along with tutorials and projects, software development kits (SDKs), toolkits, and general resources</li></ul><p><strong>Knowledge Center:</strong></p><ul><li>The AWS Knowledge Center is basically a frequently asked questions (FAQ) page.</li><li>The Knowledge Center page contains links to nearly 1,000 questions arranged by service, each representing a fairly common problem encountered by real AWS customers.</li><li>You’ll find questions like, “How can I install the AWS CloudFormation helper scripts on Ubuntu or Red Hat Enterprise Linux?” and “What happens when my reserved instance expires?”</li></ul><p><strong>Discussion Forums:</strong></p><ul><li>When things don’t work the way you expected, it’s generally safe to assume you’re not the first person to hit this particular brick wall. Even if this is something only a couple dozen people have experienced, there’s a good chance that at least one of them asked about it on some online forum.</li><li>While many of those questions were probably asked on Stack Overflow or another public site, the AWS discussion forums have also addressed their share of problems.</li></ul><h4>Trusted Advisor (TA)</h4><p>You use Trusted Advisor to visually confirm whether your account resource configurations are sound and are compliant with best practices.</p><p>Trusted Advisor organizes its <strong>compliance alerts</strong> across five categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*deXoZFDVfWA_IoVB6JD8XQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*EHFH8PRjiVtNjSfs4pXH7Q.png" /></figure><p>The full range of Trusted Advisor alerts is only available for users signed on to either the Business or Enterprise Support service tier. For everyone else — including those on the free Basic Support plan — access is limited to service limits and some of the security alerts.</p><h3>Securing Your AWS Resources</h3><p>Everyone in the IT world knows that application and infrastructure security are critically important elements of any deployment. Unfortunately, the constant stream of news about catastrophic data breaches suggests that some of us may not yet realize just how important.</p><p>In this section, we will learn how to use the Identity and Access Management (IAM) service to control which people and processes get past the wall guarding your resources (authentication) and what they’re allowed to do once they’re in (authorization).</p><h4>Identity and Access Management (IAM)</h4><p>IAM is a global service and not depends upon the regions. In IAM’s management dashboard, we will see all administration tools that we will need to manage the basics of account security.</p><p><strong>Protecting The Root User:</strong></p><ul><li>Root user is created by default when you sign-up with the AWS. This account must not be used or shared but always be protected.</li><li>For practical reasons, the root user has the permissions necessary to perform any task on your account. That includes launching any resources in any region and authorizing any expenses.</li><li>The problem is that actively using the root user over the long term with only minimal protections presents a significant security risk.</li><li>Should the root credentials ever be compromised through an attack, there will be no limit to the potential for mischief. All your data could be stolen or deleted or the attacker could run up hundreds of thousands of dollars of charges running a rogue crypto mining operation.</li><li>The recommended best practice is, therefore, to protect the root user by creating a complex password and implementing multifactor authentication and, for most administration activities, <strong><em>use IAM users instead</em></strong>.</li></ul><p><strong>IAM Users:</strong></p><ul><li>As we have stated above, once you are root users you can create multiple users to do various tasks.</li><li>If you wanted to create a primary admin to replace your root user for day-to-day administration, you would select the AdministratorAccess policy, which would provide enough permissions to get most admin tasks done without exposing your account to unnecessary risk.</li><li>Users are people within your organization, and can be grouped.</li></ul><p><strong>IAM Groups:</strong></p><ul><li>IAM groups only contains IAM users.</li><li>Certain IAM users are grouped together in the organization to form IAM Groups.</li><li>Creating group is important as it is very tedious task to assign policy to each users. Once we created groups, we can assign related policies to group directly and it will be applicable to all users in that group.</li><li>User can belong to one or multiple groups. Also, it is possible for users not be part of any group.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PbFGgRwpswMVkeaeZwak-Q.png" /></figure><p><strong>IAM Roles:</strong></p><ul><li>Like users and groups, IAM roles define the limits for what can be done within your AWS account.</li><li>Some AWS service will need to perform actions on your behalf. To do so, we will assign permissions to AWS services with IAM Roles.</li><li>Common roles:</li></ul><ol><li>EC2 Instance Roles,</li><li>Lambda Function Roles,</li><li>Roles for CloudFormation, etc.</li></ol><p><strong>IAM Permissions:</strong></p><ul><li>Users or Groups can be assigned JSON documents called policies</li><li>These policies define the permissions of the users.</li><li>• In AWS you apply the <strong><em>least privilege principle</em></strong>: don’t give more permissions than a user needs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*ojTMbZgQNZ_nu9URyEFcBQ.png" /></figure><p><strong>IAM Policies inheritance:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JkyB8QixyXVFjZfdfNTIcg.png" /></figure><p><strong>IAM Policies Structure:</strong></p><p>Consists of →</p><ul><li>Version: policy language version, always include “2012 -10–17”</li><li>Id: an identifier for the policy (optional)</li><li>Statement: one or more individual statements (required)</li></ul><p>Statements consists of →</p><ul><li>Sid: an identifier for the statement (optional)</li><li>Effect: whether the statement allows or denies access (Allow, Deny)</li><li>Principal: account/user/role to which this policy applied to</li><li>Action: list of actions this policy allows or denies</li><li>Resource: list of resources to which the actions applied to</li><li>Condition: conditions for when this policy is in effect (optional)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*fY890V217wVFUFMKPkn5Hg.png" /></figure><p><strong>IAM Password Policy:</strong></p><p>The root user logs into the AWS Management Console with the associated email address along with the password set when the account was created. But as you’re no doubt already well aware, not all passwords are created equal. If you want your account to have any chance of surviving an attack, you should avoid passwords that can be easily guessed.</p><p>Instead, choose complex and long passwords that include uppercase and lowercase characters, numbers, and symbols. Even better, use only randomly generated strings that aren’t even distantly based on the stuff going on in your life (like your birthday). And never (ever) reuse passwords across multiple accounts.</p><p>In AWS, you can set up a password policy:</p><ul><li>Set a minimum password length</li><li>Require specific character types: Including Uppercase letter, lowercase letter, numbers, non-alphanumeric characters etc.</li><li>Allow all IAM users to change their own passwords.</li><li>Require users to change their password after some time (We can set password expiration)</li><li>We can also prevent password re-use. You won’t be able to set same past password as current password.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*G4T9Fxa-t9xs1kpr3t_pIQ.png" /></figure><p><strong>Multi-Factor Authentication — MFA:</strong></p><ul><li>Users have access to your account and can possibly change configurations or delete resources in your AWS account.</li><li>Multi-factor authentication (MFA) adds a second layer of security to your logins.</li><li>Once it’s enabled, a user will need to provide not only a password to authenticate (“something you know”) but also, as a second factor, a temporary digital token sent through a preset device (“something you have”), like a smartphone running an Authenticator app.</li><li>MFA works by associating a physical device — either a Universal 2nd Factor (U2F) or MFA-compliant device like YubiKey or a smartphone with the Authenticator app installed — with your account.</li><li>When you try to log in, you’ll fi rst enter a password, and then a short-lived code (usually a six-digit number) will be sent to your MFA device.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LN9xrlDoo8AwzJya9SvGDg.png" /></figure><ul><li><strong>Main benefit of MFA:</strong> if a password is stolen or hacked, the account is not compromised.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9z5u3aERSAQc5lTj3rhRAA.png" /><figcaption>MFA devices options in AWS</figcaption></figure><p><strong>IAM Security Tools:</strong></p><ul><li><strong>IAM Credentials Report (account-level):</strong> There is one more IAM resource that we must know and that is Credentials Report. It is accessed from IAM’s dashboard. It consists of ‘simple download button’ upon clicking on it you will download CSV file. It contains lists all your account’s users and the status of their various credentials.</li><li><strong>IAM Access Advisor (user-level): </strong>Access advisor shows the service permissions granted to a user and when those services were last accessed.</li></ul><p><strong>IAM Guidelines &amp; Best Practices:</strong></p><ol><li>Don’t use the root account except for AWS account setup.</li><li>Assign users to groups and assign permissions to groups.</li><li>Create a strong password policy.</li><li>Use and enforce the use of Multi-Factor Authentication (MFA)</li><li>Create and use Roles for giving permissions to AWS services.</li><li>Use Access Keys for Programmatic Access (CLI / SDK).</li><li>Audit permissions of your account with the IAM Credentials Report.</li><li>Never share IAM users &amp; Access Keys! (We will talk about this more in next section)</li></ol><h3>How can users access AWS ?</h3><p>To access the AWS, user has 3 main options : →</p><ol><li>AWS Management Console (protected by password + MFA)</li><li>AWS Command Line Interface (CLI): protected by access keys</li><li>AWS Software Developer Kit (SDK) — for code: protected by access keys.</li></ol><p>Now let’s look at one by one to understand about them.</p><h4>The AWS Management Console</h4><p>The primary way you’ll interact with AWS services is through the AWS Management Console, a web-based application you can use from any compatible web browser. Until you get intimately familiar with the core AWS services, you’ll likely use the AWS Management Console almost exclusively.</p><p>The AWS Management Console gives you a user friendly, point-and-click way to navigate your AWS resources, and you’ll start by learning your way around it. We also have AWS Console Mobile Application, which allows you to view and manage some of your AWS resources from an Android or iOS mobile device.</p><p>Now let’s look at some important pointers about AWS Management Console →</p><ul><li>The AWS Management Console, also known as the AWS Console or the AWS Web Console, is a web interface you can use to manage all of your AWS cloud resources using a web browser, including <strong><em>compute, storage, and networking.</em></strong></li><li>The AWS Management Console is what you’ll choose if you want to do things using a point-and-click interface.</li><li>Each AWS service has its own service console. Some services such as CloudWatch and AWS Billing and Cost Management offer visual reports that you can view and download.</li><li>Most settings for your AWS resources can be configured using the AWS Management Console.</li><li>The AWS Management Console is compatible with the these web browsers:</li></ul><ol><li>Apple Safari</li><li>Google Chrome</li><li>Microsoft Edge</li><li>Microsoft Internet Explorer</li><li>Mozilla Firefox</li></ol><p><strong>Accessing the AWS Management Console:</strong></p><p>To access the AWS Management Console, browse to <a href="https://console.aws.amazon.com/">https://console.aws.amazon.com</a> in your web browser.</p><p>There are two ways to sign in: as the <strong><em>root user</em></strong> or as an<strong><em> Identity and Access Management (IAM) user</em></strong>.</p><ul><li>To log in as the root user for your account, enter the email address and password associated with your AWS account.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*oxdt3cxcDa4eP61RIFplqw.png" /></figure><ul><li>To log in as an IAM user, enter your account ID or account alias and choose Next.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*mRQCuYCBgTxCDif0rxjfuQ.png" /></figure><ul><li>The AWS Management Console will take you to another page where you should enter your IAM username and password.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*CsDPdGrK9jjhiSgyvJNSEQ.png" /></figure><p><strong>Note:-</strong></p><ul><li>Your login is protected by password + MFA</li><li>Once you’re logged in, your session will remain active for 12 hours. After that, it’ll expire and log you out to protect your account.</li></ul><p><strong>The AWS Console Mobile Application:</strong></p><p>The AWS Console Mobile Application is a smartphone application that lets you manage your AWS account and resources on the go</p><p>The application features a dashboard showing key information about your AWS account and resources, including the following:</p><ul><li>Service Health — View any current health issues with AWS services across different regions.</li><li>CloudWatch Alarms — View alarm graphs and current alarm status.</li><li>Billing — View your current billing balance and a graph of usage charges.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*JVA8bJpT040lQP8UWd15PQ.png" /><figcaption>The AWS Console Mobile Application dashboard</figcaption></figure><p>The AWS Console Mobile Application supports Apple iOS 7.0+ and Android 4.0+. You can download it from the Amazon Appstore, Google Play, or iTunes.</p><p>When you first launch the application, it’ll prompt you to authenticate to an existing AWS account by adding an identity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*ac6Zrg7yROWL9HDw6wc7lg.png" /><figcaption>Adding an identity to the AWS Console Mobile Application</figcaption></figure><h4>The AWS Command Line Interface (AWS CLI)</h4><p>The AWS Command Line Interface (AWS CLI) is a unified command-line tool to manage your AWS resources. AWS gives access to the public application programming interfaces for all AWS services within 180 days of service launch.</p><blockquote>A tool that enables you to interact with AWS services using commands in your command-line shell</blockquote><p>Anything you can do in the AWS Management Console, you can do from your terminal using the AWS CLI. The AWS CLI is <strong><em>useful for performing repetitive tasks</em></strong>, such as launching EC2 instances, taking EBS snapshots, or attaching policies to IAM users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*NuNxWt5eahNhVnUZb2j49g.png" /><figcaption>AWS CLI Interface</figcaption></figure><p>You can enter AWS CLI commands <strong><em>manually</em></strong> for convenience, or you can incorporate them into a <strong><em>script for automation</em></strong>.</p><p>The AWS CLI is a versatile tool that can save you a lot of time versus the AWS Management Console.</p><p><strong>Login with Access Keys:</strong></p><p>AWS CLI requires you to log in using the access keys. The Access Keys are generated through the AWS Console. User is responsible for managing their access keys.</p><p>Access Keys are secret, just like a password. Don’t share them. Just like we need username to login in console, with CLI, we need <strong>Access Key ID </strong>and as password is your <strong>Secret Access Key</strong></p><ul><li>Username → Access Key ID</li><li>Password → Secret Access Key</li></ul><p><strong>Requirements:</strong></p><ul><li>The AWS CLI is compatible with Windows, macOS, and Linux. To connect to AWS using the CLI, your network should allow outbound access to the internet on TCP port 443.</li><li>You’ll also need an IAM access key ID and secret key to authenticate to AWS using the CLI.</li></ul><p><strong>Installation:</strong></p><ul><li>Standalone installation available for Windows, Mac, and Linux.</li><li>For Windows, use the MSI installer that includes setup packages for Windows 64-bit and 32-bit architectures.</li><li>The stand-alone installer for Linux and macOS is a bundled installer that includes the AWS CLI, dependencies, and a script to install it</li></ul><p><strong>Note:-</strong> You need Python to be installed in your system.</p><h4>Software Development Kits (SDK)</h4><p>AWS software development kits simplify the use of AWS services in custom applications. Application developers can use an <strong><em>SDK to integrate their applications with AWS services</em></strong> easily and reliably.</p><p>SDKs save application developers from having to write <strong><em>low-level code</em></strong> to interact directly with the AWS service API endpoints. Instead, the developer just uses the SDK’s well-documented methods to learn how to incorporate it into their application.</p><p>AWS offers SDKs for the following popular programming languages:</p><ul><li>Java</li><li>.NET</li><li>Node.js</li><li>PHP</li><li>Python</li><li>Ruby</li><li>JavaScript</li><li>Go</li><li>C++</li></ul><p><strong>Mobile Software Development Kits:</strong></p><p>AWS also offers mobile SDKs for the development of applications for smartphones and tablets. Available mobile SDKs include the following:</p><ul><li>AWS Mobile SDK for Android</li><li>AWS Mobile SDK for iOS.</li></ul><p><strong>Internet of Things Device Software Development Kits:</strong></p><p>You can use the <strong>AWS IoT SDKs</strong> to create applications that run on Internet of Things (IoT) devices, such as sensors, microcontrollers, smart appliances, smart lightbulbs, and AWS IoT buttons.</p><p>AWS IoT is a collection of services that allow IoT devices to interact with AWS services, other applications, and even other devices. The AWS IoT platform lets you centrally onboard, manage, and monitor IoT devices.</p><p>The AWS IoT SDKs allow developers to optimize memory, network, and power usage; reduce the size of applications; and ensure secure, fast communication with AWS.</p><p>IoT device SDKs are available for the following languages and platforms:</p><ul><li>Embedded C</li><li>JavaScript</li><li>Arduino Yún</li><li>Python</li><li>Java</li><li>C++</li></ul><h3>The AWS EC2 (Elastic Compute Cloud)</h3><p>The AWS EC2 (Elastic Compute Cloud) is one of the most popular of AWS’ offering from Amazon and it is comes under the “Infrastructure as a Service (IaaS)”</p><p>It consists of →</p><ul><li>Renting virtual machines (EC2)</li><li>Storing data on virtual drives (EBS)</li><li>Distributing load across machines (ELB)</li><li>Scaling the services using an auto-scaling group (ASG)</li></ul><p>To get your virtual machine (VM) instance running, you’ll first define the elements one at a time. Rather than installing an operating system and a software stack from scratch the traditional way, you need to choose <strong><em>Aamzon Machine Image (AMI)</em></strong>.</p><p>Instead of choosing the right CPU, memory modules, and network adapters and adding them to your physical motherboard, you’ll choose the <strong><em>instance type</em></strong> matching your application needs.</p><p>And rather than purchasing storage drives and sliding them into your server chassis, you’ll define <strong><em>virtual storage volumes</em></strong> available through the <strong><em>Elastic Block Store (EBS)</em></strong></p><h4>Amazon Machine Images (AMI)</h4><p>An <strong><em>image</em></strong> is a software bundle that was built from a template definition and made available within a single AWS Region.</p><p>The bundle can be copied to a freshly created storage volume that, once the image is extracted, will become a bootable drive that’ll turn the VM it’s attached to into a fully operational server. (Think like it is bootable image which contains software’s and OS)</p><p>The nice thing about AMIs is that they’re available in so many flavors. You can select AMIs that will give you clean, cloud-optimized operating systems like official versions of Red Hat Enterprise Linux (RHEL), Ubuntu, Windows Server, or Amazon’s own Amazon Linux.</p><p>It also contains OS you need preloaded with one of hundreds of popular software stacks like OpenVPN (secure remote connectivity), TensorFlow (neural networks), or a Juniper firewall already installed and ready to go.</p><p>AMIs are organized into four collections:</p><ul><li>Quick Start AMIs</li><li>Custom AMI’s</li><li>AWS Marketplace</li><li>Community AMIs</li></ul><p><strong>Quick Start AMIs:</strong></p><ul><li>AWS makes the most popular AMIs easily available through the QuickStart tab on the Choose An Amazon Machine Image page.</li><li>They’re Free Tier–eligible.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*AFX26qGJYreGeGrDkdrM_Q.png" /></figure><ul><li>In Free Tier → We can use open-source operating systems like shown above.</li><li>But other choices — like Windows Server and RHEL — will carry the normal licensing charges. Once you launch an instance running one of those images, the charges will be billed through your AWS account.</li></ul><p><strong>AWS Marketplace AMIs:</strong></p><ul><li>AWS Marketplace is a software store managed by Amazon where vendors make their products available to AWS customers as ready-to-run AMIs</li><li>Companies like SAP, Oracle, and NVIDIA will package their software solutions into AMIs, often running on one or another Linux distribution</li><li>Marketplace AMIs will often offer a limited-time free trial for their software and reduced annual subscription rates.</li><li>When you select a Marketplace AMI, you’ll be shown its total billing cost, broken down into separate software license and EC2 infrastructure amounts.</li></ul><p><strong>Community AMIs:</strong></p><ul><li>Looking for a more specialized image built with a software stack that’s not available in the QuickStart or Marketplace tab? There are more than 100,000 AMIs to choose from in the Community AMIs tab.</li><li>Some are supported by recognized vendors such as Canonical, but others are provided as is, often by end-users like you.</li><li>Given the informal sources of some Community AMIs, you must take responsibility for the security and reliability of AMIs you launch.</li></ul><p><strong>Custom AMIs:</strong></p><p>It’s possible to convert any existing EC2 instance into an AMI by creating a snapshot from the EBS volume used with an instance and then creating an image from the snapshot.</p><h4>Understanding EC2 Instance Types</h4><p>An EC2 instance type is simply a description of the <strong><em>kind of hardware resources</em></strong> your instance will be using.</p><p>When we try to configure EC2 instance, we may need to consider following questions →</p><ul><li>What would be the OS? …Linux, Window, macOS</li><li>How much compute power &amp; cores (vCPU)</li><li>How much random-access memory (RAM)</li><li>How much storage space?: Network-attached (EBS &amp; EFS), hardware (EC2 Instance Store)</li><li>Which would be the Network card?: Speed of the card, Public IP address</li><li>What would be Firewall rules?: Security Groups</li><li>What would be the Bootstrap script (configure at first launch): EC2 User Data</li></ul><p>A vCPU is a metric used by AWS to describe the compute power you’ll get from a given instance. It’s meant to make you think in terms of the multiprocessor CPUs on consumer and server motherboards, where more is generally better.</p><p>While, in general, the more vCPUs and memory you get, the better your instance will perform, that’s definitely not the whole story. EC2 offers instance type families that are optimized for very different computing tasks. The T2, T3, and M5 types are included in the general-purpose family because of their ability to perform well for a wide range of uses.</p><p>The following are the various instance type that EC2 offers depending upon the usage or use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*3P-ieoP8lqLpobKo_0E4vw.png" /></figure><p>The bottom line is that choosing the right instance type family will sometimes let you get away with fewer vCPUs and less memory — and a lower cost.</p><p>If regulatory restrictions or company policy requires you to use only physically isolated instances, you can request either a <strong>dedicated instance</strong> or a <strong>dedicated host.</strong></p><p><strong><em>But wait, what’s the difference between two?</em></strong></p><ul><li>A dedicated instance is a regular EC2 instance that, instead of sharing a physical host with other AWS customers, runs on an isolated host that’s set aside exclusively for your account.</li><li>A dedicated host also gives you instance isolation but, in addition, allows a higher level of control over how your instances will be placed and run within the host environment.</li><li>Both levels involve extra per-hour pricing and are available using on-demand, reserved, or spot models</li></ul><p><strong>AWS Instance Types Naming Convention:</strong></p><p>AWS has the following naming convention,</p><p>Example:- <strong><em>m5.2xlarge</em></strong></p><ul><li><strong>m</strong>: Instance class</li><li><strong>5</strong>: Generation (AWS improves them over time)</li><li><strong>2xlarge</strong>: Size within the instance class.</li></ul><p>Let’s look at the instance types one by one.</p><p><strong>General Purpose:</strong></p><ul><li>Great for a diversity of workloads such as web servers or code repositories</li><li>It is a<strong> </strong>balance between: Compute, Memory &amp; Networking.</li><li>Most often times you will see <strong><em>t2.micro</em></strong> which is a General Purpose EC2 instance.</li></ul><p><strong>Compute Optimized:</strong></p><ul><li>It is great for compute-intensive tasks that require high performance processors.</li><li>Examples: Scientific modeling &amp; machine learning, Dedicated gaming servers, Media transcoding, High performance web servers, High performance computing (HPC), Batch processing workloads etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xghHOvSxa0GgfMuC29JudQ.png" /></figure><p><strong>Memory-Optimized:</strong></p><ul><li>When you want fast performance for workloads that process large data sets in memory.</li><li>Examples: High performance, relational/non-relational databases, In-memory databases optimized for BI (business intelligence), processing big unstructured data etc.</li></ul><p><strong>Storage Optimized:</strong></p><ul><li>Great for storage-intensive tasks that <strong><em>require high, sequential read and write access</em></strong> to large data sets on local storage</li><li>Examples: High frequency online transaction processing (OLTP) systems, Relational &amp; NoSQL databases, Cache for in-memory databases (for example, Redis), Data warehousing applications, Distributed file systems etc.</li></ul><h4>Introduction to Security Groups</h4><p>Security Groups are the fundamental of network security in AWS. They control how traffic is allowed into or out of our EC2 Instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*AQ00Ztroodv5JyeAshzqow.png" /></figure><p>The Security groups are acting as a<strong><em> “firewall”</em></strong> on EC2 instances. only contains <strong><em>allow </em></strong>rules.</p><p>They regulate:</p><ul><li>Access to Ports</li><li>Authorised IP ranges — IPv4 and IPv6</li><li>Control of inbound network (from other to the instance)</li><li>Control of outbound network (from the instance to other)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYyobEfIpPuOGDcddDy_Uw.png" /></figure><p>Some good to know pointers about Security Groups:</p><ul><li>Security groups can be attached to multiple instances.</li><li>They do live “outside” the EC2 → if traffic is blocked by security group, the EC2 instance won’t see it.</li><li>It’s good to maintain one separate security group for SSH access.</li><li>If your application is not accessible (time out), then it’s a security group issue.</li><li>If your application gives a “connection refused“ error, then it’s an application error, not the security group blocking it.</li><li>By default, security groups blocks all inbound (incoming) traffic.</li><li>By default, All outbound (Outgoing) traffic is authorised by default.</li></ul><p><strong>How do we connect to EC2 instance?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7QmKCYHdS-rxN4z1sPM-w.png" /></figure><ul><li>SSH is one of the most important function. It allows you to control a remote machine, all using the command line.</li><li>Windows &lt; 10, we can use PuTTY to connect EC2 instance.</li><li>EC2 instance connect allows you to connect EC2 instance within your browser.</li></ul><h4>Virtual Server Storage (EC2 Instance Storage Section)</h4><p>Like everything else in the cloud, the storage volumes holding your instance’s OS and data are going to be virtual.</p><p>In most cases, that’ll mean the 20 or 30 (or 2,000) GB drive holding your application is really just a 20 or 30 GB partition cleverly disguised to look like a stand-alone device. In fact, however, it was actually carved out of a much larger drive.</p><p>Some instance types support only volumes from the <strong><em>Elastic Block Store (EBS)</em></strong>, others get their storage from <strong><em>Instance Store Volumes</em></strong>, and some can happily handle both.</p><p><strong>Amazon Elastic Block Store (EBS):</strong></p><ul><li>The physical drive where an EBS volume actually exists may live quite a distance from the physical server that’s giving your instance life.</li><li>Rather than connecting directly to the motherboard via, say, a SATA cable the way a physical drive plugs into a physical computer, EBS volumes speak with your instance over a <strong><em>super low-latency network</em></strong> connection spanning the data center.</li><li>EBS are fast but they are not faster than Instance Store Volumes.</li><li>Unlike the instance store, the data stored on EBS volumes will survive shutdowns and system crashes.</li><li>EBS volumes can be encrypted, which, when you’re working with sensitive data, can make a big difference.</li><li>EBS volumes can be moved around, mounted on other instances, and, as you’ve seen, converted to AMIs.</li></ul><p><strong>Amazon EC2 Instance Store Volumes:</strong></p><ul><li>It is faster as data on physical drives attached directly to the physical instance server.</li><li>The downsides of instance store volumes: No encryption, lack of flexibility)</li></ul><p><strong>Note:-</strong> Think like, EBS is storage away from the physical instance server. Though they are fast as they are connected through super low latency network. The Instance Store Volume in other hand connected to physical instance server.</p><h4>Understanding EC2 Pricing Models</h4><p>What you’ll pay for your EC2 instances will depend on the way you consume the service. Here are some pricing models that we need to know.</p><p><strong>On-Demand Instances:</strong></p><ul><li>The most expensive pricing tier is on-demand instances.</li><li>In this model, you pay for every hour the instance is running regardless of whether you’re actually using it.</li><li>On-demand is great for workloads that need to run for a limited time without interruption.</li><li>It is like Pay for what you use model.</li><li>It has the highest cost but no upfront payment.</li><li>Since it is pay for what you use model, therefore no long-term commitments.</li></ul><p><strong>Reserved Instances:</strong></p><ul><li>If your application needs to run uninterrupted for more than a month at a time, then you’ll usually be better off purchasing a reserved instance.</li><li>Practically, however, you’re unlikely to find an available reservation with a term shorter than 12 months. One- and three-year terms are always available.</li><li>Reserved instances are paid for using an All Upfront, Partial Upfront, or No Upfront payment option.</li><li>When you select reserved instances, there is up to 72% discount compared to on-demand instances.</li><li>As reservation period increases, discount also increases.</li><li>Discount is also depends upon the purchasing options. All upfront gets more discount than partial one.</li><li>Recommended for steady-state usage applications (think database)</li></ul><p><strong>EC2 Spot Instances:</strong></p><ul><li>It is most cost-effective AWS instances</li><li>Can get a discount of up to 90% compared to On-demand</li><li>For workloads that don’t need to run constantly and can survive unexpected shutdowns, your cheapest option will probably involve requesting instances on the EC2 spot market.</li><li>It is useful for workloads that are resilient to failure. Such as: Data Analysis, Image processing, and distributed workloads or workload with a flexible start and end time.</li><li>Not suitable for critical jobs or databases.</li></ul><p><strong>EC2 Dedicated Hosts:</strong></p><ul><li>An Amazon EC2 Dedicated Host is a physical server with EC2 instance capacity fully dedicated to your use.</li><li>Dedicated Hosts can help you address compliance requirements and reduce costs by allowing you to use your existing server-bound software licenses.</li><li>Allocated for your account for a 3-year period reservation</li><li>It is quite expensive.</li></ul><p><strong>EC2 Dedicated Instances:</strong></p><p>A dedicated instance is a regular EC2 instance that, instead of sharing a physical host with other AWS customers, runs on an isolated host that’s set aside exclusively for your account.</p><h4>Which purchasing option is right for me?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><ul><li><strong>On-demand:</strong> Coming and staying in resort whenever we like, we pay the full price</li><li><strong>Reserved:</strong> like planning ahead and if we plan to stay for a long time, we may get a good discount.</li><li><strong>Spot instances:</strong> the hotel allows people to bid for the empty rooms and the highest bidder keeps the rooms. You can get kicked out at any time</li><li><strong>Dedicated Hosts:</strong> We book an entire resort for ourself.</li></ul><h3>EC2 Instance Storage</h3><p>Like everything else in the cloud, the storage volumes holding your instance’s OS and data are going to be virtual.</p><p>In most cases, that’ll mean the 20 or 30 (or 2,000) GB drive holding your application is really just a 20 or 30 GB partition cleverly disguised to look like a stand-alone device. In fact, however, it was actually carved out of a much larger drive.</p><p>Some instance types support only volumes from the <strong><em>Elastic Block Store (EBS)</em></strong>, others get their storage from <strong><em>Instance Store Volumes</em></strong>, and some can happily handle both.</p><h4><strong>Elastic Block Store (EBS)</strong></h4><ul><li>An EBS (Elastic Block Store) Volume is a network drive you can attach to your instances while they run.</li><li>Rather than connecting directly to the motherboard via, say, a SATA cable the way a physical drive plugs into a physical computer, EBS volumes speak with your instance over a <strong><em>super low-latency network</em></strong> connection spanning the data center.</li><li>It allows your instances to persist data, even after their termination.</li><li>EBS are fast but they are not faster than Instance Store Volumes.</li><li>Unlike the instance store, the data stored on EBS volumes will survive shutdowns and system crashes.</li><li>EBS volumes can be encrypted, which, when you’re working with sensitive data, can make a big difference.</li><li>EBS volumes can be moved around, mounted on other instances, and, as you’ve seen, converted to AMIs.</li><li>They can only be mounted to one instance at a time (at the CCP level)</li><li>They are bound to a specific availability zone (AZs). Meaning an EBS Volume in us-east-1a cannot be attached to us-east-1b.</li></ul><blockquote><strong>Analogy:</strong> Think of them as a “network USB stick”</blockquote><ul><li>Note:- Free tier: 30 GB of free EBS storage of type General Purpose (SSD)</li><li>It can be detached from an EC2 instance and attached to another one quickly (Using Snapshot, we will learn this later)</li><li>We can increase the capacity of the drive over time and we will get billed according to provisional capacity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urZKEBOuB4PA-ThzXGvb4w.png" /></figure><ul><li>We can controls the EBS behaviour when an EC2 instance terminates. When EC2 gets terminated, by default, the root EBS volume is deleted and not any other attached EBS volume.</li><li>We can preserve the root volume when instance is terminated.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKwbWj8ohxgDtIZuASOrSA.png" /></figure><p><strong>EBS Snapshots:</strong></p><ul><li>We can make a backup of EBS volume at any point of time with the help of EBS Snapshot.</li><li>It is not necessary to detach volume to do snapshot, but recommended.</li><li>With the help of this, we can copy snapshots across AZ or Region.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjpKVqrVSUWrLQ-5ozP0mg.png" /></figure><ul><li>We can create AMI through EBS snapshot. The AMIs created by EBS snapshots are faster as all the configuration, settings, software were already installed and snapshotting is done from existing EC2 instances.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzKx60jzO1u4M4Td-gvNtw.png" /></figure><p><strong>EC2 Image Builder:</strong></p><ul><li>It is used to automate the creation of Virtual Machines or container images.</li><li>Automate the creation, maintain, validate and test EC2 AMIs</li><li>It’s Free service (only pay for the underlying resources)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4Pr8G4GulLbhcOr8y--vA.png" /></figure><h4>EC2 Instance Store</h4><ul><li>EBS volumes are network drives with good but “limited” performance as it’s connected through low-latency network. Though, even it is low latency, it impacts somewhat on the performance.</li><li>If you need a high-performance hardware disk, use EC2 Instance Store.</li><li>It provides better I/O performances.</li><li>It is ephemeral. As EC2 Instance Store lose their storage if they’re stopped.</li><li>It is good for buffer / cache / scratch data / temporary content.</li><li>Risk of data loss if hardware fails.</li><li>Backups and Replication are your responsibility.</li></ul><h4>Elastic File System (EFS)</h4><p>AWS Elastic File System (EFS) is one of three main storage services offered by Amazon. It is a scalable, cloud-based file system for <strong><em>Linux-based applications</em></strong> and workloads that can be used in combination with AWS cloud services and on-premise resources.</p><p>EFS offers a choice between two storage classes, Infrequent Access and Standard access, depending on your needs.</p><ul><li>Standard access storage is designed for frequently accessed files.</li><li>Infrequent Access is intended for storing long-lived but less used files at a lower cost (EFS-IA)</li></ul><p>It is highly scalable and expensive service and often used as pay-per-use model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m31DVWosMInkH6_4pbi5Cg.png" /></figure><p>EFS uses the NFSv4 protocol for its file system structure, which mirrors a standard on-premise structure and simplifies transferring and accessing your files.</p><p>It can be used in combination with Elastic Cloud Compute (EC2) instances or as a stand-alone file system.</p><p>EFS does not require storage provisioning and is pay-for-use allowing you to scale services as needed.</p><p><strong>EBS vs EFS:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OywTp11iIJUUi732M5Tk_Q.png" /></figure><p><strong>EFS Infrequent Access (EFS-IA):</strong></p><ul><li>It is a storage class that is cost-optimized for files not accessed every day.</li><li>Up to 92% lower cost compared to EFS Standard.</li><li>EFS will automatically move your files to EFS-IA based on the last time they were accessed.</li><li>We can Enable EFS-IA with a Lifecycle Policy. Example: move files that are not accessed for 60 days to EFS-IA</li></ul><h4>Amazon FSx</h4><p>Amazon FSx is a fully managed <strong><em>third-party file system</em></strong> solution. It uses SSD storage to provide fast performance with low latency.</p><p>There are two available FSx solutions available in AWS:</p><p><strong>Amazon FSx for Windows File Server:</strong></p><ul><li>A fully managed, highly reliable, and scalable Windows native shared file system.</li><li>It is built on Windows File Server</li><li>It supports SMB protocol &amp; Windows NTFS.</li></ul><p><strong>Amazon FSx for Lustre:</strong></p><ul><li>A fully managed, high-performance, scalable file storage for High Performance Computing (HPC)</li><li>The name Lustre is derived from “Linux” and “cluster”.</li><li>Use cases: Machine Learning, Analytics, Video Processing, Financial Modeling</li></ul><h3>Elastic Load Balancing &amp; Auto Scaling Groups</h3><h4>Scalability &amp; High Availability</h4><ul><li>Scalability means that an application / system can handle greater loads by adapting.</li><li>There are two kinds of scalability: Vertical Scalability, Horizontal Scalability (elasticity)</li></ul><p>Let’s deep dive into the distinction, using a call center as an example.</p><p><strong>Vertical Scalability:</strong></p><ul><li>Vertical Scalability means increasing the size of the instance</li><li>For example, your application runs on a t2.micro. The scaling that application vertically means running it on a t2.large.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*0mLCKTwtbtskHqFJZZDO6Q.png" /></figure><ul><li>Vertical scalability is very common for non distributed systems, such as a database.</li><li>There’s usually a limit to how much you can vertically scale (hardware limit)</li></ul><p><strong>Horizontal Scalability:</strong></p><ul><li>Horizontal Scalability means increasing the number of instances / systems for your application.</li><li>Horizontal scaling implies distributed systems.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*hcsRFt42n0Jsx0gM_211Kg.png" /></figure><ul><li>This is very common for web applications / modern applications.</li><li>It’s easy to horizontally scale thanks the cloud offerings such as Amazon EC2.</li></ul><h4>High Availability</h4><ul><li>High Availability usually goes hand in hand with horizontal scaling</li><li>High availability means running your application / system in <strong><em>at least 2 Availability Zones (AZs)</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*gBBlAEK2PuZKeDteC3_Sng.png" /></figure><ul><li>The goal of high availability is to survive a data center loss in case of disaster or any emergency.</li></ul><p><strong>High Availability &amp; Scalability For EC2:</strong></p><p><strong>Vertical Scaling:</strong> Increase instance size (= scale up / down)</p><ul><li>From: t2.nano — 0.5G of RAM, 1 vCPU</li><li>To: u-12tb1.metal — 12.3 TB of RAM, 448 vCPUs</li></ul><p><strong>Horizontal Scaling:</strong> Increase number of instances (= scale out / in)</p><ul><li>Auto Scaling Group</li><li>Load Balancer</li></ul><p><strong>High Availability:</strong> Run instances for the same application across multi AZs</p><ul><li>Auto Scaling Group multi-AZ</li><li>Load Balancer multi-AZ</li></ul><h4>Scalability vs Elasticity vs Agility</h4><ul><li><strong>Scalability:</strong> Ability to accommodate a larger load by making the hardware stronger (scale-up), or by adding nodes (scale-out)</li><li><strong>Elasticity:</strong> Once a system is scalable, elasticity means that there will be some <strong><em>“auto-scaling”</em></strong> so that the <strong><em>system can scale based on the load</em></strong>. This is “cloud-friendly”: pay-per-use, match demand, optimize costs</li><li><strong>Agility:</strong> (not related to scalability — distractor) new IT resources are only a click away, which means that you reduce the time to make those resources available to your developers from weeks to just minutes. (This is the power of cloud)</li></ul><h4>What is Load Balancing?</h4><p>Load balancers are servers that forward internet traffic to multiple servers (EC2 Instances) downstream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isRVBRC7tXEP7jVPIzQ5SQ.png" /></figure><p><strong>Why use a load balancer?</strong></p><ul><li>It spreads a load across multiple downstream instances.</li><li>Expose a single point of access (DNS) to your application</li><li>Seamlessly handle failures of downstream instances</li><li>Do regular health checks to your instances.</li><li>Provide SSL termination (HTTPS) for your websites.</li><li>High availability across zones.</li></ul><p><strong>Why use an Elastic Load Balancer?</strong></p><p>An ELB (Elastic Load Balancer) is a managed load balancer. It is managed by AWS hence →</p><ul><li>AWS guarantees that it will be working</li><li>AWS takes care of upgrades, maintenance, high availability</li><li>AWS provides only a few configuration knobs</li></ul><p>It costs less to set up your own load balancer but it will be a lot more effort on your end (maintenance, integrations)</p><p>There are 3 kinds of load balancers offered by AWS:</p><ul><li><strong>Classic Load Balancer:</strong> It is an old elastic load balancer which would be retiring soon. It is used in layer 4 and 7.</li><li><strong>Application Load Balancer:</strong> It is meant for HTTP and HTTPS only. It is used in layer 7.</li><li><strong>Network Load Balancer:</strong> It has ultra high performance. It allows for TCP. It is used in lower layer (Layer 4)</li></ul><h4>What’s an Auto Scaling Group (ASG)?</h4><p>In real-life, the load on your websites and application can change time to time. It is important to handle increased load by your website. That’s the reason, we have something called ASG.</p><p>The goal of an Auto Scaling Group (ASG) is to:</p><ul><li>Scale-out (add EC2 instances) to match an increased load.</li><li>Scale in (remove EC2 instances) to match a decreased load.</li><li>Ensure we have a minimum and a maximum number of machines running.</li><li>Automatically register new instances to a load balancer.</li><li>Replace unhealthy instances.</li></ul><p><strong>Note:-</strong> It does cost savings. As it only run at an optimal capacity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osJXZDw82w_RT_yoQ48Giw.png" /></figure><p>Let’s understand how the Auto Scaling group works with load balancer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxYqkqMKUoBttxgqYP0LiQ.png" /></figure><p><strong>Auto Scaling Groups Scaling Strategies:</strong></p><p>There are 3 ASG strategies that followed in the AWS.</p><p><strong><em>Manual Scaling:</em></strong></p><ul><li>In this case we can update the scaling manually in the dashboard.</li></ul><p><strong><em>Dynamic Scaling:</em></strong></p><ul><li><strong>Simple / Step Scaling:</strong> When a CloudWatch alarm is triggered (for example CPU &gt; 70%), then add 2 units. When a CloudWatch alarm is triggered (for example CPU &lt; 30%) remove 1 unit.</li><li><strong>Target Tracking Scaling: </strong>We can set the average ASG CPU to stay at around 40%.</li><li><strong>Scheduled Scaling: </strong>Anticipate a scaling based on known usage patterns. Example: increase the min. capacity to 10 at 5 pm on Fridays. (Big Billion Day)</li></ul><p><strong><em>Predictive Scaling:</em></strong></p><ul><li>Uses Machine Learning to predict future traffic ahead of time.</li><li>Automatically provisions the right number of EC2 instances in advance.</li><li>Useful when your load has predictable time—based patterns.</li></ul><h3>Amazon S3 (The Core Storage Service)</h3><p>For many organizations, their most valuable asset is their data. But organizations often have their data split between the cloud and on-premises locations such as offices and data centers. (Hybrid)</p><p>It’s therefore critical to understand the different options AWS provides for storing data in the cloud, transferring data between the cloud and on-premises, and doing both in a cost-effective way without sacrificing performance.</p><p>Amazon S3 is one of the main building blocks of AWS. It’s advertised as “infinitely scaling” storage for a reason. Nowadays many websites use Amazon S3 as a backbone and many AWS services use Amazon S3 as an integration as well.</p><p><strong>Note:-</strong> The CCP exam requires “deeper” knowledge about S3</p><p>Let’s see some pointers on Amazon S3 (Simple Storage Service)</p><ul><li>Amazon’s <strong><em>Simple Storage Service(S3)</em></strong> lets you <strong><em>store </em></strong>and <strong><em>retrieve </em></strong>unlimited amounts of data from anywhere in the world at any time. You can use S3 to store any kind of file.</li><li>Although AWS calls it <strong>“storage for the internet”</strong> you can implement access controls and encryption to restrict access to your files to specific individuals and IP addresses.</li><li>S3 opens up a variety of uses, both inside and outside of AWS.</li></ul><p>Let’s start with the S3 use cases</p><ol><li>Backup and storage</li><li>Disaster Recovery</li><li>Archive</li><li>Hybrid Cloud storage (Storage on cloud and on-premises)</li><li>Application and Media hosting</li><li>Data lakes &amp; big data analytics</li><li>Static Websites</li></ol><h4>Amazon S3 Overview — Objects &amp; Buckets</h4><ul><li>Amazon S3 allows people to store objects (files) in “buckets” (directories)</li><li>You can store any kind of file, including text, images, videos, database files, and so on.</li><li>Each object can be up to 5 TB in size.</li><li>S3 stores objects in a container called a bucket that’s essentially a flat-file system. A bucket can store an unlimited number of objects.</li><li>When you create a bucket, you must assign it a name between 3 and 63 characters long, and the name must be <strong><em>globally unique</em></strong> across AWS.</li><li>Remember, Buckets are defined at the <strong><em>region level</em></strong>.</li><li>S3 looks like a global service but buckets are created in a region.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*ZASRB13kmWv1fyXx69Kk1w.png" /></figure><p><strong>Naming convention:</strong></p><ul><li>No uppercase</li><li>No underscore</li><li>3–63 characters long</li><li>Not an IP</li><li>Must start with lowercase letter or number</li></ul><p>Every object (files) has a key. The key is nothing but the full path as shown below →</p><ul><li>s3://my-bucket/my_file.txt</li><li>s3://my-bucket/my_folder1/another_folder/my_file.txt</li></ul><p>If you look at the key which is composed of prefix + object name. Just keys with very long names that contain slashes (“/”)</p><p><strong>Example:</strong></p><p>Let’s look at the URL:</p><p><strong><em>https://benpiper.s3.amazonaws.com/text.txt</em></strong></p><p>Here the <strong><em>object text.txt</em></strong> is stored in a <strong><em>bucket named benpiper.</em></strong></p><p>As you might expect, S3 comes with a cost. You’re not charged for uploading data to S3, but you may be charged when you download data. For example, in the US East region, you can download up to 1 GB of data per month at no charge. Beyond that, the rate is $0.09 or less per gigabyte. S3 also charges you a monthly fee based on how much data you store and the storage class you use.</p><h4>Access Permissions (S3 Security)</h4><p>S3 is storage for the internet, but that doesn’t mean everyone on the internet can read your data. By default, objects you put in S3 are inaccessible to anyone outside of your AWS account.</p><p>S3 offers the following three methods of controlling who may read, write, or delete objects stored in your S3 buckets:</p><ol><li>Bucket policies</li><li>User policies</li><li>Bucket and object access control lists</li></ol><p><strong>Bucket Policies:</strong></p><ul><li>A bucket policy is a resource-based policy that you apply to a bucket.</li><li>You can use bucket policies to grant access to all objects within a bucket or just specific objects.</li><li>You can also control which principals and accounts can read, write, or delete objects.</li><li>You can also grant anonymous read access to make an object, such as a webpage or image, available to everyone on the internet.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQkSJpTJg6_RQR85UNeTOg.png" /></figure><p><strong>User Policies:</strong></p><p>You can use IAM policies to grant IAM principals access to S3 objects. Unlike bucket policies that you apply to a bucket, you can apply user policies only to an IAM principal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4RnDf4IMIkmHc_z-H2b4w.png" /></figure><p><strong>Bucket and Object Access Control Lists(ACL):</strong></p><p>Bucket and object access control lists (ACLs) are legacy access control methods that have mostly been superseded by bucket and user policies.</p><p>Nevertheless, you can still use bucket and object ACLs to grant other AWS accounts and anonymous users access to your S3 resources.</p><p><strong>S3 Bucket Policies:</strong></p><ul><li>It is JSON based policies which will instruct whom to give access and whom not to.</li><li>It is used to Grant public access to the bucket.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*AcbdYdzQsMyWasbkErUnjQ.png" /></figure><p><strong>Bucket settings for Block Public Access:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmJ7gKdKF7ZdiND0bLDHzA.png" /></figure><ul><li>These settings were created to prevent company data leaks.</li><li>If you know your bucket should never be public, leave these on.</li><li>Can be set at the account level.</li></ul><h4>Encryption</h4><p>S3 doesn’t change the contents of an object when you upload it. That means if you upload a document containing personal information, that document is stored unencrypted.</p><p>Using appropriate access permissions can protect your data from unauthorized access, but to add an additional layer of security, you have the option of encrypting objects before storing them in S3.</p><p>This is called encryption at rest . S3 gives you the following two options for encrypting objects at rest:</p><p><strong>Server-side encryption:</strong></p><ul><li>When you create an object, S3 encrypts the object and saves only the encrypted content.</li><li>When you retrieve the object, S3 decrypts it and delivers the unencrypted object.</li><li>Server-side encryption is the easiest to implement and doesn’t require you to keep track of encryption keys. Amazon manages the keys and therefore has access to your objects.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*hfYjibXEFlfbJS8FStOfKQ.png" /></figure><p><strong>Client-side encryption:</strong></p><ul><li>You encrypt the data prior to uploading it to S3.</li><li>You must decrypt the object when you retrieve it from S3.</li><li>This option is more complicated, as you’re responsible for encryption and decryption.</li><li>If you lose the key used to encrypt an object, you won’t be able to decrypt it.</li><li>Organizations with strict security requirements may choose this option to ensure Amazon doesn’t have the ability to read their encrypted objects.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*koN-ESVkjKavAzh5Lo8SOQ.png" /></figure><h4>S3 Versioning</h4><p>To further protect against accidentally deleting or overwriting the contents of your important files, you can use versioning. To understand how versioning works, consider this example:</p><blockquote>Without versioning, if you upload an object with the same name as an existing object in the same bucket, the contents of the original object will get overwritten. But if you enable versioning on the bucket and then upload an object with the same name as an existing object, S3 will simply create a new version of that object. The original version will remain intact and available.</blockquote><p>If you delete an object in a bucket on which versioning is disabled, the contents of the object aren’t deleted. Instead, S3 adds a <strong><em>delete marker</em></strong> to the object and hides it from the S3 service console view.</p><p>Versioning is disabled by default when you create a bucket. You must explicitly enable versioning on a bucket to use it, and it applies to all objects in the bucket.</p><p>There’s no limit to the number of versions of an object you can store. You can delete versions manually or automatically using object life cycle configurations.</p><h4>S3 Access Logs</h4><ul><li>For audit purposes, you may want to log all access to S3 buckets, in that case, Access Logs were used.</li><li>Any request made to S3, from any account, authorized or denied, will be logged into another S3 bucket. And that data can be analyzed using data analysis tools</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*gQjwWoGZJoT0AoRZ7g43Ig.png" /></figure><ul><li>Very helpful to come down to the root cause of an issue, or audit usage, view suspicious patterns, etc</li></ul><h4>S3 Replication (CRR &amp; SRR)</h4><ul><li>In order to perform replication, user must enable versioning in source and destination.</li><li>There are basically two types of replications: Cross-Region Replication (CRR) &amp; Same Region Replication (SRR)</li><li>Copy process is asynchronous.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*St3h_-AW1bHAydtjZu-CHg.png" /></figure><ul><li>CRR — Use cases: compliance, lower latency access, replication across accounts</li><li>SRR — Use cases: log aggregation, live replication between production and test accounts</li></ul><h4>S3 Storage Classes</h4><p>All data is not created equal. Depending on its importance, certain fi les may require more or less availability or protection against loss than others.</p><p>Some data you store in S3 is irreplaceable, and losing it would be catastrophic. Examples of this might include digital photos, encryption keys, and medical records.</p><h4>Durability and Availability</h4><p>Objects that need to remain intact and free from inadvertent deletion or corruption are said to need high durability, which is the percent likelihood that an object will not be lost over the course of a year.</p><p>The greater the durability of the storage medium, the less likely you are to lose an object. To understand how durability works, consider the following two examples.</p><ul><li>First, suppose you store 100,000,000,000 objects on storage with 99.999999999 percent durability. That means you could expect to lose only one (0.000000001 percent) of those objects over the course of a year!</li><li>Now consider a different example. Suppose you store the same number of objects on storage with only 99.99 percent durability. You’d stand to lose 10,000,000 objects per year!</li></ul><p>Different data also has differing availability requirements. <strong><em>Availability is the percent of time an object will be available for retrieval.</em></strong></p><blockquote>For instance, a patient’s medical records may need to be available around the clock, 365 days a year. Such records would need a high degree of both durability and availability.</blockquote><p>Note that, the level of durability and availability of an object depends on its storage class. S3 offers six different storage classes at different price points.</p><p>S3 charges you a monthly storage cost based on the amount of data you store and the storage class you use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*OPUBl7AVJYX4JpSQfDGaQA.png" /></figure><p>Your choice of storage class then hinges upon your desired level of availability, which depends on how frequently you’ll need to access your files. You may find it helpful to categorize your files in terms of the following three access patterns:</p><ul><li>Frequently accessed objects</li><li>Infrequently accessed objects</li><li>A mixture of frequently and infrequently accessed objects</li></ul><h4>Storage Classes for Frequently Accessed Objects</h4><p>If you need to access objects frequently and with minimal latency, the following two storage classes fit the bill:</p><p><strong>S3 Standard — General Purposes</strong></p><ul><li>This is the default storage class.</li><li>It offers the highest levels of durability and availability, and your objects are always replicated across at least three Availability Zones in a region.</li><li>Used for frequently accessed data.</li><li>Low latency and high throughput.</li><li>Use Cases: Big Data analytics, mobile &amp; gaming applications, content distribution.</li></ul><p><strong>Reduced Redundancy</strong></p><ul><li>The REDUCED_REDUNDANCY (RRS) storage class is meant for data that can be easily replaced, if it needs to be replaced at all.</li><li>It has the lowest durability of all the classes, but it has the same availability as STANDARD.</li><li>AWS recommends against using this storage class but keeps it available for people who have processes that still depend on it.</li></ul><h4>Storage Classes for Infrequently Accessed Objects</h4><p>Two of the storage classes designed for infrequently accessed objects are suffixed with the <strong><em>“IA” initialism for “infrequent access.”</em></strong></p><p>These IA classes offer millisecond-latency access and high durability but the lowest availability of all the classes.</p><p>They’re designed for objects that are at least 128 KB in size. You can store smaller objects, but each will be billed as if it were 128 KB</p><p><strong>S3 Standard — Infrequent Access (IA):</strong></p><ul><li>Suitable for data that is less frequently accessed, but requires rapid access when needed.</li><li>99.9% Availability.</li><li>Lower cost compared to Amazon S3 Standard, but retrieval fees.</li><li>Use Cases: As a data store for disaster recovery, backups.</li></ul><p><strong>S3 One Zone — Infrequent Access (IA):</strong></p><ul><li>Same as IA but data is stored in a single AZ</li><li>99.5% Availability</li><li>Low latency and high throughput performance.</li><li>Lower cost compared to S3-IA (by 20%)</li><li>Use Cases: Storing secondary backup copies of on-premises data, or storing data you can recreate.</li></ul><p><strong>Amazon Glacier &amp; Glacier Deep Archive:</strong></p><ul><li>The GLACIER class is designed for long-term archiving of objects that rarely need to be retrieved.</li><li>Objects in this storage class are stored using the S3 Glacier service.</li><li>Unlike the other storage classes, you can’t retrieve an object in real-time. Instead, you must initiate a restore request for the object and wait until the restore is complete.</li><li>The time it takes to complete a restore depends on the retrieval option you choose and can range from 1 minute to 12 hours.</li><li>Actually it has a low cost object storage (in GB/month) meant for archiving / backup</li><li>Data is retained for the longer term (years).</li><li>Amazon Glacier Deep Archive is the most cost-effective option if you want to archive data and do not have a retrieval time requirement. You can retrieve data in 12 or 48 hours.</li></ul><p>Amazon Glacier — cheap:</p><ul><li>Expedited (1 to 5 minutes)</li><li>Standard (3 to 5 hours)</li><li>Bulk (5 to 12 hours)</li></ul><p>Amazon Glacier Deep Archive — cheapest:</p><ul><li>Standard (12 hours)</li><li>Bulk (48 hours)</li></ul><h4>Storage Class for Both Frequently and Infrequently Accessed Objects</h4><p>S3 currently offers only one storage class designed for both frequently and infrequently accessed objects: <strong>INTELLIGENT_TIERING</strong></p><ul><li>This storage class automatically moves objects to the most cost-effective storage tier based on past access patterns.</li><li>An object that hasn’t been accessed for 30 consecutive days is moved to the lower-cost infrequent access tier.</li><li>Once the object is accessed, it’s moved back to the frequent access tier.</li></ul><h4>Moving between storage classes</h4><ul><li>You can transition objects between storage classes</li><li>For infrequently accessed object, move them to STANDARD_IA</li><li>For archive objects you don’t need in real-time, GLACIER or DEEP_ARCHIVE</li><li>Moving objects can be automated using a lifecycle configuration</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*b2ufMjTRC0fjaZLqIZCEsg.png" /></figure><h4>S3 Object Lock &amp; Glacier Vault Lock</h4><p><strong>S3 Object Lock:</strong></p><ul><li>Adopt a WORM (Write Once Read Many) model.</li><li>Block an <strong><em>object version deletion</em></strong> for a specified amount of time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*jEL_AC8dDan1rhG7r9-y7w.png" /></figure><p><strong>Glacier Vault Lock:</strong></p><ul><li>Adopt a WORM (Write Once Read Many) model.</li><li><strong><em>Lock the policy for future edits</em></strong> (can no longer be changed)</li><li>Helpful for compliance and data retention</li></ul><h4>Object Life Cycle Configurations</h4><p>Because S3 can store practically unlimited amounts of data, it’s possible to run up quite a bill if you continually upload objects but never delete any. This could happen if you have an application that frequently uploads log fi les to a bucket.</p><p>You may also spend more than necessary by keeping objects in a more expensive storage class when a cheaper one would meet your needs.</p><blockquote>Object life cycle confi gurations can help you control costs by automatically moving objects to different storage classes or deleting them after a time.</blockquote><p>Object life cycle configuration rules are applied to a bucket and consist of one or both of the following types of actions:</p><p><strong>Transition actions:</strong></p><ul><li>Transition actions move objects to a different storage class once they’ve reached a certain age.</li><li>For example, you can create a rule to move objects from the STANDARD storage class to the STANDARD_IA storage class 90 days after creation.</li></ul><p><strong>Expiration actions:</strong></p><ul><li>These can automatically delete objects after they reach a certain age.</li><li>For example, you can create a rule to delete an object older than 365 days.</li><li>If you have versioning enabled on a bucket, you can create expiration actions to delete object versions of a certain age.</li><li>This allows you to take advantage of versioning without having to store endless versions of an object.</li></ul><p><strong>Note:-</strong></p><p>It’s common to use both types of actions together.</p><blockquote>For example, if you’re storing web server log files in a bucket, you may want to initially keep each log file in STANDARD storage. Once the file reaches 90 days, you can have S3 transition it to STANDARD_IA storage. Then, after 365 days in STANDARD_IA storage, the file is deleted</blockquote><h4>AWS Snow Family</h4><p>Let’s talk about buzzword, the AWS Snow Family.</p><blockquote>It is highly-secure, portable devices to <strong>collect and process data at the edge</strong>, and <strong>migrate data into and out of AWS</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*2ykSOJRLjPDPZBVr6sE_Hw.png" /></figure><p>Right now if you start migration of your data over the network, depending upon the size of the data you may face following challenges.</p><ul><li>Limited connectivity</li><li>Limited bandwidth</li><li>High network cost</li><li>Connection stability</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*03SZS-mrbaifr6WUL456pQ.png" /></figure><p><strong>Basically…</strong></p><p><strong>AWS Snow Family:</strong> It is an offline devices to perform data migrations If it takes more than a week to transfer over the network, use Snowball devices!</p><p><strong>Direct Upload Vs Snow Family Upload</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*JRJWTS8bMKl4xMEVAgbUiA.png" /><figcaption>Direct Upload</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHQckKU1ofgjRciZi2SVlw.png" /><figcaption><strong>Snow Family Upload</strong></figcaption></figure><p>Now let’s talk more about Snow Family Hardware devices.</p><p><strong>Snowball Edge (for data transfers):</strong></p><ul><li>It is a Physical data transport solution.</li><li>It can move TBs or PBs of data in or out of AWS.</li><li>Alternative to moving data over the network (and paying network fees)</li><li>It is Pay per data transfer job.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*0R3qf2No_FWYQsi5oDzOZQ.png" /></figure><ul><li>Snowball Edge Storage Optimized: 80 TB of HDD capacity for block volume and S3 compatible object storage</li><li>Snowball Edge Compute Optimized: 42 TB of HDD capacity for block volume and S3 compatible object storage</li><li>Use cases: large data cloud migrations, DC decommission, disaster recovery.</li></ul><p><strong>AWS Snowcone:</strong></p><ul><li>It is a small, portable computing, anywhere, rugged &amp; secure, withstands harsh environments.</li><li>Light (4.5 pounds, 2.1 kg)</li><li>It is used for edge computing, storage, and data transfer.</li><li>8 TBs of usable storage</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*NG6IYgyGrZ-lornkQvryCQ.png" /></figure><ul><li>Use Snowcone where Snowball does not fit (space -constrained environment)</li><li>Must provide your own battery / cables.</li><li>Can be sent back to AWS offline, or connect it to internet and use <strong><em>AWS DataSync</em></strong> to send data</li></ul><p><strong>AWS Snowmobile:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*9u-PojLfQR2Fj9lplOrVJg.png" /></figure><ul><li>Transfer exabytes of data (1 EB = 1,000 PB = 1,000,000 TBs)</li><li>Each Snowmobile has 100 PB of capacity (use multiple in parallel)</li><li>High security: temperature controlled, GPS, 24/7 video surveillance</li><li>Better than Snowball if you transfer more than 10 PB</li></ul><p><strong>AWS Snow Family for Data Migrations:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMgUioP7P00GvxY-MXzdNg.png" /></figure><p><strong>How to use AWS Snow Family?</strong></p><ul><li>Request Snowball devices from the AWS console for delivery.</li><li>Install the snowball client / AWS OpsHub on your desktop or servers.</li><li>Connect the snowball to your servers and copy files using the client.</li><li>Ship back the device when you’re done (goes to the right AWS facility).</li><li>Data will be loaded into an S3 bucket.</li><li>After that, Snowball is completely wiped.</li></ul><p><strong>What is Edge Computing?</strong></p><ul><li>Process data while it’s being created on an edge location. But what is an edge location?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*YWs1wVQmWEg-fZEQSNHWeA.png" /></figure><ul><li>Edge location is a location where data gets generated but can’t be collected with the help of regular data collection methodology.</li><li>Example: A truck on the road, a ship on the sea, a mining station underground</li><li>These locations may have:- Limited / no internet access or Limited / no easy access to computing power.</li><li>We set up a Snowball Edge / Snowcone device to do edge computing.</li><li>Use cases of Edge Computing: Preprocess data, Machine learning at the edge, Transcoding media streams etc.</li><li>Eventually (if need be) we can ship back the device to AWS (for transferring data for example)</li></ul><p><strong>Required Hardware for Edge Computing?</strong></p><p>Snowcone (smaller):</p><ul><li>2 CPUs, 4 GB of memory, wired or wireless access</li><li>USB-C power using a cord or the optional battery</li></ul><p>Snowball Edge — Compute Optimized</p><ul><li>52 vCPUs, 208 GiB of RAM</li><li>Optional GPU (useful for video processing or machine learning)</li><li>42 TB usable storage</li></ul><p>Snowball Edge — Storage Optimized</p><ul><li>Up to 40 vCPUs, 80 GiB of RAM</li><li>Object storage clustering available</li></ul><p>All above hardware can run EC2 Instances &amp; AWS Lambda functions (using AWS IoT Greengrass)</p><h4>AWS OpsHub</h4><ul><li>Historically, to use Snow Family devices, you needed a CLI (Command Line Interface tool)</li><li>Today, you can use <strong><em>AWS OpsHub (a software you install on your computer / laptop)</em></strong> to manage your Snow Family Device</li></ul><h4>Hybrid Cloud for Storage</h4><p>AWS is pushing for ”hybrid cloud”. But what exactly is the Hybrid Cloud? Take a look at below.</p><ul><li>Part of your infrastructure is on-premises</li><li>Part of your infrastructure is on the cloud</li></ul><p>This can be due to variety of reasons. Few included below:-</p><ul><li>Long cloud migrations</li><li>Security requirements</li><li>Compliance requirements</li><li>IT strategy</li></ul><p><strong>But…</strong></p><blockquote>S3 is a proprietary storage technology (unlike EFS / NFS), so how do you expose the S3 data on-premise?</blockquote><p>The AWS storage getaway is the solution.</p><h4>AWS Storage Gateway</h4><p>AWS Storage Gateway makes it easy to connect your existing on-premises servers to storage in the AWS cloud. Because it uses industry-standard storage protocols, there’s no need to install special software on your existing servers.</p><p>It bridge between on-premises data and cloud data in S3.</p><blockquote>It is a Hybrid storage service to allow on- premises to seamlessly use the AWS Cloud</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*NI6TCp9gmaKoVwX8XO2CUg.png" /></figure><p><strong>Use cases:</strong> disaster recovery, backup &amp; restore, tiered storage etc.</p><p>There are 3 types of storage gateways.</p><ul><li>File Gateway</li><li>Volume Gateway</li><li>Tape Gateway</li></ul><h4>AWS Storage Cloud-Native Options</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w6KMRlSDtgdsS2sHZsu2Yg.png" /></figure><h3>The Core Database Services</h3><p>Many applications use databases to store, retrieve, and organize data, so the type of database you choose and how you configure it have a big impact on the performance and availability of such a database-backed application.</p><p>In traditional infrastructure, organizations typically installed and configured their own database servers. For example, a business might use a Microsoft SQL Server or Oracle database to store customer information.</p><p>It’s possible to build and run your own database servers in the cloud, but AWS offers another — and for many, better — option: managed database services.</p><p>With a managed database service, you use the AWS Management Console or AWS command-line interface (CLI) to provision a database. AWS handles the installation and maintenance of the database software, as well as database backups and replication.</p><h4>Database Models</h4><p>A database can use a relational or nonrelational model. The model you choose depends on how your application needs to store, organize, and retrieve data. It’s important to understand that the needs of the application determine the database model you choose, not the other way around.</p><ul><li>Relational Database</li><li>Nonrelational Database</li></ul><p>Let’s find more information about the relational and non-relational databases.</p><p><strong>Relational Databases:</strong></p><ul><li>Relational databases have been around a long time. It looks just like Excel spreadsheets, with links between them.</li></ul><blockquote>A relational database is <strong>a type of database that stores and provides access to data points that are related to one another</strong>.</blockquote><ul><li>A relational database is analogous to a spreadsheet that contains columns and rows.</li><li>In a relational database, columns are called attributes , and rows are called records.</li><li>Both are stored in a table, and a database can contain multiple tables.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7GVZsLlxbVxuurEcpr_GmQ.png" /><figcaption>Relational Database</figcaption></figure><ul><li>An advantage of storing structured data in a relational database is that you can quickly search an entire database for specific values.</li><li>Relational databases are ideal for performing complex analytics and generating reports against large datasets.</li><li>We use the SQL language to perform queries / lookups.</li></ul><p><strong>Nonrelational (No-SQL) Databases:</strong></p><ul><li>NoSQL = non-SQL = non relational databases</li><li>Relational databases are wildly popular, but because of their restrictions, they’re also overly complex for applications that don’t need to store structured data.</li><li>Also, relational databases often perform poorly when put under the strain of handling thousands of reads or writes per second.</li><li>Nonrelational databases were developed to provide a fast alternative for applications that need to perform tens of thousands of reads or writes per second.</li></ul><blockquote>In addition to being able to handle these high transaction rates, nonrelational databases let you store data that doesn’t have a well-defined, predictable structure. Such data is often called <strong><em>unstructured data</em></strong>, in contrast to the structure imposed on data by a relational database.</blockquote><ul><li>Because of their unstructured nature, nonrelational or no-SQL databases are said to be schemaless.</li><li>Nonrelational databases also store information in tables; tables are sometimes called collections, and each row or record is called an item.</li><li>Examples: Key-value, document, graph, in-memory, search databases</li></ul><p><strong>NoSQL data example: JSON</strong></p><ul><li>JSON = JavaScript Object Notation</li><li>JSON is a common form of data that fits into a NoSQL model</li><li>Data can be nested, fields can be changed over time</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*AvYJ-Qc5AnsaTebih3KKVw.png" /></figure><h4>Amazon Relational Database Service (RDS)</h4><p>The Amazon Relational Database Service (RDS) is Amazon’s managed relational database service.</p><p>RDS lets you provision a number of popular relational database management systems (RDBMSs) including</p><ul><li>Microsoft SQL Server,</li><li>Oracle,</li><li>MySQL,</li><li>PostgreSQL,</li><li>Aurora (AWS Proprietary database).</li></ul><p>You can always install and configure your own database server on an EC2 instance. But RDS offers several advantages over this →</p><ul><li>Automated provisioning, OS patching.</li><li>Continuous backups and restore to specific timestamp (Point in Time Restore)!</li><li>Monitoring dashboards</li><li>Read replicas for improved read performance</li><li>Multi AZ setup for DR (Disaster Recovery)</li><li>Scaling capability (vertical and horizontal)</li></ul><p>Note:- You can’t SSH into your instances.</p><p><strong>RDS Solution Architecture:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GrpDqRtFVN8i8xiYomSZUQ.png" /></figure><p><strong>Amazon Aurora:</strong></p><ul><li>Aurora is a proprietary technology from AWS (not open sourced)</li><li>PostgreSQL and MySQL are both supported as Aurora DB</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*3bZTiswt7AOAfjxYu-0LiQ.png" /></figure><blockquote>Aurora is <strong>“AWS cloud optimized”</strong> and claims <strong>5x</strong> performance improvement over <strong>MySQL</strong> on RDS, over <strong>3x</strong> the performance of <strong>Postgres </strong>on RDS</blockquote><ul><li>Aurora storage automatically grows in increments of 10GB, up to 64 TB.</li><li>Aurora costs more than RDS (20% more) — but is more efficient.</li><li>It’s not available in the free tier.</li></ul><p><strong>RDS Deployments:</strong></p><ol><li>Read Replicas</li><li>Multi-AZ</li><li>Multi-Region</li></ol><p>Let’s learn about these two deployments.</p><p><strong>Read Replicas:</strong></p><ul><li>Scale the read workload of your DB</li><li>Can create up to 5 Read Replicas</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*4767d7iA8u7TBU4TjOfGvw.png" /></figure><ul><li>When you have multiple applications then it is useful to creates Read Replica so that your applications read operation will be faster and much more efficient.</li><li>In case of writing, data is only written to the main DB.</li></ul><p><strong>Multi-AZ:</strong></p><ul><li>The concept of Multi-AZ is used when the event of Failover in case of AZ outage.</li><li>Data is only read/written to the main database.</li><li>We can only use one AZ as failover.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*LDUIb4-kpN906NSXY0y9aA.png" /></figure><ul><li>The failover DB is only gets activated in case of failure of main DB.</li></ul><p><strong>Multi-Region:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vdeJZ4iXjmxE8IztkmB8zg.png" /></figure><ul><li>Disaster recovery in case of region issue</li><li>Local performance for global reads</li></ul><h4>Amazon ElastiCache</h4><ul><li><a href="https://aws.amazon.com/elasticache/">Amazon ElastiCache</a> is a cache-as-a-service developed and distributed by Amazon Web Services (AWS).</li><li>These caches are in-memory databases with high performance, low latency.</li><li>Amazon ElastiCache relies on two different caching engines — Memcached and Redis.</li><li>It helps reduce load off databases for read-intensive workloads.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0PHk_oIsP4c5nPBR2OfYg.png" /></figure><h4>DynamoDB</h4><ul><li>DynamoDB is Amazon’s managed non-relational database service. It’s designed for highly transactional applications that need to read from or write to a database tens of thousands of times a second.</li><li>It is a NoSQL database — not a relational database.</li><li>It is fully Managed Highly available with replication across 3 AZ.</li><li>It is distributed “serverless” database.</li><li>Fast and consistent in performance.</li><li><strong><em>Single-digit millisecond latency </em></strong>— low latency retrieval</li><li>It can be Integrated with IAM for security, authorization and administration</li><li>Low cost and auto-scaling capabilities</li><li>DynamoDB is a key/value database.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*ZVRgbks22txtkVhPutwoUw.png" /></figure><p><strong>DAX(DynamoDB Accelerator):</strong></p><ul><li>It is a fully managed in-memory cache for DynamoDB.</li><li>10x performance improvement: <strong><em>single-digit millisecond latency</em></strong> to <strong><em>microseconds latency</em></strong> — when accessing your DynamoDB tables.</li><li>Secure, highly scalable &amp; highly available.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*6A8UNhI8qyqqSbF-UvXDNQ.png" /></figure><p><strong>ElastiCache Vs DAX:</strong></p><blockquote>DAX is only used for and is integrated with DynamoDB, while ElastiCache can be used for other databases.</blockquote><p><strong>Global Tables:</strong></p><ul><li>Global table is nothing but to make a DynamoDB table accessible with low latency in multiple-regions.</li><li>Active-Active replication (read/write to any AWS Region)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13AGiKosfJNNncHFnZKF1Q.png" /></figure><h4>Redshift</h4><ul><li>Redshift is a database that is based on PostgreSQL, but it’s not used for OLTP.</li><li>It’s <strong>OLAP </strong>— Online Analytical Processing (analytics and data warehousing)</li><li>Load data once every hour, not every second</li><li>10x better performance than other data warehouses, scale to PBs of data.</li><li>Columnar storage of data (instead of row-based)</li><li>Massively Parallel Query Execution (MPP), highly available</li><li>Pay as you go based on the instances provisioned</li><li>It has a SQL interface for performing the queries</li><li>We can integrate BI tools such as s AWS Quicksight or Tableau with it.</li></ul><blockquote>So anytime in the exam you are seeing the database needs to be a warehouse and to do analytics on it, then Redshift is going to be your answer.</blockquote><h4>Amazon EMR</h4><ul><li>EMR stands for “Elastic MapReduce”</li><li>EMR helps creating Hadoop clusters (Big Data) to analyze and process vast amount of data.</li><li>The clusters can be made of hundreds of EC2 instances</li><li>It also supports Apache Spark, HBase, Presto, Flink, etc.</li><li>EMR takes care of all the provisioning and configuration</li><li>Use cases: data processing, machine learning, web indexing, big data</li></ul><blockquote>So from an exam perspective, any time you see Hadoop cluster, think no more, it’s going to be Amazon EMR.</blockquote><h4>Amazon Athena</h4><ul><li>It is a serverless query service to analyze data stored in Amazon S3.</li><li>It uses standard SQL language to query the files.</li><li>Supports CSV, JSON, ORC, Avro, and Parquet (built on Presto)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*veNJn28feT6uxASAMKKGfQ.png" /></figure><ul><li>Pricing: $5.00 per TB of data scanned</li><li>Use compressed or columnar data for cost-savings (less scan)</li><li>Use cases: Business intelligence / analytics / reporting, analyze &amp; query VPC Flow Logs, ELB Logs, CloudTrail trails, etc’</li></ul><blockquote>So from an exam perspective, whenever you see <strong>serverless </strong>analyze data in <strong>S3 </strong>use SQL, then think <strong>Amazon Athena</strong>.</blockquote><h4>Amazon QuickSight</h4><ul><li>It’s Serverless machine learning-powered business intelligence service to create interactive dashboards.</li><li>Fast, automatically scalable, embeddable, with per-session pricing</li><li>Use cases: Business analytics, Building visualizations, Perform ad-hoc analysis, Get business insights using data etc.</li><li>It can be integrated with RDS, Aurora, Athena, Redshift, S3</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*3W7lET_GFwmooOvCcOelWw.png" /></figure><h4>DocumentDB</h4><ul><li>Aurora is an “AWS-implementation” of PostgreSQL / MySQL. Likewise DocumentDB is the same for MongoDB (which is a NoSQL database)</li><li>MongoDB is used to store, query, and index JSON data.</li><li>It uses the similar “deployment concepts” as Aurora.</li><li>Fully Managed, highly available with replication across 3 AZ</li><li>Automatically scales to workloads with millions of requests per seconds</li></ul><blockquote>So at the exam, if you see anything related to MongoDB, think DocumentDB, or if you see anything relate to NoSQL databases, think DocumentDB and also DynamoDB.</blockquote><h4>Amazon Neptune</h4><ul><li>It is fully managed graph database.</li><li>A popular graph dataset would be a social network: Users have friends, Posts have comments, Comments have likes from users, Users share and like posts.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*gLvHUV7e2MR-pgsYw5MTuw.png" /></figure><ul><li>Highly available across 3 AZ, with up to 15 read replicas.</li><li>Build and run applications working with highly connected datasets — optimized for these complex and hard queries</li><li>Can store up to billions of relations and query the graph with milliseconds latency.</li><li>Great for knowledge graphs (Wikipedia), fraud detection, recommendation engines, social networking.</li></ul><blockquote>So, coming from an exam perspective, anytime you see anything related to graph databases, think no more than Neptune.</blockquote><h4>Amazon QLDB</h4><ul><li>QLDB stands for ”Quantum Ledger Database”</li><li>A ledger is a book recording financial transactions.</li><li>Fully Managed, Serverless, High available, Replication across 3 AZ.</li><li>It is used to review history of all the changes made to your application data over time.</li><li>It is an immutable system: no entry can be removed or modified, cryptographically verifiable.</li><li>Difference with Amazon Managed Blockchain: no decentralization component, in accordance with financial regulation rules.</li></ul><blockquote>Anytime you see financial transactions and ledger, think QLDB.</blockquote><h4>Amazon Managed Blockchain</h4><ul><li>Blockchain makes it possible to build applications where multiple parties can execute transactions without the need for a trusted, central authority.</li><li>Amazon Managed Blockchain is a managed service to join public blockchain networks or create your own scalable private network.</li><li>Compatible with the frameworks Hyperledger Fabric &amp; Ethereum</li></ul><blockquote>So from an exam perspective, if you see anything related to Blockchains or Hyperledger fabric or Ethereum, you have to think Amazon managed Blockchain.</blockquote><h4>AWS Glue</h4><ul><li>It is managed <strong><em>extract, transform, and load (ETL)</em></strong> service.</li><li>It is useful to prepare and transform data for analytics.</li><li>It is a fully serverless service.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Csz6LNliPpTDFbICFJcVw.png" /></figure><h4>DMS (Database Migration Service)</h4><ul><li>Quickly and securely migrate databases to AWS, resilient, self healing</li><li>The source database remains available during the migration</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*_vPMRxytg6C18aKWpCbQ_A.png" /></figure><p>It supports:</p><ul><li>Homogeneous migrations: example, Oracle to Oracle.</li><li>Heterogeneous migrations: example, Microsoft SQL Server to Aurora</li></ul><blockquote>So any time in the exam you see migration of a database, DMS is going to be the answer for it.</blockquote><h3>AWS Other Compute Services</h3><p>In this section we will learn about the other compute services (Apart from core compute services like EC2) that are managed by AWS.</p><p>Let’s start with understanding about docker.</p><h4>Docker</h4><p>Let me define a docker for you -</p><blockquote>Docker is a software development platform to deploy apps. These Apps are packaged in <strong>containers </strong>that can be run on literally any OS</blockquote><p><strong>Benefits of Dockers:</strong></p><ul><li>Apps runs on any machine</li><li>No compatibility issues</li><li>Predictable behavior</li><li>Easier to maintain and deploy</li><li>Works with any language, any OS, any technology</li><li>Scale containers up and down very quickly (seconds)</li></ul><p><strong>Where Docker images are stored?</strong></p><ul><li>Dockers generally works on something called the docker images. These images are stored in Docker Repositories.</li><li>There is a public docker repository → <a href="https://hub.docker.com/">https://hub.docker.com/</a></li><li>Here you will find the docker images with any technology or os.</li><li>Private Docker Repository → <strong><em>Amazon ECR</em></strong> (Elastic Container Registry) where docker images will be stored.</li></ul><p><strong>Docker Vs Virtual Machines</strong></p><ul><li>Docker is ”sort of” a virtualization technology, but not exactly</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVF6aJ68mNQQFgGg7ERQpg.png" /></figure><ul><li>In docker, we don’t need to have Guest OS. Many containers will run on Docker Daemon.</li></ul><h4>Amazon ECS (Elastic Container Service)</h4><ul><li>ECS = Elastic Container Service</li><li>It is used to <strong><em>launch Docker Containers</em></strong> on AWS</li><li>You must provision &amp; maintain the infrastructure (the EC2 instances)</li><li>It has an integrations with the Application Load Balancer</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*KkBOvHTo70w8lPepU2SwmA.png" /></figure><h4>Fargate</h4><ul><li>It is also used to launch Docker Containers on AWS.</li><li>The main difference between ECS and farmgate is, here do not provision the infrastructure (no EC2 instances to manage) — simpler.</li><li>Therefore it is a serverless offering.</li><li>AWS just runs containers for you based on the CPU / RAM you need.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*wlwzIfe501lo_FWPVVyk4g.png" /></figure><h4>Amazon ECR (Elastic Container Repository)</h4><ul><li>It is a private Docker Registry on AWS</li><li>This is where you <strong><em>store your Docker images</em></strong> so they can be run by ECS or Fargate</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*P_s_kul48bJC_sCkCR2rhg.png" /></figure><h4>What’s serverless?</h4><ul><li>Serverless is a new paradigm in which the developers don’t have to manage servers anymore.</li><li>They just need to deploy code or functions.</li><li>Serverless == FaaS (Function as a Service)</li><li>Serverless was pioneered by <strong><em>AWS Lambda</em></strong> but now also includes anything that’s managed: “databases, messaging, storage, etc.”</li></ul><blockquote><strong><em>Serverless does not mean there are no servers… it means you just don’t manage / provision / see them</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njnik5H4vI0QX5cOImyciA.png" /><figcaption>Serverless Services by AWS</figcaption></figure><h4>AWS Lambda</h4><p>AWS Lambda is an event-driven, <strong><em>serverless computing platform</em></strong> provided by Amazon as a part of Amazon Web Services.</p><p>Therefore you don’t need to worry about which AWS resources to launch, or how well you manage them. Instead, you need to put the code on Lambda, and it runs.</p><p>In AWS Lambda the code is executed based on the response of events in AWS services such as add/delete files in S3 bucket, HTTP request from Amazon API gateway, etc. However, Amazon Lambda can only be used to execute background tasks.</p><p><strong>Why AWS Lambda (Serverless Computing Service)?</strong></p><p><strong><em>Amazon EC2:</em></strong></p><ul><li>It’s not serverless. Basically virtual servers are in cloud.</li><li>Limited by RAM and CPU</li><li>It needs to run continuously</li><li>Here scaling means intervention to add / remove servers.</li></ul><p><strong><em>Amazon Lambda:</em></strong></p><ul><li>It has a <strong><em>Virtual functions</em></strong> — no servers to manage.</li><li>Limited by time — It is used for short executions.</li><li>It doesn’t run continuously but it runs on-demand.</li><li>Scaling in AWS lambda is automated.</li></ul><p><strong>Benefits of AWS Lambda:</strong></p><ul><li>Easy Pricing: Pay per request and compute time.</li><li>Free tier gets 1,000,000 AWS Lambda requests and 400,000 GBs of compute time.</li><li>It can be integrated with the whole AWS suite of services.</li><li>It’s Event-Driven which means functions get invoked by AWS when needed.</li><li>It’s integrated with many programming languages.</li><li>We can do easy <strong><em>monitoring through AWS CloudWatch.</em></strong></li><li>Easy to get more resources per functions (up to 10GB of RAM!)</li><li>Increasing RAM will also improve CPU and network!</li></ul><p><strong>AWS Lambda language support:</strong></p><ul><li>Node.js (JavaScript)</li><li>Python</li><li>Java</li><li>C# (.NET Core)</li><li>Golang</li><li>C# / Powershell</li><li>Ruby</li><li>Custom Runtime API (community supported, example Rust)</li></ul><p><strong>Lambda Container Image:</strong></p><p>There is something called lambda container images. But it is not used widely. The container image must implement the Lambda Runtime API. Therefore ECS / Fargate is preferred for running arbitrary Docker images.</p><p><strong>Lambda Examples:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X60olGNWOvTImP6qXkE1HA.png" /><figcaption><strong><em>Serverless Thumbnail creation (</em></strong>thumbnail is a smaller version of the image)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5C32Vhs65D4SGfqobq5zTQ.png" /><figcaption>Serverless CRON Job</figcaption></figure><p><strong>CRON </strong>allows you to <strong><em>define a schedule</em></strong>. For example, every hour, every day or every Monday and based on that schedule to run a script. And by default, a CRON job is run on an Linux AMI.</p><p><strong>AWS Lambda Pricing:</strong></p><ul><li>Pay per calls.</li><li>First 1,000,000 requests are free</li><li>$0.20 per 1 million requests thereafter ($0.0000002 per request)</li><li>It also can be priced based on Pay per duration.</li><li>It is usually <strong><em>very cheap</em></strong> to run AWS Lambda so it’s very popular</li></ul><h4>Amazon API Gateway</h4><ul><li>The Amazon API Gateway is used to build the serverless API.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QH52OaaDF-lYs4fbhtoKdQ.png" /></figure><ul><li>Fully managed service for developers to easily create, publish, maintain, monitor, and secure APIs</li><li>It is Serverless and scalable</li><li>It supports Supports <strong><em>RESTful APIs</em></strong> and <strong><em>WebSocket APIs</em></strong></li><li>Support for security, user authentication, API throttling, API keys, monitoring.</li></ul><h4><strong>AWS Batch</strong></h4><ul><li>Fully managed batch processing at any scale</li><li>Efficiently run 100,000s of computing batch jobs on AWS</li><li>A “batch” job is a job with a start and an end (opposed to continuous)</li><li>Batch will dynamically launch EC2 instances or Spot Instances</li><li>AWS Batch provisions the right amount of compute / memory</li><li>You submit or schedule batch jobs and AWS Batch does the rest!</li><li>Batch jobs are defined as Docker images and run on ECS</li><li>Helpful for cost optimizations and focusing less on the infrastructure</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tvBvBlPW3g-olvsITD8MPg.png" /></figure><h4>Batch vs Lambda</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R992WJX_xkvGWZcWzl6Naw.png" /></figure><h4>Amazon Lightsail</h4><ul><li>Amazon Lightsail is a standalone service from AWS</li><li>It provides virtual servers, storage, databases, and networking</li><li>Low &amp; predictable pricing</li><li>Simpler alternative to using EC2, RDS, ELB, EBS, Route 53</li><li>Great for people with <strong><em>little cloud experience!</em></strong></li><li>Can set up notifications and monitoring of your Lightsail resources</li><li>Use cases: Simple web applications, Websites (templates for WordPress, Magento, Plesk, Joomla), Dev / Test environment.</li><li>It has a high availability but no auto-scaling, limited AWS integrations.</li></ul><blockquote>From the exam perspective, if you see someone that has <strong>no cloud experience</strong> and <strong>need to get started quickly with a low and predictable pricing</strong> without configuring things much that will be Lightsail, <strong>otherwise Lightsail will almost always be a wrong answer. (It’s distractor)</strong></blockquote><p>Amazon Lightsail is designed to be the easiest way to launch and manage a virtual private server with AWS. Lightsail plans include everything you need to jumpstart your project — a virtual machine, SSD- based storage, data transfer, DNS management, and a static IP address — for a low, predictable price. It can be used to create a simple web application, a website or a dev/test environment.</p><h3>Automating Your AWS Workloads</h3><p>Automation is a best practice when it comes to designing architectures in the cloud. Automation allows common tasks to be repeated faster than doing them manually. These tasks can be simple and routine, such as installing the latest security patches on an EC2 instance running Linux. Or they can be complex, perhaps creating an entirely new and pristine AWS environment containing dozens of EC2 instances running a multitier, database-backed web application behind an application load balancer.</p><p>Whatever the task, whether simple or complex, automation confers several benefits, including the following:</p><ul><li>Rapid testing and experimentation</li><li>Reducing expenses</li><li>Minimizing human error</li><li>Rolling back changes safely and completely</li></ul><p>Some have a misconception of automation as replacing a human with a machine. But the truth is that automation requires a tremendous amount of human intelligence and ongoing effort.</p><p>Ultimately, automation is about increasing the capacity of the people doing the work so that they can spend more time being productive and less time fixing problems.</p><p>You can deploy automation at different levels of your AWS environment, picking and choosing where it makes the most sense for you.</p><p>You may find it helpful to approach automation in two different ways: imperative and declarative.</p><p><strong>The Imperative Approach</strong></p><ul><li>The most common example of automation using an imperative approach is <strong><em>scripting</em></strong>, wherein you use a scripting language such as Bash or PowerShell, or even a tool such as the AWS Command Line Interface (CLI), to provide the explicit steps necessary to carry out a task.</li><li>For example, you may write a Bash script to install a web server on an instance and then copy HTML files from an S3 bucket to a particular directory on the instance. <strong><em>The imperative approach focuses on the specific step-by-step operations required to carry out a task.</em></strong></li></ul><p><strong>The Declarative Approach</strong></p><ul><li>Using a declarative approach, <strong><em>you write code that declares the desired result of the task, rather than how to carry it out.</em></strong></li><li>For example, rather than using the AWS CLI to create a new virtual private cloud (VPC) and subnets, you could write declarative code that simply defines the configuration for the VPC and subnets.</li><li>This approach naturally requires some intelligent software to figure out the operations required to achieve the desired resultS.</li><li>Example: CloudFormation</li></ul><p><strong>Infrastructure as Code</strong></p><ul><li>Using code to define your infrastructure and configurations is commonly called the infrastructure as code (IaC) approach.</li><li>Defining IaC is a fundamental element of automation in the cloud.</li><li>Because automation relies on code being executed by a machine, it reduces the risk of human error inherent in carrying out the same work manually.</li></ul><h4>CloudFormation</h4><p>CloudFormation automatically creates and configures your AWS infrastructure from code that defines the resources you want it to create and how you want those resources configured.</p><p>Basically, you write code containing the specifics of the AWS resources you want and present that code to CloudFormation, and it builds and configures those resources on your behalf in a matter of seconds.</p><p>CloudFormation use something called Templates to carry out the cloud formation tasks.</p><p><strong>Templates:</strong></p><ul><li>Templates contain a description of the AWS resources you want CloudFormation to create, so they simultaneously function as infrastructure documentation.</li><li>Templates use the proprietary CloudFormation language, which can be written in <strong><em>JavaScript Object Notation (JSON) or YAML format</em></strong>.</li><li>You can use the same template to build AWS infrastructure repeatedly, such as for development or testing</li><li>You can also use a single template to build many similar environments. For example, you can use one template to create identical resources for both production and test environments.</li></ul><p><strong>Stack:</strong></p><ul><li>To provision resources from a template, you must specify a stack name that’s unique within your account.</li><li>A stack is a container that organizes the resources described in the template.</li><li>The purpose of a stack is to collectively manage related resources.</li><li>If you delete a stack, CloudFormation automatically deletes all of the resources in it.</li><li>This makes CloudFormation perfect for test and development environments that need to be provisioned as pristine and then thrown away when no longer needed.</li><li>Deleting a stack helps ensure that all resources are deleted and that no forgotten resources are left lingering, running up charges.</li></ul><blockquote>One of the fundamental principles of good cloud design is to make your test environments mirror your production environments as closely as possible. CloudFormation makes this not only possible but almost trivially easy!</blockquote><p><strong>Stack Updates:</strong></p><ul><li>You can have CloudFormation change individual resources in a stack. Just modify the template to delete, modify, or add resources, and then instruct CloudFormation to perform a stack update using the template.</li><li>CloudFormation will automatically update the resources accordingly.</li><li>Alternatively, you can create a changeset. Make the desired changes to your template, and then have CloudFormation generate a changeset based on the template.</li><li>CloudFormation will let you review the specific changes it will make, and then you can decide whether to execute those changes or leave everything as is.</li></ul><p><strong>Tracking Stack Changes:</strong></p><ul><li>Each stack contains a timestamped record of events that occur within the stack, including when resources were created, updated, or deleted.</li><li>This makes it easy to see all changes made to your stack.</li></ul><p><strong>CloudFormation vs. the AWS CLI:</strong></p><ul><li>You can script AWS CLI commands to create resources fast and automatically, but those resources won’t be kept in a stack, so you won’t get the same advantages that stacks provide.</li><li>When you’re using the AWS CLI, you can’t update your resources as easily as you can with CloudFormation.</li><li>With CloudFormation, you simply adjust the template or parameters to change your resources, and CloudFormation figures out how to perform the changes.</li></ul><p>CloudFormation template, you say:</p><ul><li>I want a security group.</li><li>I want two EC2 instances using this security group.</li><li>I want an S3 bucket.</li><li>I want a load balancer (ELB) in front of these machines.</li></ul><p><strong>Benefits of AWS CloudFormation:</strong></p><p><strong><em>Infrastructure as code:</em></strong></p><p>No resources are manually created, which is excellent for control. Changes to the infrastructure are reviewed through code.</p><p><strong><em>Costs:</em></strong></p><ul><li>Each resources within the stack is tagged with an identifier so you can easily see how much a stack costs you.</li><li>You can estimate the costs of your resources using the CloudFormation template.</li></ul><p><strong><em>Productivity:</em></strong></p><ul><li>Ability to destroy and re-create an infrastructure on the cloud on the fly</li><li>Automated generation of Diagram for your templates!</li></ul><p><strong><em>Don’t re-invent the wheel:</em></strong></p><ul><li>Leverage existing templates on the web</li><li>Leverage the documentation</li></ul><p><strong><em>Supports (almost) all AWS resources:</em></strong></p><ul><li>Everything we’ll see in this course is supported.</li><li>You can use “custom resources” for resources that are not supported.</li></ul><h4>AWS Cloud Development Kit (CDK)</h4><ul><li>With the help of CDK, we can define your cloud infrastructure using a familiar language.</li><li>Example: JavaScript/TypeScript, Python, Java, and .NET</li><li>The code is “compiled” into a CloudFormation template (JSON/YAML)</li></ul><h4>AWS Elastic Beanstalk</h4><ul><li>Elastic Beanstalk is a <strong><em>developer-centric view of deploying an application</em></strong> on AWS.</li></ul><blockquote>Elastic Beanstalk is a platform within AWS that is used for deploying and scaling web applications.</blockquote><ul><li>It uses all the component’s we’ve seen before: EC2, ASG, ELB, RDS, etc</li><li>But it’s all in one view that’s easy to make sense of. We still have full control over the configuration</li><li><strong>Beanstalk = Platform as a Service (PaaS)</strong></li><li>Beanstalk is free but you pay for the underlying instances.</li><li>AWS Elastic Beanstalk allows you to quickly deploy applications and services without having to worry about configuring underlying resources, services, operating systems or web servers.</li><li>Elastic Beanstalk takes care of the hosting infrastructure, coding language interpreter, operating system, security, HTTPS service and application layer. <strong><em>All you need to worry about is writing your code</em></strong>.</li><li>You can develop code in a number of languages which is then zipped up and the zip file is used when instantiating a new elastic beanstalk instance.</li><li>Supported language platforms include: Java, Node.Js, Python, JS, C#, Ruby etc.</li></ul><p><strong>Health Monitoring with Elastic Beanstalk:</strong></p><ul><li>Health agent pushes metrics to CloudWatch</li><li>Checks for app health, publishes health events</li></ul><h4>AWS Developer Tools</h4><p>The AWS Developer Tools are a collection of tools designed to help application developers develop, build, test, and deploy their applications onto EC2 and on-premises instances.</p><p>These tools facilitate and automate the tasks that must take place to get a new application revision released into production.</p><p>However, the AWS Developer Tools enable more than just application development. You can use them as part of any IaC approach to automate the deployment and configuration of your AWS infrastructure.</p><p>Tools Includes:-</p><ul><li>CodeCommit</li><li>CodeBuild</li><li>CodeDeploy</li><li>CodePipeline</li></ul><p>Lets learn more about these tools.</p><p><strong>CodeCommit:</strong></p><ul><li>Before pushing the application code to servers, it needs to be stored somewhere.</li><li>Developers usually store code in a repository, using the Git technology.</li><li>A famous public offering is GitHub, AWS’ competing product is CodeCommit.</li></ul><p><strong>CodeBuild:</strong></p><ul><li>Code building service in the cloud (name is obvious)</li><li>CodeBuild is a fully managed build service. A build is a set of actions performed on source code to get it ready for deployment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*b6d_BpwELNO1shDEzQVtYg.png" /></figure><ul><li>A build could include testing the code for errors or transforming it into a machine-readable language, but the specifi c build actions depend on the application.</li><li>It is fully managed, serverless service.</li><li>Pay-as-you-go pricing — only pay for the build time</li></ul><p><strong>CodeDeploy:</strong></p><ul><li>CodeDeploy can automatically deploy applications to EC2 instances, the Elastic Container Service (ECS), Lambda, and even on-premises servers.</li><li>This service is used when we want to deploy our application automatically.</li><li>It works with EC2 Instances and also works with On-Premises Servers (Hybrid service)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*KESDgLyeMS9dQadGa2f8lg.png" /></figure><p><strong>CodePipeline:</strong></p><ul><li>CodePipeline helps orchestrate and automate every task required to move software from development to production.</li><li>It works by taking your source code and processing it through a series of stages, up to and including a deployment stage. In between the required source and deployment stages, you can add other stages also, such as a build stage that runs tests, or an approval stage that requires manual approval before deployment.</li><li>Code =&gt; Build =&gt; Test =&gt; Provision =&gt; Deploy</li><li>It served basis for CICD (Continuous Integration &amp; Continuous Delivery)</li><li>It’s fully managed, compatible with CodeCommit, CodeBuild, CodeDeploy, Elastic Beanstalk, CloudFormation, GitHub, 3rd-party services (GitHub…) &amp; custom plugin</li><li>Fast delivery &amp; rapid updates</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q49d-XqfUWjbBd5WR2F91A.png" /></figure><p><strong>CodeArtifact:</strong></p><ul><li>Software packages depend on each other to be built (also called code dependencies)</li><li>Storing and retrieving these dependencies is called artifact management.</li><li>Traditionally you need to setup your own artifact management system but AWS provides something called CodeArtifact which is a secure, scalable, and cost-effective artifact management for software development.</li><li>It works well with common dependency management tools such as Maven, Gradle, npm, yarn, twine, pip, and NuGet.</li><li>Developers and CodeBuild can then retrieve dependencies straight from CodeArtifact</li></ul><blockquote>So from an exam perspective, CodeArtifact is going to be very helpful, if your team needs a artifact management system or a place to store their code dependencies.</blockquote><p><strong>CodeStar:</strong></p><ul><li>Unified UI to easily manage software development activities in one place.</li><li>“Quick way” to get started to correctly set-up CodeCommit, CodePipeline, CodeBuild, CodeDeploy, Elastic Beanstalk, EC2, etc</li><li>Can edit the code ”in-the-cloud” using <strong>AWS Cloud9</strong> (IDE for Cloud)</li></ul><p><strong>AWS Cloud9:</strong></p><ul><li>AWS Cloud9 is a cloud IDE (Integrated Development Environment) for writing, running and debugging code</li><li>“Classic” IDE (like IntelliJ, Visual Studio Code…) are downloaded on a computer before being used.</li><li>A cloud IDE can be used within a web browser, meaning you can work on your projects from your office, home, or anywhere with internet with no setup necessary.</li><li>AWS Cloud9 also allows for code collaboration in real -time (pair programming)</li></ul><h4>Configuration Management</h4><p>Configuration management is an approach to ensuring accurate and consistent configuration of your systems.</p><p>While automation is concerned with carrying out tasks, confi guration management is primarily concerned with enforcing and monitoring the internal configuration state of your instances to ensure they’re what you expect.</p><p>As with automation in general, configuration management tools use either imperative or declarative approaches.</p><p>AWS offers both approaches using two tools to help you achieve configuration management of your EC2 and on-premises instances:</p><ol><li>System Manager</li><li>OpsWorks</li></ol><p><strong>AWS Systems Manager (SSM):</strong></p><ul><li>Systems Manager uses the imperative approach (step-by-step) to get your instances and AWS environment into the state that you want.</li><li>It helps you you manage your EC2 and On-Premises systems at scale. Therefore it would another Hybrid AWS service.</li><li>It sends you operational insights about the state of your infrastructure.</li><li>It is suite of 10+ products.</li><li>Works for both Windows and Linux OS</li></ul><p>Features of SSM:</p><ul><li>Patching automation for enhanced compliance</li><li>Run commands across an entire fleet of servers</li><li>Store parameter configuration with the SSM Parameter Store</li></ul><p>How Systems Manager works?</p><ul><li>We need to install the SSM agent onto the systems we control</li><li>It’s installed by default on Amazon Linux AMI &amp; some Ubuntu AMI</li><li>If an instance can’t be controlled with SSM, it’s probably an issue with the SSM agent!</li><li>Thanks to the SSM agent, we can run commands, patch &amp; configure our servers</li></ul><blockquote>So, from an exam perspective, anytime you see a way to patch your fleet of EC2 instances or On-Premises servers, you have to think about SSM, or if you wanted to run a command consistently</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*Epq3rfQtGkQbTpi9qM8YaA.png" /></figure><p><strong>AWS OpsWorks:</strong></p><p>OpsWorks is a set of three different services that let you take a declarative approach to configuration management.</p><p>As explained earlier, using a declarative approach requires some intelligence to translate declarative code into imperative operations.</p><p>OpsWorks uses two popular configuration management platforms that fulfill this requirement:</p><ol><li>Chef</li><li>Puppet</li></ol><p>Puppet and Chef are popular configuration management platforms that can configure operating systems, deploy applications, create databases, and perform just about any configuration task you can dream of, all using code.</p><p>Both Puppet and Chef are widely used for on-premises deployments, but OpsWorks brings their power to AWS as the OpsWorks managed service.</p><blockquote>In the exam: Chef or Puppet needed =&gt; AWS OpsWorks</blockquote><h3>Global Infrastructure</h3><h4>Why make a global application?</h4><p>A global application is an application deployed in multiple geographies. On AWS: this could be Regions and / or Edge Locations.</p><p><strong>Decreased Latency:</strong></p><ul><li>With the global application, we can observe the decreased latency. (Latency is the time it takes for a network packet to reach a server)</li><li>It takes time for a packet from Asia to reach the US.</li><li>Deploy your applications closer to your users to decrease latency, better experience.</li></ul><p><strong>Disaster Recovery (DR):</strong></p><ul><li>If an AWS region goes down (earthquake, storms, power shutdown, politics)</li><li>You can fail-over to another region and have your application still working</li><li>A DR plan is important to increase the availability of your application</li></ul><p><strong>Attack protection: </strong>The distributed global infrastructure is harder to attack</p><h4>Global AWS Infrastructure</h4><ul><li><strong>Regions: </strong>For deploying applications and infrastructure</li><li><strong>Availability Zones:</strong> Made of multiple data centers.</li><li><strong>Edge Locations (Points of Presence):</strong> For content delivery as close as possible to users</li></ul><h4>Global Applications in AWS</h4><p><strong>Global DNS: Route 53</strong></p><ul><li>Great to route users to the closest deployment with least latency</li><li>Great for disaster recovery strategies</li></ul><p><strong>Global Content Delivery Network (CDN): CloudFront</strong></p><ul><li>Replicate part of your application to AWS Edge Locations — decrease latency</li><li>Cache common requests — improved user experience and decreased latency</li></ul><p><strong>S3 Transfer Acceleration: </strong>Accelerate global uploads &amp; downloads into Amazon S3</p><p><strong>AWS Global Accelerator: </strong>Improve global application availability and performance using the AWS global network</p><p>Now let’s look at these one by one in more details.</p><h4>Amazon Route 53</h4><ul><li>Route 53 is Amazon’s global Domain Name System (DNS) service.</li><li>The primary purpose of DNS is to translate human-readable domain names (such as example.com) into IP addresses.</li><li>DNS is a collection of rules and records which helps clients understand how to reach a server through URLs.</li></ul><p><strong>How it works?</strong></p><blockquote>when you enter the domain name example.com into your web browser, your computer sends out a query to its configured DNS server asking for the IP address of that domain. The DNS server then sends the query to the domain’s authoritative DNS server — the one that’s in charge of the example.com domain name. The authoritative DNS server responds with the IP address for example.com. This process of translating a domain name to an IP address is called name resolution.</blockquote><p><strong>Resource Records:</strong></p><ul><li>Name resolution goes beyond just mapping domain names to IP addresses. DNS can store mappings for different types of data, including IPv6 addresses, mail servers, and even arbitrary text.</li><li>When you send an email to someone, DNS provides the lookup mechanism to ensure it gets routed to the correct mail server for that domain.</li><li>For DNS to work, someone must first define some <strong><em>resource records</em></strong> for a domain. A resource record consists of several fields, but the most important are the name, type, and value.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*M5yyyzeKawLHH1NWsqR5rg.png" /></figure><p><strong>Domain Name Registration:</strong></p><ul><li>To ensure that no two entities try to use the same domain name, anyone who wants to have a public domain name must register it with a domain registrar.</li><li>When you register a domain name, you must do so under a top-level domain (TLD) such as .com, .net, or .org.</li><li>Route 53 is a domain registrar for hundreds of TLDs.</li><li>If you have an existing domain name with another registrar, you can transfer it to Route 53. Transferring a domain entails extending the registration by at least one year.</li><li>It’s important to understand that domain name registration and DNS hosting are two different functions.</li><li>The domain registrar and DNS hosting provider don’t have to be the same company, but they often are. <strong><em>Route 53 is both a registrar and a DNS hosting provider.</em></strong></li></ul><p><strong>Hosted Zones:</strong></p><ul><li>To have Route 53 host the DNS for a public domain name, you create a public hosted zone and specify the domain name</li><li>If you use Route 53 to register a domain name, it automatically takes care of creating a public hosted zone for the domain.</li></ul><p><strong>Routing Policies:</strong></p><p>In some cases, you just need a domain name to resolve to a particular IP address. But there are other times when you want the value of a resource record to change dynamically to work around failures or ensure users get pointed to the least busy server.</p><p>Route 53 lets you accomplish this with a variety of routing policies.</p><p>Simple:</p><ul><li>The Simple routing policy is the default for new resource records. It simply lets you map a domain name to a single static value, such as an IP address.</li><li>It doesn’t check whether the resource the record points to is available.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5ErgkftKvzsTTtO40Ce-w.png" /></figure><p>Weighted:</p><ul><li>A Weighted policy distributes traffic across multiple resources according to a ratio.</li><li>For example, when introducing a new web server, you may want to route only 10 percent of the traffic to the new server while evenly distributing the load across the rest.</li></ul><p>Latency:</p><p>A Latency policy sends users to resources in the AWS Region that’s closest to them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nFJkJETK0_rfessmQYIEuw.png" /></figure><p>Failover:</p><p>A Failover policy lets you route traffic to a primary resource unless it’s unavailable. In that case, traffic will be redirected to a secondary resource.</p><h4>AWS CloudFront</h4><ul><li>Amazon CloudFront is a <strong>content delivery network (CDN)</strong> that helps deliver static and dynamic web content to users faster than just serving it out of an AWS Region.</li><li>For example, if you’re hosting a website from a single AWS Region, as a general rule, the farther a user is away from that region, the more network latency they’ll encounter when accessing it. <strong><em>CloudFront solves this problem by caching your content in a number of data centers called edge locations.</em></strong></li><li>There are more than 216 edge locations spread out around the world on six continents.</li><li>CloudFront works by sending users to the edge location that will give them the best performance.</li><li>Typically, this is the edge location that’s physically closest to them.</li><li>CloudFront also increases the availability of your content because copies of it are stored in multiple edge locations.</li><li>The more edge locations you use, the more redundancy you have and the better performance you can expect.</li><li>As you might expect, the price of CloudFront increases as you utilize more edge locations.</li><li>You can’t select individual edge locations. Rather, you must choose from the following three options:</li></ul><ol><li>United States, Canada, and Europe</li><li>United States, Canada, Europe, Asia, and Africa</li><li>All edge locations</li></ol><ul><li>To make your content available via CloudFront, you must create a distribution. A distribution defines the <strong><em>type of content</em></strong> you want CloudFront to cache, as well as the <strong><em>content’s origin</em></strong> — where CloudFront should retrieve the content from.</li><li>There are two types of distributions: Web and Real-Time Messaging Protocol (RTMP).</li></ul><p><strong>Web Distribution:</strong></p><ul><li>A Web distribution is the most common type. It’s used for static and dynamic content such as web pages, graphic files, and live or on-demand streaming video.</li><li>Users can access Web distributions via HTTP or HTTPS.</li><li>When creating a Web distribution, you must specify an origin to act as the authoritative source for your content.</li></ul><p><strong>RTMP Distribution:</strong></p><ul><li>Real-Time Messaging Protocol (RTMP)</li><li>The Real-Time Messaging Protocol (RTMP) delivers streaming video or audio content to end-users.</li><li>To set up an RTMP distribution, you must provide both a media player and media files to stream, and these must be stored in S3 buckets.</li></ul><h4>S3 Transfer Acceleration</h4><p>Increase transfer speed by transferring file to an AWS edge location which will forward the data to the S3 bucket in the target region</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rylaGw9lKaey5_3bDK-OPw.png" /></figure><h4>AWS Global Accelerator</h4><ul><li>Improves global application <strong><em>availability </em></strong>and <strong><em>performance </em></strong>using the AWS global network</li><li>Leverage the AWS internal network to <strong><em>optimize the route to your application</em></strong> (60% improvement)</li><li><strong><em>2 Anycast IP</em></strong> are created for your application and traffic is sent through Edge Locations</li><li>The Edge locations send the traffic to your application</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYS2CoK-CbpJ8wFLRwbVyw.png" /></figure><p><strong>AWS Global Accelerator vs CloudFront</strong></p><ul><li>They both use the AWS global network and its edge locations around the world</li><li>Both services integrate with AWS Shield for DDoS protection.</li></ul><p>CloudFront:</p><ul><li>Improves performance for your cacheable content (such as images and videos)</li><li>Content is served at the edge</li></ul><p>Global Accelerator:</p><ul><li>No caching, proxying packets at the edge to applications running in one or more AWS Regions.</li><li>Improves performance for a wide range of applications over TCP or UD</li></ul><h4>AWS Outposts</h4><ul><li>It is useful for businesses that keep an on-premises infrastructure alongside a cloud infrastructure (Hybrid Cloud)</li><li>Therefore, two ways of dealing with IT systems: One for the AWS cloud and one for their on -premises infrastructure.</li><li>Therefore AWS solves this issue of having multiple ITs by AWS Outposts.</li><li>AWS Outposts are <strong><em>“server racks”</em></strong> that offers the same AWS infrastructure, services, APIs &amp; tools to build your own applications on-premises just as in the cloud.</li><li>AWS will set up and manage “Outposts Racks” within your on-premises infrastructure and you can start leveraging AWS services on-premises</li><li>You are responsible for the Outposts Rack physical security</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*fOdWPpsoG2Akr0OZFxCjAg.png" /></figure><p>Benefits of AWS Outposts:</p><ul><li>Low-latency access to on-premises systems</li><li>Local data processing</li><li>Data residency</li><li>Easier migration from on-premises to the cloud</li></ul><h4>AWS WaveLength</h4><ul><li>WaveLength Zones are infrastructure deployments embedded within the telecommunications providers’ datacenters at the edge of the 5G networks</li><li>Brings AWS services to the edge of the 5G networks</li><li>This is only used for ultra-low latency applications through 5G networks</li><li>Traffic doesn’t leave the Communication Service Provider’s (CSP) network</li><li>High-bandwidth and secure connection to the parent AWS Region</li><li>Use cases: Smart Cities, ML-assisted diagnostics, Connected Vehicles, Interactive Live Video Streams, AR/VR, Real-time Gaming</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*YFR8xWA3oN5uvlvR307yMA.png" /></figure><blockquote>The idea is that whenever you see 5G in your questions, this is most likely going to be WaveLength</blockquote><h4>AWS Local Zones</h4><ul><li>Places AWS compute, storage, database, and other selected AWS services closer to end-users <strong><em>to run latency-sensitive applications</em></strong></li><li>Extend your VPC to more locations — “Extension of an AWS Region”</li></ul><p><strong>Example:</strong></p><ul><li>AWS Region: N. Virginia (us-east-1)</li><li>AWS Local Zones: Boston, Chicago, Dallas, Houston, Miami,</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*AtyEd4vgWrQkIkYG8T2fVg.png" /></figure><h4>Global Applications Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFD_4to3RRNsSZ09T8Uwww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCnK35sPTOVahsV5VLj8Cw.png" /></figure><h3>Cloud Integration</h3><p>When we start deploying multiple applications, they will inevitably need to communicate with one another. There are generally two types of patterns to make applications communicate:</p><ol><li>Synchronous Communication</li><li>Asynchronous Communication</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxHJVE_tlHOjGQNXw0_stg.png" /></figure><p>The first one is easy to understand. It’s called a <strong><em>synchronous communication</em></strong>, in which an application talks to another application.</p><p>For example →</p><blockquote>You have created a service to buy something, then you need to talk to a service that ships what has been bought, and so therefore you want to integrate the buying service and the shipping service synchronously because they talk directly to one another.</blockquote><p>The second communication type is <strong><em>asynchronous, or event based communication</em></strong>. Here ‘Queue’ will be implemented to act as mediator between two applications.</p><p>For Example →</p><blockquote>Our buying service this time, If we bought something, that will put an order in a queue, and the shipping service will be reading from the queue to get the orders.</blockquote><p>As you can see in this example, <strong><em>your buying service</em></strong> and<strong><em> your shipping service</em></strong> are <strong><em>not directly integrated</em></strong> with one another, they are something called <strong><em>decoupled</em></strong>, because there is a <strong><em>queue </em></strong>in between to talk to. And this allows us to get some nice integration patterns.</p><p>Synchronous between applications can be problematic if there are sudden spikes of traffic. For an example, let’s say, there are 10000 orders, instead of 10.</p><p>In this case, the service you are talking to may get overwhelmed, and you may get an issue. Therefore In that case, it’s better to decouple your applications with the help of the following models.</p><ol><li>Using SQS: Queue Based Model</li><li>Using SNS: Pub/Sub Based Model</li></ol><h4>Amazon SQS(Simple Queue Service)</h4><ul><li>It’s Simple Queue Service</li><li>It allows us to decouple the application with the help of SQS Queue</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zrWI8kLBQ8v6FlB0fAE4w.png" /></figure><ul><li>Here producers sends messages into the queue. Remember, producers can be single or multiple. Once the messages are stored in a queue, that can be read by consumers who will be polling the message from queue, that means requesting messages from the queue.</li><li>Oldest AWS offering (over 10 years old)</li><li>Fully managed service (~serverless), use to decouple applications.</li><li>Scales from 1 message per second to 10,000s per second.</li><li>Default retention of messages: 4 days, maximum of 14 days.</li><li>There is no limit to how many messages can be in the queue.</li><li>Messages are deleted after they’re read by consumers</li><li>Low latency</li></ul><h4>Amazon SNS(Simple Notification Service)</h4><ul><li>What if you want to send one message to many receivers or subscribers?</li><li>Think like you have large subscriber base and you want to convey your message to them. You can’t send message to all individuals; rather send it to one mediator and that mediator will be sharing your message to all the subscribers.</li><li>Here that mediator is nothing but the Pub/Sub.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*L6vOZWf4rnCKkhbHrxpZ8w.png" /></figure><ul><li>The “event publishers” only send a message to one SNS topic</li><li>As many “event subscribers” as we want to listen to the SNS topic notifications</li><li>Each subscriber to the topic will get all the messages</li><li>Up to 10,000,000 subscriptions per topic, 100,000 topics limit</li><li>Emails, SMS messages, Mobile Notifications etc.</li></ul><h4>Amazon Kinesis</h4><ul><li><strong>Kinesis = real-time big data streaming</strong></li><li>Managed service to collect, process, and analyze real-time streaming data at any scale</li></ul><h4>Amazon MQ</h4><ul><li>SQS, SNS are “cloud-native” services, and they’re using proprietary protocols from AWS.</li><li>Traditional applications running from on-premise may use open protocols such as MQTT, AMQP, STOMP, Openwire, WSS</li><li>When migrating to the cloud, instead of re-engineering the application to use SQS and SNS, we can use Amazon MQ</li><li><strong>Amazon MQ = managed Apache ActiveMQ</strong></li><li>Amazon MQ doesn’t “scale” as much as SQS / SNS</li><li>Amazon MQ runs on a dedicated machine (not serverless)</li><li>Amazon MQ has both queue feature (~SQS) and topic features (~SNS)</li></ul><h3>Cloud Monitoring</h3><h4>CloudWatch</h4><p>Amazon CloudWatch is a key service that helps you plan, monitor, and fine-tune your AWS infrastructure and applications.</p><p>It lets you <strong><em>collect</em></strong>, <strong><em>search</em></strong>, and <strong><em>visualize </em></strong>data from your applications and AWS resources in the form of <strong><em>logs</em></strong>, <strong><em>metrics</em></strong>, and <strong><em>events</em></strong>.</p><p>Let’s discuss the common CloudWatch use cases.</p><p><strong>Infrastructure monitoring and troubleshooting: </strong>Visualize performance metrics to discover trends over time and spot outliers that might indicate a problem.</p><p><strong>Resource optimization:</strong> Save money and help with resource planning by identifying overused or underused resources.</p><p><strong>Application monitoring: </strong>Create CloudWatch alarms to alert you and take corrective action when a resource’s utilization, performance, or health falls outside of a threshold that you define.</p><p><strong>Log analytics:</strong> Search, visualize and correlate logs from multiple sources to help with troubleshooting and identify areas for improvement.</p><p>Now let’s discuss more on CloudWatch Metrics</p><p><strong>CloudWatch Metrics:</strong></p><ul><li>CloudWatch provides metrics for every service in AWS</li><li>CloudWatch Metrics is a feature that collects numeric performance metrics from both AWS and non-AWS resources such as on-premises servers.</li><li>A metric is a variable that contains a time-ordered set of data points. Each data point contains a timestamp, a value, and optionally a unit of measure.</li><li>We can create CloudWatch dashboards of metrics.</li><li>All AWS resources automatically send their metrics to CloudWatch. These metrics include things such as EC2 instance CPU utilization, S3 bucket sizes, and DynamoDB consumed read and write capacity units.</li><li>CloudWatch stores metrics for up to 15 months. You can graph metrics to view trends and how they change over time.</li></ul><p><strong>CloudWatch Alarms:</strong></p><ul><li>A CloudWatch alarm watches over the value of a single metric. If the metric crosses a threshold that you specify (and stays there), the alarm will take an action.</li><li>For example, you might configure an alarm to take an action when the average CPU utilization for an instance exceeds 80% for five minutes.</li><li>These alarms are used to trigger notifications for any metric.</li></ul><p><strong>CloudWatch Logs:</strong></p><ul><li>CloudWatch Logs collects and stores log files from AWS and non-AWS sources and make it easy to view, search, and extract custom metrics from them.</li><li>Enables real-time monitoring of logs.</li><li>You configure your applications and AWS services to send log events to CloudWatch Logs.</li><li>A log event is analogous to a line in a log file and always contains a timestamp and an event message.</li><li>By default, no logs from your EC2 instance will go to CloudWatch</li><li>You need to run a CloudWatch agent on EC2 to push the log files you want</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*0_OyuJUg2IO8FxBpyjz09g.png" /></figure><ul><li>The CloudWatch log agent can be set up on-premises too.</li></ul><p><strong>CloudWatch Events:</strong></p><ul><li>The CloudWatch Events feature lets you continuously monitor for specific events that represent a change in your AWS resources action when they occur.</li><li>For example, an EC2 instance going from the running state to the stopped state would be an event. An IAM user logging into the AWS Management Console would also be an event. CloudWatch Events can then automatically and immediately take actions in response to those events.</li><li>CloudWatch responds to events as they occur, in real-time. Unlike CloudWatch alarms, which take action when a metric crosses and remains crossing a numeric threshold, CloudWatch events trigger immediately.</li></ul><h4>Amazon EventBridge</h4><ul><li>EventBridge is the next evolution of CloudWatch Events</li><li><strong>Default Event Bus:</strong> Generated by AWS services (CloudWatch Events)</li><li><strong>Partner Event Bus:</strong> receive events from SaaS service or applications (Zendesk, DataDog, Segment, Auth0…)</li><li><strong>Custom Event buses:</strong> for your own applications</li><li>EventBridge has a different name to mark the new capabilities.</li><li>Soon the CloudWatch Events name will be replaced with EventBridge</li></ul><h4>AWS CloudTrail</h4><ul><li>CloudTrail keeps detailed event logs of every action that occurs against your AWS resources.</li><li>It is used to provides governance, compliance and audit for your AWS Account</li><li>CloudTrail is enabled by default!</li><li>It tells us n history of events / API calls made within your AWS Account by: Console, SDK, CLI, etc.</li><li>We can put logs from CloudTrail into CloudWatch Logs or S3.</li><li>A trail can be applied to All Regions (default) or a single Region.</li><li>If a resource is deleted in AWS, investigate CloudTrail first.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TrQFBztFPquL3faGr8cieg.png" /></figure><p><strong>CloudTrail Events:</strong></p><p>Management Events:</p><ul><li>Any operations that are performed on resources in your AWS account.</li><li>Examples: Configuring security, Configuring rules for routing data, Setting up logging, etc.</li><li>By default, trails are configured to log management events.</li><li>Can separate Read Events (that don’t modify resources) from Write Events (that may modify resources)</li></ul><p>Data Events:</p><ul><li>By default, data events are not logged (because high volume operations)</li><li>Example: Amazon S3 object-level activity, AWS Lambda function execution activity</li></ul><p><strong>CloudTrail Insights:</strong></p><p>We need to enable CloudTrail Insights to detect unusual activity in your account. It includes:-</p><ul><li>inaccurate resource provisioning</li><li>hitting service limits</li><li>Bursts of AWS IAM actions</li><li>Gaps in periodic maintenance activity</li></ul><p><strong>CloudTrail Events Retention:</strong></p><ul><li>Events are stored for 90 days in CloudTrail</li><li>To keep events beyond this period, log them to S3 and use Athena</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5kY5PcPlNkPJak7CiVZ5w.png" /></figure><h4>AWS X-Ray</h4><p>when your application is actually deployed, the good old way, you would test locally, then you would add log statements anywhere. Maybe look into how it logs, then you would re-deploy in production, and then see if you can find the problem this way.</p><p>The problem is that we have logs from different services and different applications. Doing log analysis is very hard because we have to combine everything.</p><p>Remember, debugging is easy if we have one big applications. But it is relatively difficult when we have distributed services. Therefore to solve this problem, AWS has introduced something called AWS X-Ray.</p><ul><li>So, with X-Ray, you’re going to be able to do a tracing and get visual analysis of your application.</li><li>Once you enable the X-Ray on your services, then you’ll get a full picture of what is happening for each service.</li><li>With X-Ray, we can see which services are failing, their performance, and in case one request goes wrong, you will be able to visualize it directly into the X-Ray console.</li></ul><p><strong>Benefits of X-Ray:</strong></p><ul><li>Troubleshooting performance (bottlenecks)</li><li>Understand dependencies in a microservice architecture</li><li>Pinpoint service issues</li><li>Find errors and exceptions</li><li>Identify users that are impacted</li><li>It is also known as debugging in Production. It enables us to → Test things locally, Add log statements everywhere, redeploy them in productions.</li><li>Debugging is easy if we have one big applications. But it is relatively difficult when we have distributed services.</li></ul><h4>Amazon CodeGuru</h4><p>It’s an ML-powered service for <strong><em>automated code reviews</em></strong> and <strong><em>application performance recommendations.</em></strong></p><p>It provides two services:</p><ol><li><strong>CodeGuru Reviewer:</strong> Automated code reviews for static code analysis (development stage)</li><li><strong>CodeGuru Profiler:</strong> Visibility/Recommendations about application performance during runtime (production stage)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i_BVr88JfLmSY82b_TiOlQ.png" /></figure><p>Lets’ talk more about CodeGuru Reviewer.</p><p><strong>CodeGuru Reviewer:</strong></p><ul><li>It identifies critical issues, security vulnerabilities, and hard-to-find bugs</li><li>Example: common coding best practices, resource leaks, security detection, input validation</li><li>It uses Machine Learning and automated reasoning</li><li>Supports Java and Python</li><li>Integrates with GitHub, Bitbucket, and AWS CodeCommit</li></ul><p><strong>CodeGuru Profiler:</strong></p><ul><li>It helps to understand the runtime behavior of your application</li><li>Example: identify if your application is consuming excessive CPU capacity on a logging routine</li><li>Support applications running on AWS or on-premise</li></ul><h4>AWS Status (Service Health Dashboard)</h4><ul><li>It shows all regions, all services health.</li><li>It shows historical information for each day</li><li>It has an RSS feed you can subscribe to.</li></ul><h4>AWS Personal Health Dashboard</h4><ul><li>AWS Personal Health Dashboard provides alerts and remediation guidance when AWS is experiencing events that may impact you.</li><li>While the <strong><em>Service Health Dashboard</em></strong> displays the <strong><em>general status</em></strong> of AWS services, <strong><em>Personal Health Dashboard</em></strong> gives you a <strong><em>personalized view</em></strong> into the <strong><em>performance and availability</em></strong> of the AWS services underlying your AWS resources.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*RvD3WLYo6E5Z6RwL8AnVcg.png" /></figure><ul><li>The dashboard displays relevant and timely information to help you manage events in progress and provides proactive notification to help you plan for scheduled activities.</li><li>It shows you how AWS outages directly impact you &amp; your AWS resources</li></ul><h3>Virtual Private Cloud (VPC) &amp; Networking</h3><p>VPC is something you should know in depth for the AWS Certified Solutions Architect Associate &amp; AWS Certified SysOps Administrator. At the AWS Certified Cloud Practitioner Level, you should know the chapters included into this section.</p><h4>VPC &amp; Subnets Primer</h4><ul><li>VPC is a private network to deploy your resources.</li><li>a VPC is linked to a specific region. So if you have multiple regions in AWS and you have multiple VPC.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*L6ZsSDJqDgXIDuVW8B3D5Q.png" /></figure><ul><li>Subnets allow you to partition your network inside your VPC.</li><li>A <strong><em>public subnet</em></strong> is a subnet that is accessible from the internet</li><li>A <strong><em>private subnet</em></strong> is a subnet that is not accessible from the internet</li><li>To define access to the internet and between subnets, we use Route Tables.</li></ul><h4>Internet Gateway &amp; NAT Gateways</h4><ul><li>Internet Gateways helps our VPC instances connect with the internet.</li><li>Public Subnets have a route to the internet gateway</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*kcizzmhwn1VbOe-yLqx06A.png" /></figure><ul><li>NAT Gateways (AWS-managed) &amp; NAT Instances (self-managed) allow your instances in your <strong><em>Private Subnets</em></strong> to <strong>a<em>ccess the internet</em></strong> while remaining private</li></ul><h4>Network ACL &amp; Security Groups</h4><p><strong>NACL (Network ACL):</strong></p><ul><li>A firewall that controls traffic from and to the subnet.</li><li>Unlike Security Groups, it can have ALLOW and DENY rules.</li><li>They are attached at the Subnet level</li><li>Rules only include IP addresses</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*uLnFesLbGFe3z2yho6qV8Q.png" /></figure><p><strong>Security Groups:</strong></p><ul><li>A firewall that controls traffic to and from an ENI / an EC2 Instance</li><li>It can have only ALLOW rules.</li><li>Rules include IP addresses and other security groups</li></ul><p><strong>Network ACLs vs Security Groups:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BehTkaa7IgiobE9PuKYaUw.png" /></figure><h4>VPC Flow Logs</h4><ul><li>It captures information about the <strong><em>IP traffic</em></strong> going into your interfaces.</li><li>It helps to monitor &amp; troubleshoot connectivity issues.</li><li>It captures network information from AWS managed interfaces too: Elastic Load Balancers, ElastiCache, RDS, Aurora, etc.</li><li>VPC Flow logs data can go to S3 / CloudWatch Logs</li></ul><h4>VPC Peering</h4><ul><li>It allows us to connect two VPC, privately using AWS’ network.</li><li>Make them behave as if they were in the same network</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*nF_gDWq0wZK1zTw7OKbFYg.png" /></figure><ul><li>Must not have overlapping CIDR (IP address range)</li><li>VPC Peering connection is not transitive (must be established for each VPC that need to communicate with one another)</li></ul><h4>VPC Endpoints</h4><ul><li>Endpoints allow you to connect to AWS Services using a private network instead of the public www network</li><li>This gives you enhanced security and lower latency to access AWS services</li><li><strong><em>VPC Endpoint Gateway:</em></strong> S3 &amp; DynamoDB</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*l5wroor0UU_aHXJxUaQeDA.png" /></figure><h4>Site to Site VPN &amp; Direct Connect</h4><p><strong>Site to Site VPN:</strong></p><ul><li>Connect an <strong><em>on-premises</em></strong> VPN to <strong><em>AWS</em></strong></li><li>The connection is automatically encrypted</li><li>Goes over the public internet</li></ul><p><strong>On-premises:</strong> must use a Customer Gateway (CGW)</p><p><strong>AWS</strong>: must use a Virtual Private Gateway (VGW)</p><p><strong>Direct Connect (DX):</strong></p><ul><li>Establish a physical connection between on-premises and AWS</li><li>The connection is private, secure and fastThe connection is private, secure and fast.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*6wfkD9ZNe0MiC1QjZ41Rew.png" /></figure><ul><li>Takes at least a month to establish.</li><li>It goes over a private network</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIfQ171kUYHOBRHWWDZKeQ.png" /></figure><h4>Transit Gateway</h4><ul><li>Connect thousands of VPC and on-premises networks together</li><li>For having transitive peering between thousands of VPC and on -premises, hub-and-spoke (star) connection.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*0TSowP30FpOKjPp9fvq9Hw.png" /></figure><ul><li>One single Gateway to provide this functionality</li><li>Works with Direct Connect Gateway, VPN connections</li></ul><h3>Security &amp; Compliance</h3><p>We have seen the AWS shared responsibility models in almost all the sections. It’s time we must formally introduce it in this section.</p><h4>AWS Shared Responsibility Model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*C7hTo1zce938uGJfnsAkUA.png" /></figure><p><strong>AWS responsibility is the security of the cloud:</strong></p><p>That means that all the infrastructure they provide to you, that includes the hardware, the software facilities, networking. They have to protect it. This is because the infrastructure will run all the services that you’re using on AWS.</p><p>On top of it, any service that is managed by AWS, such as S3 DynamoDB, RDS, is the responsibility of AWS. But once they provide a service to you, then how you use that service is your responsibility.</p><p><strong>Your responsibility is the security in the cloud:</strong></p><ul><li>You are responsible for the management of all the operating system that including patching the operating system and making updates to it.</li><li>You must configure the firewall.</li><li>You need to make sure that your EC2 instance has the correct IAM information through the use of IAM instance role.</li><li>You also need to ensure that you encrypt the application data, according to compliance requirements.</li></ul><p><strong>Shared Responsibility:</strong></p><p>Patch management, configuration management, awareness, and training are both shared between AWS and you.</p><p><strong>Example:</strong></p><ul><li>For batch managements, if using something like RDS, then AWS will do the patch management for us.</li><li>If we are using something like EC2 then we have to patch our operating system</li><li>For awareness and training, AWS has to train their employees to use their facilities correctly, and to make sure they adhere to their security guidelines. Sameway, you have to make sure to train your employees correctly, to use the cloud.</li></ul><h4>What’s a DDoS* Attack?</h4><p>A DDoS attack is a Distributed Denial-of-Service attack on our infrastructure. Look at the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f_OqOSLfxCxPhW9p42xR1g.png" /></figure><p>Here is the attacker or hacker and he wants to do a DDoS attack against our application server. In this case, they’re going to launch multiple master servers and these servers are going to launch multiple bots. These bots are going to send requests to our application server.</p><p>Now our server is not meant to handle this many requests so it will be overwhelmed and it will not be working anymore.</p><p>Therefore any normal user trying to connect to our application server, will see that our server is not accessible or not responsive. This is how the attacks gets carried away which makes our application down.</p><p><strong>DDOS Protection on AWS</strong></p><p>AWS Shield Standard:</p><ul><li>It’s a <strong><em>free and default</em></strong> service from AWS for all.</li><li>It protects against DDOS attack for your website and applications, for all customers at no additional costs</li><li>Provides protection from attacks such as <strong><em>SYN/UDP Floods</em></strong>, <strong><em>Reflection attacks, </em></strong>and another layer<strong><em> 3/layer 4 attacks</em></strong></li></ul><p>AWS Shield Advanced:</p><ul><li>It’s premium service</li><li>Protection is 24*7</li><li>It provides an optional DDoS mitigation service ($3,000 per month per organization)</li><li>It protects against more sophisticated attack on Amazon EC2, Elastic Load Balancing (ELB), Amazon CloudFront, AWS Global Accelerator, and Route 53</li><li>24/7 access to AWS DDoS response team (DRP)</li><li>It protects against higher fees during usage spikes due to DDoS</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Je0xuuilQ2v4ZZPajstMWQ.png" /></figure><p>AWS WAF:</p><ul><li>It’s Web Application Firewall (WAF) service from Amazon</li><li>It filters specific requests based on rules</li><li>It protects your web applications from common web exploits (Layer 7)</li><li>Layer 7 is HTTP (vs Layer 4 is TCP)</li><li>It can be deployed on Application Load Balancer, API Gateway, CloudFront</li><li>It also allows us to define Web ACL (Access Control List) which can protect us from SQL injections, cross-site scripting, etc.</li></ul><p>CloudFront and Route 53:</p><ul><li>Availability protection using global edge network</li><li>Combined with AWS Shield, provides attack mitigation at the edge</li></ul><h4>Penetration Testing on AWS Cloud</h4><ul><li>Penetration testing is when you’re trying to attack your own infrastructure to test your security.</li><li>AWS customers are welcome to carry out security assessments or penetration tests against their AWS infrastructure without prior approval for 8 services which includes: Amazon EC2 instances, NAT Gateways, and Elastic Load Balancers, RDS, CloudFront, Aurora, Lambda, API Gateways etc.</li></ul><h4>Encryption with KMS and CloudHSM</h4><p>There are generally two types of encryption that happens in AWS.</p><ol><li>Encryption when Data at Rest</li><li>Encryption when Data at Transit</li></ol><p>Let’s look at the above concepts in more detail.</p><ul><li>Encryption when Data at Rest means data is stored or archived on the device. It could be on RDS, S3 Glacier etc.</li><li>Encryption when Data at Transit (in motion) means data being moved from one location to another. It could means data transferred on the network. For example, Transfer from on-premises to AWS, EC2 to DynamoDB, etc.</li></ul><p>We want to encrypt data in both states to protect it. For this, we leveraged something called encryption keys. These encryption keys are responsible for encryption and descriptions.</p><p>Therefore the encryption service at AWS is called KMS (Key Management Service)</p><p><strong>AWS KSM:</strong></p><ul><li>Anytime you hear <strong><em>“encryption” for an AWS service</em></strong>, it’s most likely <strong><em>KMS</em></strong></li><li>In KMS, AWS manages the encryption keys for us.</li></ul><p><strong>CloudHSM:</strong></p><ul><li>In KMS, AWS manages the software for encryption.</li><li>In CloudHSM, AWS provisions encryption hardware.</li><li>Here HSM stands for Hardware Security Module.</li><li>In this service, you manage your own encryption keys entirely (not AWS)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*S81jjjSrHcbKRQCjd7FKgA.png" /></figure><h4>Customer Master Keys (CMK)</h4><p><strong>Customer Managed CMK:</strong></p><ul><li>Create, manage and used by the customer, can enable or disable</li><li>Possibility of rotation policy (new key generated every year, old key preserved)</li><li>Possibility to bring-your-own-key</li></ul><p><strong>AWS managed CMK:</strong></p><ul><li>Created, managed and used on the customer’s behalf by AWS</li><li>Used by AWS services (aws/s3, aws/ebs, aws/redshift)</li></ul><p><strong>AWS owned CMK:</strong></p><ul><li>Collection of CMKs that an AWS service owns and manages to use in multiple accounts</li><li>AWS can use those to protect resources in your account (but you can’t view the keys)</li></ul><p><strong>CloudHSM Keys (custom Keystore):</strong></p><ul><li>Keys generated from your own CloudHSM hardware device</li><li>Cryptographic operations are performed within the CloudHSM cluster</li></ul><h4>AWS Certificate Manager (ACM)</h4><ul><li>It lets you easily provision, manage, and deploy SSL/TLS Certificates.</li><li>These certificate used to provide in-flight encryption for websites by providing HTTPS endpoints.</li><li>It supports both public and private TLS certificates.</li><li>Free of charge for public TLS certificates</li><li>It provides an Automatic TLS certificate renewal service.</li></ul><blockquote>So anytime you see what service can help us do <strong>in-flight encryption</strong> and <strong>generates these certificates</strong> then think ACM</blockquote><h4>AWS Secrets Manager:</h4><ul><li>It’s newer service from AWS, meant for storing secrets. As the name indicates, Secrets Manager is a great way to store secrets.</li><li>On top of it, you can force the rotation of these secrets, I mean, they have to change every X number of days.</li></ul><p><strong>Example</strong>: Every 90 days, I want to change my password</p><ul><li>You can automate the generation of these secrets using Lambda.</li><li>It has an integration with Amazon RDS. So using the Secrets Manager, we can create the passwords for Amazon RDS automatically</li><li>The secrets are going to be encrypted using KMS.</li></ul><blockquote>From an exam perspective, anytime you see <strong>a secret to be managing in RDS</strong> and to be <strong>rotated</strong>, you have to think about <strong>Secrets Manager</strong>.</blockquote><ul><li>It’s paid service.</li></ul><h4>AWS Artifact</h4><p>It’s actually not a service from AWS but it’s a portal that provides customers with on-demand access to AWS compliance documentation and AWS agreements.</p><p><strong>Artifact Reports:</strong></p><p>Allows you to download AWS security and compliance documents from third-party auditors, like AWS ISO certifications, Payment Card Industry (PCI), and System and Organization Control (SOC) reports</p><p><strong>Artifact Agreements:</strong></p><p>Allows you to review, accept, and track the status of AWS agreements such as the Business Associate Addendum (BAA) or the Health Insurance Portability and Accountability Act (HIPAA) for an individual account or in your organization</p><h4>Amazon GuardDuty</h4><ul><li>If you wanted to protect your accounts against attacks from the outside and from the inside, GuardDuty is an intelligent threat discovery mechanism that will use Machine Learning Algorithm to detect anomalies within your account.</li><li>It’s One click to enable service (30 days trial), no need to install any software.</li><li>We can set up CloudWatch Event rules to be notified in case of findings.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bEHW0kCCftnKsi8ZIyNGA.png" /></figure><p>GaurdDuty needs to read data or logs in this case from various sources. It includes:</p><ul><li>CloudTrail Logs: unusual API calls, unauthorized deployments</li><li>VPC Flow Logs: unusual internal traffic, unusual IP address</li><li>DNS Logs: compromised EC2 instances sending encoded data within DNS queries</li></ul><p><strong><em>GuardDuty will analyze above input logs</em></strong> using some machine learning algorithm, and then it will emit events into CloudWatch Events.If findings are found, then from cloud watch events, we can trigger a lambda function or send ourselves an email through an SNS topic.</p><h4>Amazon Inspector</h4><ul><li>Inspector is used to conduct automated security assessments on your <strong><em>EC2</em></strong> instances.</li><li>Analyze the running OS against known vulnerabilities</li><li>Analyze against unintended network accessibility</li><li>For this, AWS Inspector Agent must be installed on OS in EC2 instances</li><li>After the assessment, you get a report with a list of vulnerabilities.</li></ul><h4>AWS Config</h4><ul><li>AWS Config helps with <strong><em>auditing </em></strong>and <strong><em>recording </em></strong>the c<strong><em>ompliance of your resources</em></strong> by recording the configuration and their changes over time.</li><li>This configuration data can be stored in S3.</li></ul><p>Questions that can be solved by AWS Config:</p><ul><li>Is there unrestricted SSH access to my security groups?</li><li>Do my buckets have any public access?</li><li>How has my ALB configuration changed over time?</li></ul><h4>Amazon Macie</h4><ul><li>Amazon Macie is a fully managed data security and data privacy service that uses machine learning and pattern matching to discover and protect your sensitive data in AWS.</li><li>Macie helps identify and alert you to sensitive data, such as <strong><em>personally identifiable information (PII)</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NNOe063kq7agSwT8Tb9ZpQ.png" /></figure><h4>AWS Security Hub</h4><p>It’s a central security tool to manage security across several AWS accounts and automate security checks.</p><p>Integrated dashboards showing current security and compliance status to quickly take actions</p><p>Automatically aggregates alerts in predefined or personal findings formats from various AWS services &amp; AWS partner tools:</p><ul><li>GuardDuty</li><li>Inspector</li><li>Macie</li><li>IAM Access Analyzer</li><li>AWS Systems Manager</li><li>AWS Firewall Manager</li><li>AWS Partner Network Solutions</li></ul><p><strong>Note:-</strong> You must first enable the AWS Config Service to use AWS Security Hub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p5DIkkBvtcEe-aJNNs7z-Q.png" /></figure><h4>Amazon Detective</h4><ul><li>GuardDuty, Macie, and Security Hub are used to identify potential security issues or findings</li><li>Sometimes security findings require deeper analysis to isolate the root cause and take action — it’s a complex process</li><li>Amazon Detective <strong><em>analyzes</em></strong>, <strong><em>investigates</em></strong>, and <strong><em>quickly identifies</em></strong> the <strong><em>root cause</em></strong> of security issues or suspicious activities (using ML and graphs)</li><li>Automatically collects and processes events from VPC Flow Logs, CloudTrail, GuardDuty and create a unified view</li><li>Produces visualizations with details and context to get to the root cause</li></ul><h4>AWS Abuse</h4><p>It report suspected AWS resources used for abusive or illegal purposes. Abusive &amp; prohibited behaviors are:</p><ul><li><strong>Spam </strong>— receiving undesired emails from AWS-owned IP addresses, websites &amp; forums spammed by AWS resources</li><li><strong>Port scanning</strong> — sending packets to your ports to discover the unsecured ones</li><li><strong>DoS or DDoS attacks</strong> — AWS-owned IP addresses attempting to overwhelm or crash your servers/software</li><li><strong>Intrusion attempts </strong>— logging in on your resources</li><li><strong>Hosting objectionable or copyrighted content </strong>— distributing illegal or copyrighted content without consent</li><li><strong>Distributing malware</strong> — AWS resources distributing software to harm computers or machines</li></ul><h4>Root User Privileges</h4><ul><li>Root user = Account Owner (created when the account is created)</li><li>He/She has complete access to all AWS services and resources</li><li>Do not use the root account for everyday tasks, even administrative tasks</li></ul><p>But there are certain actions that can be performed only by the root user. These includes:</p><ul><li>Change account settings (account name, email address, root user password, root user access keys)</li><li>Close your AWS account</li><li>Change or cancel your AWS Support plan</li><li>Register as a seller in the Reserved Instance Marketplace</li><li>View certain tax invoices</li><li>Restore IAM user permissions</li><li>Configure an Amazon S3 bucket to enable MFA</li><li>Edit or delete an Amazon S3 bucket policy that includes an invalid VPC ID or VPC endpoint ID</li><li>Sign up for GovCloud</li></ul><h3>Account Management, Billing &amp; Support Section</h3><h4>AWS Organizations</h4><ul><li>It’s a global service.</li><li>It allows us to manage multiple AWS accounts.</li><li>The main account is the master account.</li><li>API is available to automate AWS account creation.</li><li>Restrict account privileges using <strong><em>Service Control Policies (SCP)</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jmPBR570vpgCLlbxwPU8g.png" /></figure><p>It provides us various costs benefits (If we use AWS organization):</p><ul><li>Consolidated Billing across all accounts — single payment method</li><li>Pricing benefits from aggregated usage (volume discount for EC2, S3)</li><li>Pooling of Reserved EC2 instances for optimal savings.</li></ul><p><strong>Multi-Account Strategies:</strong></p><ul><li>Create accounts per department, per cost center, per dev/test / prod, based on regulatory restrictions (using SCP), for better resource isolation (ex: VPC), to have separate per-account service limits, isolated account for logging</li><li>Use tagging standards for billing purposes</li><li>Enable CloudTrail on all accounts, send logs to central S3 account</li></ul><p><strong>Organizational Units (OU):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pH_Z-Y24PrXSEgzP7Cazug.png" /></figure><p>We can create above mentioned hierarchy when we create AWS Organization. (Think like you are creating a complete organization from scratch through AWS)</p><h4>Service Control Policies (SCP)</h4><ul><li>Service Control Policies (SCPs) are IAM-like policies to manage permissions in AWS Organizations.</li><li>SCPs are policies and as we know most of the policies are defined in JSON formats.</li><li>With SCPs, we can whitelist or blacklist IAM actions.</li><li>It can be applied at the OU or Account level. But <strong><em>does not gets applied to the Master Account.</em></strong></li><li>The SCP does not affect service-linked roles. The Service-linked roles enable other AWS services to integrate with AWS Organizations and can’t be restricted by SCPs.</li><li><strong>Use Case:</strong></li></ul><ol><li>Restrict access to certain services (for example: can’t use EMR)</li><li><strong><em>Enforce PCI compliance</em></strong> by explicitly disabling services</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8tMyD7UbS-tRVB_ebKi3w.png" /><figcaption>SCP Hierarchy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQbVAYrg9i3mFL2FO94H_Q.png" /><figcaption>SCP Policies (JSON)</figcaption></figure><h4>Consolidated Billing (AWS Organization)</h4><p>The consolidated billing is today&#39;s need. When we enable the consolidated billings provides the following benefits to us.</p><ul><li><strong>Combined Usage:</strong> It combines the usage across all AWS accounts in the AWS Organization to s<strong><em>hare the volume pricing, Reserved Instances and Savings Plans discounts</em></strong></li><li><strong>One Bill: </strong>We get one bill for all AWS Accounts in the AWS Organization</li></ul><h4>AWS Control Tower</h4><ul><li>Easy way to set up and govern a secure and compliant multi-account AWS environment based on best practices.</li><li>So instead of doing everything manually creating an organization and so on and then applying security practices, we have Control Tower where you can, with a few clicks can create a multi-account, AWS environment.</li><li>It automates the setup of your environment in a few clicks.</li><li>It can automate ongoing policy management using guardrails.</li><li>It can detect policy violations and remediate them.</li><li>Monitor compliance through an interactive dashboard</li></ul><p><strong><em>AWS Control Tower</em></strong> runs on <strong><em>top of AWS Organizations</em></strong>. It automatically sets up <strong><em>AWS Organizations</em></strong> to organize accounts and implement SCPs (Service Control Policies)</p><h4>Pricing Models in AWS</h4><p>AWS has total of 4 pricing models.</p><p><strong>Pay As You Go: </strong>pay for what you use, remain agile, responsive, meet scale demands.</p><p><strong>Save When You Reserve:</strong></p><ul><li>It minimizes risks, predictably manages budgets, complies with long-term requirements.</li><li>Reservations are available for EC2 Reserved Instances, DynamoDB Reserved Capacity, ElastiCache Reserved Nodes, RDS Reserved Instance, Redshift Reserved Nodes</li><li>It like reserving things in advance so we get some pricing benefits.</li></ul><p><strong>Payless by using more:</strong></p><ul><li>This is Volume Based Discount.</li><li>We tend to get discounts when we order things or use things more.</li></ul><p><strong>Pay less as AWS grows:</strong></p><p>AWS grows their infrastructure, they will have some cost savings, and they will pass them on to you.</p><p>So AWS is very famous for doing cost reductions every month or every year, which is really good.</p><p>As their infrastructure grow, and more people use AWS, they have volume and scale, and therefore, they will pass on that economy of scale onto you to get discounts.</p><h4>Savings Plan</h4><ul><li>It’s a new way of saving on your cost in AWS, which is called a Savings Plan. So Savings Plan are a much simpler way to look at your infrastructure on AWS.</li><li>Instead of reserving instances, you just commit to spending a certain dollar amount per hour for the next one or three years.</li><li>It’s easier than the rest because you just think in terms of dollars and you don’t think in terms of specific resources and types and so on.</li><li>Easiest way to setup long-term commitments on AWS</li></ul><p><strong>EC2 Savings Plan:</strong></p><ul><li>Up to 72% discount compared to On-Demand</li><li>Commit to usage of individual instance families in a region (e.g. C5 or M5)</li><li>Regardless of AZ, size (m5.xl to m5.4xl), OS (Linux/Windows) or tenancy.</li><li>All upfront, partial upfront, no upfront</li></ul><p><strong>Compute Savings Plan:</strong></p><ul><li>Up to 66% discount compared to On-Demand</li><li>Regardless of Family, Region, size, OS, tenancy, compute options</li><li>Compute Options: EC2, Fargate, Lambda</li></ul><p>We can set up a saving plan from the AWS Cost Explorer console.</p><h4>AWS Compute Optimizer</h4><ul><li>It <strong><em>reduce costs</em></strong> and <strong><em>improves performance</em></strong> by recommending <strong><em>optimal AWS resources</em></strong> for your workloads.</li><li>It helps you choose <strong><em>optimal configurations</em></strong> and right-size your workloads (over/under-provisioned)</li><li>It uses Machine Learning to analyze your resources’ configurations and their utilization CloudWatch metrics.</li><li>Lower your costs by up to <strong>25%</strong> :D</li></ul><h4>Billing and Costing Tools</h4><p>In AWS there are tools for almost everything.</p><p><strong>Estimating costs in the cloud:</strong></p><ul><li>TCO Calculator</li><li>Simple Monthly Calculator / Pricing Calculator</li></ul><p><strong>Tracking costs in the cloud:</strong></p><ul><li>Billing Dashboard</li><li>Cost Allocation Tags</li><li>Cost and Usage Reports</li><li>Cost Explorer</li></ul><p><strong>Monitoring against costs plans:</strong></p><ul><li>Billing Alarms</li><li>Budget</li></ul><p>Now let’s see one by one in more details.</p><h4>AWS Total Cost of Ownership (TCO) Calculators</h4><ul><li>AWS helps you reduce Total Cost of Ownership (TCO) by reducing <strong><em>the need to invest in large capital expenditures</em></strong> and <strong><em>providing a pay-as-you-go, model</em></strong></li><li>The TCO calculators allow you to <strong><em>estimate the cost savings</em></strong> when using AWS and provide a detailed set of reports that can be used in executive presentations.</li><li>It <strong><em>compares the cost</em></strong> of your applications in an <strong><em>on-premises</em></strong> or traditional hosting environment to<strong><em> AWS</em></strong>: Server, Storage, Network, IT Labor</li><li>How much cost can incur when moving from on-premises to AWS.</li></ul><h4>Simple Monthly Calculator / Pricing Calculator</h4><ul><li>Simple Monthly Calculator deprecated from service since June 30th, 2020.</li><li>Now it’s replaced by AWS Pricing Calculator.</li><li>It estimates the cost for your architecture solution</li><li>It shows the cost of services on AWS</li></ul><h4>AWS Billing Dashboard</h4><p>There are ways you can track your cost in the cloud. The first way is to use the Billing Dashboard, which will show you all the costs that occurred in the month, the forecast, and the month to date.</p><p>This is a very high-level tool, but it will be helpful to just get an overview of what’s happening.</p><p>It’s the dashboard. You will see billing-related things nicely and visually appealing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*uDskuRDeEE2rEZep3ReTYA.png" /></figure><h4>Cost Allocation Tags</h4><ul><li>They will allow us to track our costs on a detailed level and group them together.</li><li>In this, we group resources based on tags to create a detailed report.</li></ul><p><strong>AWS generated tags:</strong></p><ul><li>Automatically applied to the resource you create</li><li>Starts with Prefix aws: (e.g. AWS: createdBy)</li></ul><p><strong>User-defined tags:</strong></p><ul><li>Defined by the user</li><li>Starts with Prefix user</li></ul><p>Tags can be used to create Resource Groups:</p><ul><li>Create, maintain, and view a collection of resources that share common tags</li><li>Manage these tags using the Tag Editor</li></ul><h4>Cost and Usage Reports</h4><ul><li>Dive deeper into your AWS costs and usage</li><li>The AWS Cost &amp; Usage Report contains the most comprehensive set of AWS cost and usage data available, including additional metadata about AWS services, pricing, and reservations (e.g., Amazon EC2 Reserved Instances (RIs)).</li><li>The AWS Cost &amp; Usage Report lists AWS usage for each service category used by an account and its IAM users in hourly or daily line items, as well as any tags that you have activated for cost allocation purposes.</li><li>It can be integrated with Athena, Redshift, or QuickSight for analysis purposes. (After all it contains information at a more granular level in excel file)</li></ul><h4>Cost Explorer</h4><ul><li>It’s more of a visual tool</li><li>In cost explorer, we visualize, understand, and manage the cost and usage over time.</li><li>With the help of Cost Explorer, most importantly, we can <strong><em>forecast usage up to 12 months</em></strong> based on the previous usage.</li><li>View current usage (detailed) and forecast usage</li></ul><h4>Billing Alarms in CloudWatch</h4><ul><li>It’s a simple alarm, it’s not as powerful as budgets</li><li>But this will be helpful to send you an email notification.</li></ul><p>For example, in case you go over a certain threshold. Let’s say, I set my threshold to $70 and so as soon as I crossed the $70, I received an email notification.</p><h4>AWS Budget</h4><ul><li>Budgets are very helpful to send alarms when the cost exceeds the budget or when a forecast also exceeds the budget.</li><li>Create a budget and send alarms when costs exceed the budget</li><li>There are basically 3 types of budgets: Usages, Cost, Reservation</li></ul><h4>Trusted Advisor</h4><p>No need to install anything — It just gives you a high-level AWS account assessment.</p><p>It analyses your AWS accounts and provides recommendations on 5 categories (Below mentioned)</p><ol><li>Cost optimization</li><li>Performance</li><li>Security</li><li>Fault tolerance</li><li>Service limits</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JmHw3wAvwxMwxGZdKxj3FA.png" /><figcaption>Trusted Adviser Support Plans</figcaption></figure><h3>Advanced Identity</h3><h4>AWS STS (SecurityToken Service)</h4><ul><li>Enables you to create temporary, limited- privileges credentials to access your AWS resources</li><li>These are short-term credentials: you configure the expiration period.</li></ul><p>Use cases:</p><ol><li><strong>Identity Federation:</strong> manage user identities in external systems, and provide them with STS tokens to access AWS resources</li><li><strong>IAM Roles for cross/same account access</strong></li><li><strong>IAM Roles for Amazon EC2:</strong> provide temporary credentials for EC2 instances to access AWS resources</li></ol><blockquote>It’s basically temporary, limited-privileges credentials to access AWS resources</blockquote><h4>Amazon Cognito</h4><ul><li>Identity for your Web and Mobile applications users (potentially millions)</li><li>Instead of creating them an IAM user, you create a user in Cognito</li><li>It just creates a database of users for your mobile &amp; web applications</li><li>Example: Login using Google, Facebook, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mUXj8pmncxzRnlIxAsGLRQ.png" /></figure><h4>Microsoft Active Directory</h4><ul><li>With the Microsoft Active Directory, we can use accounts on any organization&#39;s laptop or computer.</li><li>With the help of a domain controller, we can use our credentials on any machine.</li><li>We can integrate this into AWS with the help of Active Directory(AD)</li></ul><h4>AWS Single Sign-On (SSO)</h4><ul><li>Centrally manage Single SignOn to access multiple accounts and 3rd-party business applications.</li><li>One login for multiple AWS accounts &amp; applications</li></ul><h3>Other AWS Services</h3><h4>Amazon WorkSpaces</h4><ul><li>It’s managed Desktop as a Service (DaaS) solution to easily provision Windows or Linux desktops.</li><li>Great to eliminate management of on-premise VDI (Virtual Desktop Infrastructure)</li><li>Fast and quickly scalable to thousands of users</li><li>So the idea is that if someone wants you to have a windows laptop in the cloud, they can do so using WorkSpaces.</li><li>It’s secured because it’s integrated with KMS, and it’s pay as you go service, so you only pay for the usage of these actual desktops.</li></ul><blockquote>So you’re a user, you’re maybe at home, and you want to access a secure windows desktop from within AWS, you would provision one using workspaces, and then you would get access to your cloud or your corporate data center directly from this virtual desktop that is going to be secure and maybe within your VPC.</blockquote><h4>Amazon AppStream 2.0</h4><ul><li>It’s Desktop Application Streaming Service.</li><li>You want to stream an application to any computer without acquiring and provisioning infrastructure. And the application itself is going to be accessible and delivered from within a web browser.</li><li>The application is delivered from within a web browser</li></ul><p>Example:</p><blockquote>Say you want to have the Blender application to create the 3D models directly from within a web browser, you can with Amazon AppStream. So it is application-focused, and they’re delivered through your web browser.</blockquote><p><strong>Amazon AppStream 2.0 vs WorkSpaces</strong></p><ul><li>WorkSpaces is to give you a full VDI and a full Windows desktop or Linux desktop. So you can launch as many applications as you want within your desktop, and you have to connect directly using your remote desktop application.</li><li>Workspaces are on-demand or always on</li><li>Stream a desktop application to web browsers (no need to connect to a VDI)</li><li>Works with any device (that has a web browser)</li><li>Allow to configure an instance type per application type (CPU, RAM, GPU) Example: You can specify if your apps required more RAMs to run.</li></ul><h4>Amazon Sumerian</h4><ul><li>Sumerian is used to create virtual reality or augmented reality, so VR and AR, and 3D applications.</li><li>It can be used to quickly create 3D models with animations.</li><li>It is Ready-to-use templates based, hence no programming expertise is required.</li><li>Accessible via a web-browser URL or on popular hardware for AR/VR</li></ul><h4>AWS IoT Core</h4><ul><li>IoT stands for “Internet of Things” — the network of internet-connected devices that are able to collect and transfer data</li><li>AWS IoT Core allows you to easily connect IoT devices to the AWS Cloud</li><li>Serverless, secure &amp; scalable to billions of devices and trillions of messages</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*VFYP6LeK5hL1njxI1l6bmQ.png" /></figure><ul><li>Your applications can communicate with your devices even when they aren’t connected</li><li>Integrates with a lot of AWS services (Lambda, S3, SageMaker, etc.)</li><li>Build IoT applications that gather, process, analyze, and act on data</li></ul><h4>Amazon Elastic Transcoder</h4><ul><li>Elastic Transcoder is used to convert media files stored in S3 into media files in the formats required by consumer playback devices (phones etc..)</li><li>Easy to use</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQss8PO6FYgWOaKlxV2NTQ.png" /></figure><ul><li>Highly scalable — can handle large volumes of media files and large file sizes</li><li>Cost-effective — duration-based pricing model</li></ul><h4>AWS Device Farm</h4><ul><li>AWS Device Farm is an application testing service that lets you improve the quality of your web and mobile apps by testing them across an extensive range of desktop browsers and real mobile devices; without having to provision and manage any testing infrastructure.</li><li>Device Farm is a real farm of devices</li><li>Run tests concurrently on multiple devices (speed up execution)</li><li>Ability to configure device settings (GPS, language, Wi-Fi, Bluetooth, …)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HEjR5NGrKTAgD4Gja3g77g.png" /></figure><h4>AWS Backup</h4><ul><li>Fully-managed service to centrally manage and automate backups across AWS services</li><li>On-demand and scheduled backups</li><li>Supports PITR (Point-in-time Recovery)</li><li>We can create the the frequency, as well as the retention policy of our backups.</li></ul><blockquote>Anytime you see backups at the exam, think AWS Backup.</blockquote><h4>Disaster Recovery Strategies</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PuNo9DPXckOLI9awh8d6ag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBsSCSo9XCUSxbUNDtsjHQ.png" /></figure><h4>CloudEndure Disaster Recovery</h4><ul><li>CloudEndure is a company that was acquired by AWS and so, their services are now embedded within these services of AWS.</li><li>Disaster Recovery, as the name indicates, is a way for you to quickly and easily recover your physical, virtual, and cloud-based servers into AWS using a Disaster Recovery Strategy</li><li>You may want to use CloudEndure to protect your most critical databases, such as Oracle, MySQL and SQL Server, your enterprise applications such as SAP, also protect your data in case you’re being attacked.</li><li>The way CloudEndure works is that it does very good backups at the block-level of your server and is continuous.</li></ul><h4>AWS DataSync</h4><ul><li>Move large amount of data from on-premises to AWS</li><li>Replication tasks can be scheduled hourly, daily, weekly</li><li>The replication tasks are <strong>incremental </strong>after the first full load</li></ul><blockquote>So look for that word <strong>incremental </strong>at the exam. This is going to be a hint.</blockquote><p><strong>AWS Fault Injection Simulator (FIS)</strong></p><ul><li>A fully managed service for running fault injection experiments on AWS workloads</li><li>Based on Chaos Engineering — stressing an application by creating disruptive events (e.g., a sudden increase in CPU or memory), observing how the system responds, and implementing improvements</li><li>It’s kind of stress testing in AWS</li><li>It helps you uncover hidden bugs and performance bottlenecks</li></ul><h3>AWS Architecting &amp; Ecosystem</h3><h4>Well-Architected Framework General Guiding Principles</h4><ul><li>In the cloud, when you want to have good architecture, you need to <strong><em>stop guessing your capacity needs</em></strong>. Instead, you should <strong><em>use auto-scaling </em></strong>and scale based on what the actual demand on your system is going to be.</li><li>It’s also very important to automate to make architectural experimentation easier. So for this, cloud formation is very important because if you get infrastructure as code, then you can easily create an architecture on different accounts and different regions.</li><li>You should also allow making your architecture to evolve. So you need to design based on changing requirements.</li><li>Also, improve through game days, so that means that you simulate applications for flash sale days and this will stress your system by stressing your system, you will know if you are doing well.</li></ul><h4>Well-Architected Framework 5 Pillars</h4><ol><li>Operational Excellence</li><li>Security</li><li>Reliability</li><li>Performance Efficiency</li><li>Cost Optimization</li></ol><h4>1st Piller → Operational Excellence</h4><p>The first pillar in the well-architected framework is going to be operational excellence.</p><blockquote>Operational Excellence includes the ability to run and monitor systems to deliver business values and to continuously improve supporting processes and procedures.</blockquote><p>It’s about having operations that are great. There are design principles that you need to know about.</p><p><strong>Perform operations as code:</strong></p><p>All your operations should be code, infrastructure as code is going to be the cornerstone of operational excellence.</p><p><strong>Annotate documentation:</strong></p><p>You need to annotate documentation, so when you create documentation, make sure it’s annotated, make sure it’s commented, make sure it’s clean and generated after every build of your application.</p><p><strong>Make frequent, small, reversible changes:</strong></p><p>You need to make frequent and small reversible changes, so that, in case of failures, you can reverse them.</p><p><strong>Refine operations procedures frequently:</strong></p><p>You need to refine operations procedures frequently, so that the team gets more familiar with the operations, refine it, automate more, and make improvements.</p><p><strong>Anticipate failure:</strong></p><p>Finally, anticipate failure, that will always happen, and you need to learn from all these failures.</p><h4>2nd Piller → Security</h4><p>Security is the second pillar of the Well-Architected Framework.</p><blockquote>Security is the ability to protect information, systems and assets while delivering business value through risk assessment and mitigation strategies.</blockquote><p>Now let’s look at the design principles for security</p><p><strong>Implement a strong identity foundation:</strong></p><p>Centralize privilege management and reduce (or even eliminate) reliance on long-term credentials — Principle of least privilege — IAM</p><p><strong>Enable traceability:</strong></p><p>Integrate logs and metrics with systems to automatically respond and take action</p><p><strong>Apply security at all layers:</strong></p><p>You need to secure every single layer, such as if one fails maybe the next one will take over. So edge network, VPC, subnet, load balancer, every institute instance you have, the OS, patching it, the application, making sure it’s up to date, all these things</p><p><strong>Automate security:</strong></p><p>Security is not something you do manually, it’s mostly done well when it’s automated.</p><p><strong>Protect data in transit and at rest:</strong></p><p>You need to protect data in transit and at rest. That means always enable encryption, always do SSL, always use tokenization and do access control.</p><p><strong>Keep people away from data: </strong>Reduce or eliminate the need for direct access or manual processing of data</p><p><strong>Prepare for security events:</strong></p><p>Security events must happen some day in every company, I think, and so run response simulations, use tools to automate the speed of detection, investigation, and recovery</p><h4>3rd Piller → Reliability</h4><p>The third pillar of the Well-Architected Framework is reliability.</p><blockquote>Ability of a system to recover from infrastructure or service disruptions, dynamically acquire computing resources to meet demand, and mitigate disruptions such as misconfigurations or transient network issues</blockquote><p>So it’s about making sure your application runs no matter what.</p><p>Now let’s look at the design principles for Reliability</p><p><strong>Test recovery procedures:</strong></p><p>We need to test recovery procedures so you need to use automation to simulate different failures or to recreate scenarios that led to failures before.</p><p><strong>Automatically recover from failure:</strong></p><p>We need to automatically recover from failure. That means that you need to anticipate and remediate failures before they occur</p><p><strong>Scale horizontally to increase aggregate system availability:</strong></p><p>Distribute requests across multiple, smaller resources to ensure that they don’t share a common point of failure</p><p><strong>Stop guessing capacity:</strong></p><p>Maintain the optimal level to satisfy demand without over or under-provisioning — Use Auto Scaling</p><p><strong>Manage change in automation:</strong></p><p>You need to basically change everything through automation, and this is to ensure that your application will be reliable or you can roll back, or whatever.</p><h4>4th Piller → Performance Efficiency</h4><p>The fourth pillar in the Well-Architecture Framework is performance efficiency.</p><blockquote>It includes the ability to use computing resources efficiently to meet system requirements, and to maintain that efficiency as demand changes and technologies evolve</blockquote><p>So it’s all about adapting and providing the best performance.</p><p>Now let’s look at the design principles for Performance Efficiency</p><p><strong>Democratize advanced technologies:</strong></p><p>Advance technologies become services and hence you can focus more on product development.</p><p><strong>Go global in minutes:</strong></p><p>Easy deployment in multiple regions</p><p><strong>Use serverless architectures:</strong></p><p>Use serverless infrastructure. That’s the golden state. So that means you don’t manage any servers, and everything <strong><em>scales </em></strong>for you, which is really awesome.</p><p><strong>Experiment more often:</strong></p><p>Easy to carry out comparative testing</p><p><strong>Mechanical sympathy:</strong></p><p>Be aware of all AWS services</p><h4>5th Piller → Cost Optimization</h4><p>The fifth and last pillar in the Well-Architecture Framework is cost optimization.</p><blockquote>It includes the ability to run systems to deliver business value at the lowest price point possible</blockquote><p>Now let’s look at the design principles for Reliability</p><p><strong>Adopt a consumption mode:</strong></p><p>Pay only for what you use.</p><p>For example, AWS Lambda is one of these services, if you don’t use AWS Lambda you don’t pay for it, whereas RDS if you don’t use your database you still pay for it because you’ve provisioned your database.</p><p><strong>Measure overall efficiency:</strong></p><p>To measure overall efficiency, we need to use the CloudWatch service from AWS.</p><p><strong>Stop spending money on data center operations:</strong></p><p>AWS does the infrastructure part and enables customers to focus on organizational projects.</p><p><strong>Analyze and attribute expenditure:</strong></p><p>Accurate identification of system usage and costs helps measure return on investment (ROI) — Make sure to use tags</p><p><strong>Use managed and application-level services to reduce the cost of ownership: </strong>As managed services operate at a cloud scale, they can offer a lower cost per transaction or service.</p><h4>AWS Well-Architected Tool</h4><p>It’s a free tool to review your architectures against the 5 pillars Well-Architected Framework and adopt architectural best practices.</p><h4>AWS Right-Sizing</h4><p>The idea is that because you have so many EC2 instance types to choose from in the cloud, choosing the most powerful one is not the best choice, because the cloud is elastic and you can change the instance type whenever you want.</p><blockquote>Right sizing is the process of matching instance types and sizes to your workload performance and capacity requirements <strong>at the lowest possible cost.</strong></blockquote><p>In the cloud, scaling up is easy so always start small and later scale up as required.</p><p>It’s also the process of continuously looking at all your deployed instances. For example, looking at their metrics to identify which are the opportunities to eliminate or downsize without compromising on quality, capacity, performance, and so on, which will, in turn, results in lower cost.</p><p>It’s super important to right-size in two moments in your cloud journey. Number one, before you do a cloud migration because it is very common for a company to just migrate to the cloud, puts everything with the biggest instance size and forgets it. This is not the best way. Please right-size before you do cloud migration.</p><p>Once you’ve done the climate migration, you need to do it continuously. Maybe once a month, because requirements change over time and it’s important to see if you need to right-size up or right-size down.</p><p>CloudWatch, Cost Explorer, Trusted Advisor, 3rd party tools can help in finding the right size for us.</p><h4>AWS Professional Services &amp; Partner Network</h4><p>The AWS Professional Services organization is a global team of experts that can help you with AWS.</p><p>They will work alongside your team, so your people handling AWS, and a chosen member of the APN.</p><p>APN stands for, AWS Partner Network. It’s a network of people, that it was known are good with the cloud.</p><p><strong>APN Technology Partners:</strong> providing hardware, connectivity, and software</p><p><strong>APN Consulting Partners:</strong> professional services firm to help build on AWS</p><p><strong>APN Training Partners:</strong> Find who can help you learn AWS</p><p><strong>AWS Competency Program:</strong> AWS Competencies are granted to APN Partners who have demonstrated technical proficiency and proven customer success in specialized solution areas.</p><p><strong>AWS Navigate Program:</strong> help Partners become better Partners</p><h4>AWS Knowledge Center</h4><p>Contains the most frequent &amp; common questions and requests</p><h3>Machine Learning</h3><h4>Amazon Rekognition</h4><ul><li>Image Recognition</li><li>Find objects, people, text, scenes in images and videos using ML</li><li>Facial analysis and facial search to do user verification, people counting</li><li>Create a database of “familiar faces” or compare against celebrities</li></ul><p>Use cases:</p><ul><li>Labeling</li><li>Content Moderation</li><li>Text Detection</li><li>Face Detection and Analysis</li><li>Face Search and Verification</li><li>Celebrity Recognition</li><li>Pathing (ex: for sports game analysis)</li></ul><h4>Amazon Transcribe</h4><ul><li>Speech to text</li><li>Automatically convert speech to text</li><li>Uses a deep learning process called automatic speech recognition (ASR) to convert speech to text quickly and accurately</li></ul><p>Use cases:</p><ul><li>transcribe customer service calls</li><li>automate closed captioning and subtitling</li><li>generate metadata for media assets to create a fully searchable archive</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-j3ZRRGIo2pQF2x-v2Z4fw.png" /><figcaption>Speech to Text with Transcribe</figcaption></figure><h4>Amazon Polly</h4><ul><li>Text to Speech</li><li>Turn text into lifelike speech using deep learning</li><li>Allowing you to create applications that talk</li></ul><h4>Amazon Translate</h4><ul><li>Language translation service</li><li>Natural and accurate language translation</li><li>Amazon Translate allows you to localize content — such as websites and applications — for international users, and to easily translate large volumes of text efficiently</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1VIkhhNu-R-oPMDIzgdaTQ.png" /><figcaption>Amazon Translate</figcaption></figure><h4>Amazon Lex &amp; Connect</h4><p><strong>Amazon Lex</strong></p><ul><li>It’s the same technology that powers Alexa</li><li>Automatic Speech Recognition (ASR) to convert speech to text</li><li>Natural Language Understanding to recognize the intent of text, callers</li><li><strong>Helps build chatbots, call center bots</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PGY_-id-BEgvUkb1wXqzQ.png" /><figcaption>AWS Lex &amp; Connect</figcaption></figure><p><strong>Amazon Connect:</strong></p><ul><li>Receive calls, create contact flows, cloud-based virtual contact center</li><li>Can integrate with other CRM systems or AWS</li><li>No upfront payments, 80% cheaper than traditional contact center solutions</li></ul><h4>Amazon Comprehend</h4><ul><li>For Natural Language Processing — NLP</li><li>Fully managed and serverless service</li><li>Uses machine learning to find insights and relationships in text</li></ul><p><strong>Examples:</strong> Language of the text, Extracts key phrases, places, people, brands, or events, Understands how positive or negative the text is, Analyzes text using tokenization and parts of speech, Automatically organizes a collection of text files by topic</p><p><strong>Use Cases:</strong></p><ol><li>analyze customer interactions (emails) to find what leads to a positive or negative experience</li><li>Create and groups articles by topics that Comprehend will uncover</li></ol><h4>Amazon SageMaker</h4><ul><li>Fully managed service for developers / data scientists to build ML models</li><li>Typically, difficult to do all the processes in one place + provision servers</li></ul><h4>Amazon Forecast</h4><ul><li>Fully managed service that uses ML to deliver highly accurate forecasts</li><li>Example: predict the future sales of a raincoat</li><li>50% more accurate than looking at the data itself</li><li>Reduce forecasting time from months to hours</li><li><strong>Use cases:</strong> Product Demand Planning, Financial Planning, Resource Planning</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KSThKCbyE8MCewQzMWSVaQ.png" /></figure><h4>Amazon Kendra</h4><ul><li>Fully managed document search service powered by Machine Learning</li><li>Extract answers from within a document (text, pdf, HTML, PowerPoint, MS Word, FAQs…)</li><li>Natural language search capabilities</li><li>Learn from user interactions/feedback to promote preferred results (Incremental Learning)</li><li>Ability to manually fine-tune search results (importance of data, freshness, custom, …)</li></ul><h4>Amazon Personalize</h4><ul><li>Personalized recommendations service</li><li>Fully managed ML-service to build apps with real-time personalized recommendations</li><li><strong>Example:</strong> personalized product recommendations/re-ranking, customized direct marketing</li><li>Same technology used by Amazon.com</li><li>Integrates into existing websites, applications, SMS, email marketing systems</li><li>Use cases: retail stores, media and entertainment</li></ul><h3>Credits:</h3><p>As I said in the beginning, the reason that I have created this post to bring the best materials that available on internet to one consolidated place. I have referred following materials to create this blog posts for you.</p><h4>Stephane Maarek’s AWS CCP Course on Udemy</h4><p>This is the best thing happened with me that I have taken his course to prepare this exam. His knowledge and ability to explain and demonstrate things about AWS is simply great. I am sure you will enjoy his friendly teaching. I recommend you to buy his course on Udemy</p><p>Link: <a href="https://www.udemy.com/course/aws-certified-cloud-practitioner-new/">https://www.udemy.com/course/aws-certified-cloud-practitioner-new/</a></p><h4>AWS Certified Cloud Practitioner Study Guide Book By Ben Piper &amp; David Clinton</h4><p>If you wish to read in-depth services that AWS offers, this is for you.</p><h4>AWS Offcial Documentation</h4><p>There are tons of knowledge lying already on AWS documentation page. You just need to do simple Google Search.</p><p>Follow <a href="https://medium.com/u/19a974a0393">Akash Dugam</a> for more data science related blog posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f9e427ed392" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hypothesis Testing 101]]></title>
            <link>https://dugamakash.medium.com/hypothesis-testing-101-fb491635f571?source=rss-19a974a0393------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb491635f571</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Akash Dugam]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 03:33:17 GMT</pubDate>
            <atom:updated>2024-11-26T05:39:06.968Z</atom:updated>
            <content:encoded><![CDATA[<p>Hypothesis testing is an important concept in the area of statistics as well as in data science. In this post, we will be learning all the required information related to hypothesis testing. Stay tuned.</p><ol><li>What is Hypothesis Testing?</li><li>Steps involved in Hypothesis Testing</li><li>Defining Null &amp; Alternate Hypothesis</li><li>Choosing Test Statistics</li><li>Decision Making Through P-Value</li><li>Drawing Conclusion About The Population</li><li>Examples</li></ol><p>Let’s understand each of these concepts in a detailed manner.</p><h3>What is Hypothesis Testing?</h3><p>The main objective of statistics is to test a hypothesis. Let’s take an example, you are a medical researcher and by doing an experiment you found out that the drug ‘ABC’ is much effective against treating fever. But to take this into account you’ve to perform this experiment multiple times (could be with different samples) If not, no one will consider your results accurate.</p><h4><strong>What is a Hypothesis?</strong></h4><blockquote>A hypothesis is a falsifiable claim that requires <strong>verification</strong>, typically from <strong>experimental </strong>or <strong>observational data</strong>, and that allows for predictions about future observations.</blockquote><p><strong>Example:</strong></p><p>Imagine you work in the <strong>loan approval department</strong>. A bank has introduced a new <strong>credit score-based loan approval process</strong>. Before fully rolling out this system, the management wants to know if the new process improves loan repayment rates compared to the current system.</p><ul><li><strong>Null Hypothesis (H₀):</strong> The new process does not improve repayment rates.</li><li><strong>Alternative Hypothesis (H₁):</strong> The new process improves repayment rates.</li></ul><p>You will use <strong>hypothesis testing</strong> to evaluate if the observed data (repayment rates from a pilot study) provide enough evidence to support implementing the new system bank-wide.</p><h4>Why are Hypotheses important?</h4><p>Below reasons sheds some light on why are hypotheses important in the area of statistics.</p><ul><li>Hypotheses improve experiment design, critical thinking, and data analysis.</li><li>It’s not possible to do clear and meaningful data analysis without a correct hypothesis.</li><li>Hypotheses transform loose ideas or speculation into concrete and specific claims.</li><li>Hypotheses are used to develop new and more accurate theories and dissolve bad theories.</li><li>Most progress in science, engineering, medicine, and technology is the result of hypothesis testing.</li></ul><h4>Types of Hypotheses</h4><p>Hypotheses can be divided into 2 types. That is →</p><ul><li>Strong Hypothesis</li><li>Weak Hypothesis</li></ul><p>There are some characteristics of Strong Hypotheses that need to understand before we categories statements or claims into Strong or Weak Hypothesis.</p><p><strong>Characteristics of Strong Hypothesis →</strong></p><ul><li>It should be clear</li><li>It should be specific</li><li>It should be falsifiable means it can be proved wrong</li><li>A good hypothesis is based on prior data and theory.</li><li>A good hypothesis leads to a statistical test. Meaning, there should be a way to test the hypothesis.</li><li>It has to be a statement, not a question.</li><li>A prediction about the direction of an effect.</li><li>A good hypothesis is relevant for unobserved data too.</li></ul><p>Now based on the above information let’s classify the below statements into ‘Strong’, ‘Weak’ or ‘Not a hypothesis’ categories.</p><p><strong>Statement 1 →</strong></p><p><em>Medical research is important for curing diseases.</em></p><p>The above statement is correct but this is a weak hypothesis as it doesn’t provide information about data, statistics etc.</p><p><strong>Statement 2 →</strong></p><p><em>The medication has an effect.</em></p><p>The above statement falls into the ‘Weak Hypothesis’ category. This statement can be used to falsify the claim but it’s not a clear and specific statement to be categorized into the ‘Strong Hypothesis’ category.</p><p><strong>Statement 3 →</strong></p><p><em>Will students pass this exam?</em></p><p>This is a question and not a statement. Thus it’s not a hypothesis.</p><p><strong>Statement 4 →</strong></p><p><em>Studying improves grades.</em></p><p>This is a hypothesis. But It’s not clear and specific. Thus it will be categorized into a weak hypothesis.</p><p><strong>Statement 5 →</strong></p><p><em>A combination of self-study and group study will improve final exam grades by at least 10%</em></p><p>This is a clear and specific statement. It will be categorized into a strong hypothesis.</p><p><strong>Statement 6 →</strong></p><p><em>Washing hands for 20 seconds reduces disease spread.</em></p><p>This is a clear and specific claim. It can be tested. Thus we will label it as a strong hypothesis.</p><p>I hope you’ve understood the hypotheses and types of hypotheses. Now it’s time to understand what exactly mean by hypothesis testing?</p><ul><li>Hypothesis testing is a statistical method that is used in making statistical decisions using experimental data.</li><li>Hypothesis Testing is an assumption that we make about the population parameter. This assumption may or may not be true. Hypothesis testing refers to the formal procedures used by statisticians to accept or reject statistical hypotheses.</li><li>In other words, we can say, hypothesis testing is nothing but testing whether or not a claim is valid.</li></ul><h4>Examples: →</h4><p><strong><em>(A) Most people get their job from networking.</em></strong></p><p>P &gt; 0.50 …. ‘Most’ keyword used hence it is proportion. Most means, more than half.</p><p><strong><em>(B) The average payload of trucks on the highway is 18000 lbs.</em></strong></p><p>μ = 18000 …. The average was given hence it’s μ.</p><p><strong><em>(C) The pharmaceutical company X recently launched a gender selection drug, where they claim that if consumed, there are 80% of chances that women will have a baby girl. For this girl, 100 couples were tested.</em></strong></p><p>Let’s state the assumption here.</p><p>“This drug doesn’t work and the probability of having a boy or a girl is 50%.”</p><ul><li>Here we are not assuming or accepting the drug works. Because in the statistics you cannot prove something is correct.</li><li>To prove something is correct, we first need to take reciprocal of it and then try to prove that reciprocal is wrong which ultimately proves something is correct.</li></ul><p>Let’s assume we tested this drug on 2 batches of 100 couples and the result is below,</p><ul><li>52/100 had a girl…. It’s a very usual scenario</li><li>97/100 had a girl…. It’s a very unusual scenario</li></ul><p>In the first case, we can call it a usual case as the probability is almost 50%. But in case 2 which is a very unusual scenario as the probability of having a baby girl is 97% which is quite huge compared to what we’ve assumed. Thus the second case proves our assumption wrong and we will be able to say that drug works.</p><p><strong>Note →</strong></p><blockquote>The best way to determine whether a statistical hypothesis is true would be examining the entire population. But examining the entire population is often impractical. Therefore researchers tends to examine the random sample from the population. If the sample data is not consistant with statistical hypothesis, the hypothesis is rejected.</blockquote><h3>Steps involved in Hypothesis Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EhwwsMbPfm2N6UtY.png" /></figure><h3>Defining Null &amp; Alternate Hypothesis</h3><p>In this step, we need to state the two hypotheses from the statement. There are two types of statistical hypotheses.</p><ul><li>Null Hypothesis / H0</li><li>Alternative Hypothesis / H1</li></ul><h4><strong>Null Hypothesis (H0)</strong></h4><ul><li>The “Null Hypothesis” is the hypothesis that nothing interesting is happening in the data.</li><li>This is the assumption that there is no effect or no difference. It represents the “default” or “status quo” scenario.</li><li>The “Null Hypothesis” is an assumption made about the population which needs to be tested. While we test the assumption about population parameter the null hypothesis considered to be true until evidence found against it.</li><li>Null hypothesis states that the population parameter (μ, P) is equal to some value. <strong>H0: μ = 5</strong> (or) <strong>H0: P = 0.5</strong></li><li>It is denoted as H0.</li><li>We start by assuming H0 is true then we use the evidence to conclude.</li></ul><p><strong>Reject H0 → </strong>When we’ve enough evidence to prove H0 is wrong.</p><p><strong>Failed to Reject H0 → </strong>When we don’t have enough evidence to prove H0 is wrong.</p><blockquote><strong>Note </strong>→ You cannot accept the null hypothesis. You either reject it or fail to reject it depending upon the evidence.</blockquote><h4>Alternative Hypothesis (H1)</h4><ul><li>It is opposite to the assumption made i.e. the null hypothesis. It is automatically accepted when the null hypothesis gets rejected.</li><li>This is what you aim to prove. It suggests that there <strong>is</strong> an effect, difference, or relationship.</li><li>In the research, you specify the “alternative hypothesis”</li><li>It should be called an “Effect Hypothesis”</li><li>In statistical analysis, you never test the alternative hypothesis. You only test the null hypothesis.</li><li>It is denoted as H1.</li><li>The alternative hypothesis states that the population parameter (μ, P) has a different value than H0…. <strong>H1: μ ≠ 5</strong> (or) <strong>H1: P &gt; 0.6</strong></li><li>If you ‘reject’ the null hypothesis that means indirectly you accept the alternative hypothesis.</li><li>If you ‘fail to reject the null hypothesis that means you failed to accept the alternative hypothesis.</li></ul><p>Examples:</p><p><strong>Scenario 1: </strong>You work at a bank that recently introduced a loyalty program to increase the average spending of credit card customers. You want to evaluate if the program has had an impact.</p><ul><li><strong>H₀:</strong> The loyalty program does not increase the average monthly spending of customers. (No difference)</li><li><strong>H₁:</strong> The loyalty program increases the average monthly spending of customers. (There is a difference)</li></ul><p><strong>Scenario 2: </strong>A bank introduces a new loan approval policy to reduce loan defaults.</p><ul><li><strong>H₀ (Null Hypothesis):</strong> The new loan policy does not reduce the default rate.</li><li><strong>H₁ (Alternate Hypothesis):</strong> The new loan policy reduces the default rate.</li></ul><p><strong>Scenario 3: </strong>A bank introduces a new loan approval policy to reduce loan defaults.</p><ul><li><strong>H₀ (Null Hypothesis):</strong> The new loan policy does not reduce the default rate.</li><li><strong>H₁ (Alternate Hypothesis):</strong> The new loan policy reduces the default rate.</li></ul><p><strong>Scenario 4:</strong> A bank launches a promotional campaign offering cashback on purchases. It wants to check if the campaign increases monthly credit card spending.</p><ul><li><strong>H₀:</strong> The promotion does not increase average monthly credit card spending.</li><li><strong>H₁:</strong> The promotion increases average monthly credit card spending.</li></ul><p><strong>Scenario 5:</strong> The bank introduces a new fraud detection system and needs to check if it reduces the incidence of fraudulent transactions.</p><ul><li><strong>H₀:</strong> The fraud detection system does not reduce fraudulent transactions.</li><li><strong>H₁:</strong> The fraud detection system reduces fraudulent transactions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7qT3xkZAUVzzWk2sqlYWLg.png" /></figure><p>Let’s understand the above two concepts with the help of examples.</p><ul><li>A medical trial is conducted to test whether or not a new medicine reduces cholesterol by 25%.</li></ul><p><strong>H0:</strong> Medicine reduces cholesterol by 25%. | P = 0.25</p><p><strong>H1:</strong> Medicine does not reduce cholesterol by 25%. | P ≠ 0.25</p><ul><li>We want to test whether the mean GPA of students in American colleges is different from 2.0 (out of 4.0).</li></ul><p><strong>H0:</strong> Average GPA of students in American colleges is 2.0 | μ = 2.0</p><p><strong>H1:</strong> Average GPA of students in American colleges is not equal to 2.0 | μ ≠ 2.0</p><h3>Choosing Test Statistics</h3><ul><li>Test statistics are used in hypothesis testing to make a decision on ‘Null Hypothesis’ → Whether to <strong>Reject</strong> the <strong>Null Hypothesis</strong> or <strong>Fail to Reject</strong> <strong>Null Hypothesis </strong>based on the evidence.</li><li>It&#39;s a number is that is calculated from a statistical test of the hypothesis. It shows how far is your observed data from the H0</li><li>To decide on your hypothesis, we need to calculate test statistics. Since test statistics is a number, it could be p-value or critical value (z-value, t-value, F-value or x²-value )</li></ul><p><strong>Scenario:</strong> You want to determine if the average loan approval time at your bank has decreased after introducing a new automated system.</p><ul><li>You collect data on loan approval times before and after implementing the system.</li><li>A <strong>test statistic</strong> is the calculated value that tells you whether the observed difference in times is statistically significant or likely due to random variation.</li></ul><h4>p-value Interpretation</h4><p>It’s very important to understand ‘p-value’ if you are studying statistics. The majority of the decision is based on the interpretation of the p-value. And, let me tell you, this is the most confusing topic in the whole of statistics. There are many places where I have seen people misquote the p-value. I will take a simple example to explain to you what exactly is the p-value.</p><p><strong>A Coin Toss Example</strong> → Find out whether it is a trick coin or not.</p><p><strong>H0:</strong> It’s a fair Coin.</p><p><strong>H1:</strong> It’s a trick Coin.</p><p>Now we have defined our H0 and H1. The next thing would be to experiment.</p><ul><li><strong><em>Let’s toss a coin the first time and observe the result. Let’s say, you got a tails on the first attempt.</em></strong></li></ul><p>Based on this first result should we call it a trick coin? We would probably not. Since we consider the null hypothesis is true which state that it&#39;s a fair coin and if it is a fair coin then getting tails on a coin toss is random. With this limited information, we cannot just reject the H0.</p><p>Therefore, <strong>P(1T | H0) = 0.50</strong></p><ul><li><strong><em>Let’s toss a coin a second time and observe the result. Let’s say, you got a tails on the second attempt.</em></strong></li></ul><p>Based on the first two results, should we call it a trick coin? By considering H0 is true, there is a 25% chance that it could happen due to randomness. Hence we cannot reject the null hypothesis.</p><p>Therefore, <strong>P(2T | H0) = 0.25</strong></p><ul><li><strong><em>Let’s toss a coin for the third time and observe the result. Let’s say, you got a tails on the third attempt as well.</em></strong></li></ul><p>Based on the first three results, should we call it a trick coin? By considering H0 is true, there is a 12.5% chance that this could’ve happened due to randomness. We are not yet convinced to call it a trick coin.</p><p>Therefore, <strong>P(3T | H0) = 0.12</strong></p><ul><li><strong><em>Let’s toss a coin for the fourth time and observe the result. Let’s say, you got a tails on the fourth attempt too.</em></strong></li></ul><p>Based on the first four results, should we call it a trick coin? Now things get a little suspicious. By considering H0 is true, there is only a 6% (approx.) chance that this would’ve happened due to random chance.</p><p>Therefore, <strong>P(4T | H0) = 0.06</strong></p><p>Let’s toss a coin one more time to confirm it with proof.</p><ul><li><strong><em>Let’s toss a coin for the fifth time and observe the result. Let’s say, you got a tails on the fifth attempt as well.</em></strong></li></ul><p>Now should we call this a trick coin, after this conducted experiment? By considering H0 is true, there is only a 3% chance that this would’ve happened due to random chance.</p><p>Therefore, <strong>P(5T | H0) = 0.03</strong></p><p>Since the probability of happening this randomly is less, we would reject the ‘Null Hypothesis’ and consider this coin is a trick coin and biased towards the tails.</p><p>The resultant probability that we got is 3% which is less than the threshold value that is 5% (We will see how do we decide this threshold later in this blog). This leads us to reject H0 and accept the alternative hypothesis.</p><p>This probability is nothing but the p-value in hypothesis testing. When the probability of observation by considering H0 is true falls below the threshold value/alpha/level of significance (i.e. 0.05) we reject the null hypothesis and accept the alternative hypothesis.</p><p>In this example, we’ve calculated the p-value easily with the help of various probability concepts. But with increasing sample size it won’t be easy to calculate the p-value with basic probability concepts. In such cases, we mostly use a technique called <strong>‘Permutation Testing</strong>’ to calculate the p-value.</p><h4>Calculating P-Value: Permutation Testing</h4><p>Let’s understand Permutation Testing with the help of one example.</p><blockquote><strong>People who follow strict diet with gym have significant impact on weight loss than people who only goes to gym.</strong></blockquote><p>Let’s consider the two sets of samples with sample size 50 that we gathered in A and B. The initial weight of all the participants was 80KG.</p><p><strong>A →</strong> Contains sample of those who follow gym routine with a strict diet</p><p><strong>B →</strong> Contains a sample of those who follow only gym routines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8tdVDxJR940h_naL5nFi3w.png" /></figure><p>Let me define what is the P-value in the above case.</p><p>The P-Value is the <strong>p( Mean Difference in Weight ≥ 6KG | H0) </strong>which states that the probability of finding a difference (Let’s call it Δ ≥ 6KG) in mean weight when the null hypothesis is considered true. Now let’s look at calculating this probability i.e. p-value with the help of permutation testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jo3r_R7u3fHFlSIJuovkGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2spO2qmQfU83UUaRG0qKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkGwcTC9dHShAoYiP0-YpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMwiKdSfYmZR8iWa_nJH2Q.png" /></figure><p>Thus p-value literally is the percentage of values greater than Δ. In the above example is 3% hence the p-value is 0.03. Now, what does this p-value tell us? Should we reject the null hypothesis right now? …Nooh, we shouldn’t as we haven’t discussed yet how to make a decision on the basis of the p-value. We will learn how to make decisions on the basis of p-value later in this blog post but before that let’s learn something that we haven’t learnt till now. The p-value alternatives that is z-value &amp; t-Value.</p><h4>z-value and t-value</h4><p>In hypothesis testing, we can conclude the hypothesis with the help of z-value or t-value too. Not necessarily we require a p-value always.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JPWaONX6FvKRBYbGFo29lw.png" /></figure><h4>How to make a decision?</h4><p>As we’ve stated already, we need to have test statistics (p-value or z-value or t-value) to make a decision about our hypothesis. We will learn about the decision-making process in this section.</p><p>In the decision-making process, we need to have the information about the below concepts →</p><p><strong>Confidence Interval</strong></p><ul><li>It is a ‘range’ that is used to estimate a population parameter.</li><li>Confidence Interval has something called ‘Confidence Level’ associated with this.</li></ul><p><strong>Confidence Level</strong></p><ul><li>The confidence level tells that ‘ How confident are you that the actual value of the population parameter will be lying inside the range or interval.</li><li>This confidence level is expressed as <strong>‘1-α’ </strong>where <strong>α</strong> is the compliment of a confidence level.</li><li>There are mostly 3 confidence levels that we deal with</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*jFPKxLYASAdU9pJH" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/0*Kk1uBHJbMS2yDnxt.png" /></figure><ul><li>0.95 or 95% CI is mostly used in statistics. (Marked in Green above)</li></ul><p><strong>Critical Value</strong></p><ul><li>In hypothesis testing, a critical value is a point of scale or graph used to split a graph into sections like ‘rejection region’ or ‘non-rejection region’. If your test statistic falls into that region we reject the null hypothesis.</li><li>It is derived from the level of significance α i.e. z = α / 2</li><li>A z-score that separate the ‘Likely Region’ from the ‘Unlikely Region’</li><li>We do not calculate z-score for when the population parameters value is unknown. Instead, we calculate something called a t-score.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/38/0*oubuGVDAhyhUcKmg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*AJmBVUrzeZsPcyan" /><figcaption>Image Source: <a href="http://www.mathnstuff.com/">http://www.mathnstuff.com/</a></figcaption></figure><blockquote>The critical value is the value which seperate the rejection region from the region of acceptance.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0lpNvYI9HqiIzah5FzEsRQ.png" /></figure><p>The critical value serves the boundary value (or condition) to test statistics. If the test statistic falls in the region of rejection (α) which is <strong>test statistics &gt; critical value</strong> then we reject the H0.</p><p>If the test statistic falls into the region of acceptance (1-α) which is nothing but <strong>test statistics &lt; critical </strong>then we fail to reject H0. The above example is right-tailed hence the critical value is located on the right side. This could be a position of left as well as on both positions also.</p><p><strong>Note:</strong> <em>The critical values are highly affected by the left tail test, right tail test or two-tail test.</em> <em>See the above table for more information.</em></p><p><strong>Making Decision based on p-value / z- value / t-value</strong></p><p><em>Note </em><strong><em>→</em></strong> <em>Let’s consider the most used confidence level 95% or 0.95</em></p><p>Let’s consider the below values:</p><ul><li>z-value = 3.81 | z-critical = 1.96</li><li>p-value = 0.03</li><li>t-value = 0.87 | t-critical = 1.96</li><li>α = 0.05</li><li>1-α = 0.95</li></ul><p><strong>With z-value: </strong>The z-value &gt; z-critical, we reject the null hypothesis.</p><p><strong>With t-value: </strong>The t-value &lt; t-critical, we fail to reject the null hypothesis.</p><p><strong>With p-value: </strong>The p-value &lt; α, we reject the null hypothesis.</p><blockquote>In modern computing environment nowadays it is possible to calculate p-value and majority of tools / softwares return p-value for us. Therefore, p-value as test statistics used by most of the people to make decision about hypothesis testing.</blockquote><h3>Errors in Statistical Test</h3><p>In statistical hypothesis testing, no test is ever 100% certain as we rely on p-value which is based on probabilities, there is always a chance of making an incorrect conclusion regarding accepting or rejecting the null hypothesis.</p><p>Remember, when we make decisions based on statistics there are a total of 4 outcomes possible.</p><ul><li>True Positive</li><li>True Negative</li><li>False Positive</li><li>False Negative</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8IubWAEIh26K1Gbt6R--Ig.png" /></figure><p>The chances of committing these two types of errors are inversely proportional: that is, decreasing type I error rate increases type II error rate and vice versa.</p><h4>TYPE I ERROR: → FALSE POSITIVE</h4><ul><li>A type 1 error is also known as a false positive. It occurs when a null hypothesis is rejected, even though it is accurate and should not be rejected.</li><li>The probability of making a type 1 error is represented by your alpha level or confidence level. (α)</li><li>A p-value of 0.05 indicates that we are willing to accept 5% chance that we are wrong when we reject the null hypothesis.</li><li>We can reduce the risk of committing a type 1 error by using a lower value for p. For example, a <em>p</em>-value of 0.01 would mean there is a 1% chance of committing a Type I error.</li><li>But, using a lower value for alpha means you are less likely to detect true difference if one really exists. Thus risking type 2 error.</li><li>In terms of the courtroom example, a type I error corresponds to convicting an innocent defendant.</li></ul><h4>TYPE II ERROR: → FALSE NEGATIVE</h4><ul><li>A type 2 error is also known as a false negative.</li><li>It occurs when the researcher fails to reject the null hypothesis which is really false.</li><li>Here a researcher concludes there is no significant effect when actually there really is.</li><li>The probability of making type 2 error is called Beta (β) which is related to the power of the statistical test. (1-β)</li><li>We can decrease the risk of committing type 2 errors by ensuring the test has enough power. We can do this by ensuring the sample size is large enough to detect practical differences when one truly exists.</li><li>In terms of the courtroom example, a type II error corresponds to acquitting a criminal</li></ul><h4>CROSSOVER ERROR RATE (CER)</h4><ul><li>The crossover error rate is the point at which both the errors that is type 1 error and type 2 error are equal.</li><li>It represents the best way of measuring biometrics effectiveness. A system with a lower CER value provides more accuracy than a system with a higher CER value.</li></ul><h3>Python Code for Calculating P-Value Using Permutation Testing</h3><pre>treatment = [ 28.44,  29.32,  31.22,  29.58,  30.34,  28.76,  29.21,  30.4 ,<br>              31.12,  31.78,  27.58,  31.57,  30.73,  30.43,  30.31,  30.32,<br>              29.18,  29.52,  29.22,  30.56]</pre><pre>control = [ 33.51,  30.63,  32.38,  32.52,  29.41,  30.93,  49.78,  28.96,<br>            35.77,  31.42,  30.76,  30.6 ,  23.64,  30.54,  47.78,  31.98,<br>            34.52,  32.42,  31.32,  40.72]</pre><pre>from mlxtend.evaluate import permutation_test</pre><pre>p_value = permutation_test(treatment, control,<br>                           method=&#39;approximate&#39;,<br>                           num_rounds=10000,<br>                           seed=0)<br>print(p_value)</pre><pre>if p_value &lt;= 0.05 :<br>    print(&quot;Null Hypothesis is rejected and Accepted the alternate hypothesis&quot;)<br>if p_value &gt; 0.05 :<br>    print(&quot;Failed to reject the null hypothesis&quot;)</pre><p>Output →</p><pre>0.0066993300669933005<br>Null Hypothesis is rejected and Accepted the alternate hypothesis</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb491635f571" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>