<?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 NVS Yashwanth on Medium]]></title>
        <description><![CDATA[Stories by NVS Yashwanth on Medium]]></description>
        <link>https://medium.com/@nvsyashwanth?source=rss-7bd459d521f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f_YsHqA69Pni-7YVJ7WDgg.jpeg</url>
            <title>Stories by NVS Yashwanth on Medium</title>
            <link>https://medium.com/@nvsyashwanth?source=rss-7bd459d521f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:13:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nvsyashwanth/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[Evaluation metrics & Model Selection in Linear Regression]]></title>
            <link>https://medium.com/data-science/evaluation-metrics-model-selection-in-linear-regression-73c7573208be?source=rss-7bd459d521f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/73c7573208be</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[NVS Yashwanth]]></dc:creator>
            <pubDate>Wed, 07 Oct 2020 14:55:17 GMT</pubDate>
            <atom:updated>2021-01-01T11:11:20.450Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data science</h4><h4>Demystifying the most common metrics and model selection methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dy3h27CBsuC5NOc-" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, we shall go over the most common evaluation metrics in Linear Regression and also model selection strategies.</p><h3>Residual plots — Before evaluation of a model</h3><p>We know that linear regression tries to fit a line that produces the smallest difference between predicted and actual values, where these differences are unbiased as well. This difference or error is also known as <strong>residual. (</strong><em>Unbiased means there is no systematic pattern of distribution of the predicted values)</em></p><p><strong>Residual = actual value — predicted value</strong></p><p><em>e</em> = <em>y</em> — <em>ŷ</em></p><p>It is important to note that, before assessing or evaluating our model with evaluation metrics like R-squared, we must make use of residual plots.</p><p><strong><em>Residual plots expose a biased model than any other evaluation metric. If your residual plots look normal, go ahead, and evaluate your model with various metrics.</em></strong></p><p>Residual plots show the residual values on the y-axis and predicted values on the x-axis. If your model is biased you cannot trust the results.</p><p>Residual plot showing the errors corresponding to the predicted values must be randomly distributed. However, if there are any signs of a systematic pattern, then your model is biased.</p><p><strong>But what does it mean by randomly distributed errors?<br></strong>One of the assumptions of a linear regression model is that the errors must be normally distributed. This means, make sure your residuals are distributed around zero for the entire range of predicted values. Thus, if the residuals are evenly scattered, then your model may perform well.</p><h3>Evaluation metrics for a linear regression model</h3><p>Evaluation metrics are a measure of how good a model performs and how well it approximates the relationship. Let us look at<strong> MSE, MAE, R-squared, Adjusted R-squared, and RMSE.</strong></p><h4>Mean Squared Error (MSE)</h4><p>The most common metric for regression tasks is MSE. It has a convex shape. It is the average of the squared difference between the predicted and actual value. Since it is differentiable and has a convex shape, it is easier to optimize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*aLt5bWtuBr_V7TrBILe3qQ.png" /><figcaption>Mean squared error. Image by the author.</figcaption></figure><p>MSE penalizes large errors.</p><h4>Mean Absolute Error (MAE)</h4><p>This is simply the average of the absolute difference between the target value and the value predicted by the model. Not preferred in cases where outliers are prominent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*aRKkks7Fr302wcpJiaI5RA.png" /><figcaption>Mean absolute error. Image by the author.</figcaption></figure><p>MAE does not penalize large errors.</p><h4>R-squared or Coefficient of Determination</h4><p>This metric represents the part of the variance of the dependent variable explained by the independent variables of the model. It measures the strength of the relationship between your model and the dependent variable.</p><p>To understand what R-square really represents let us consider the following case where we measure the error of the model with and without the knowledge of the independent variables.</p><p><strong>Calculating regression error <br></strong>When we know the values of the independent variables, we can calculate the regression error.</p><p>We know that residual is the difference between actual and predicted value. Thus, RSS (Residual sum of squares) can be calculated as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*glXqPbWKcdlQA3p8wtBasw.png" /><figcaption>Residual sum of squares. Image by the author.</figcaption></figure><p><strong>Calculating squared residual error<br></strong>Consider the case where we don&#39;t know the values of the independent variables. We only have the <strong>y</strong> values. With this, we calculate the <strong>mean of the <em>y</em> values.</strong> This point can be represented as a horizontal line. Now we calculate the sum of squared error between the <strong>mean <em>y </em>value</strong> and that of every other <strong><em>y</em></strong> value.</p><p>The total variation in Y can be given as a sum of squared differences of the distance between every point and the arithmetic mean of Y values. This can be termed as <strong>TSS </strong>(Total sum of squares).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*nmhlSwtVwD3d244JcdBTvQ.png" /><figcaption>Total variation in y or TSS. Image by the author.</figcaption></figure><p><strong>Calculating the coefficient of determination with RSS &amp; TSS<br></strong>So we wanna find out the percentage of the total variation of Y, described by the independent variables X. If we know the percentage of the total variation of Y, that is <strong>not </strong>described by the regression line, we could just subtract the same from 1 to get the <strong>coefficient of determination or R-squared.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0d8Q-gZ-2KL31Y7t4QK3Q.png" /><figcaption>Image by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1q9TBl7kDjol_Xq35OHmrg.png" /><figcaption>Coefficient of determination. Image by the author.</figcaption></figure><blockquote><em>If the data points are very close to the regression line, then the model accounts for a good amount of variance, thus resulting in a high R² value.</em></blockquote><blockquote>However do not let the R² value fool you. A good model can have low R² value and a biased model can have a high R² value as well. That is the reason you should make use of residual plots.</blockquote><p>To summarize, the ratio of the residual error (RSS) against the total error (TSS) tells you how much of the total error remains in your regression model. Subtracting that ratio from 1 gives how much error you removed using the regression analysis. That is the R-squared error.</p><p><strong><em>If R² is high (say 1), then the model represents the variance of the dependent variable.</em></strong></p><p><strong><em>If R² is very low, then the model does not represent the variance of the dependent variable and regression is no better than taking the mean value, i.e. you are not using any information from the other variables.</em></strong></p><p><strong><em>A Negative R² means you are doing worse than the mean value. It can have a negative value if the predictors do not explain the dependent variables at all such that RSS ~ TSS.</em></strong></p><p>Thus R² evaluates the scattered data points about the regression line.</p><p>It is not possible to see a model with an R² of 1. In that case, all predicted values are the same as actual values and this essentially means that all values fall on the regression line.</p><h4>Root Mean Squared Error (RMSE)</h4><p>This is the square root of the average of the squared difference of the predicted and actual value.</p><p>R-squared error is better than RMSE. This is because R-squared is a relative measure while RMSE is an absolute measure of fit (highly dependent on the variables — not a normalized measure).</p><p>Basically, RMSE is just the root of the average of squared residuals. We know that residuals are a measure of how distant the points are from the regression line. Thus, RMSE measures the scatter of these residuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*bGLNxW-DvjRTvLMvol4vjQ.png" /><figcaption>Root mean square error. Image by the author.</figcaption></figure><p>RMSE penalizes large errors.</p><h3>Model selection &amp; Subset Regression</h3><p>Let me make it clear that, when you develop any model considering all of the predictors or regressor variables, it is termed as a <strong>full model.<br></strong>If you drop one or more regressor variables or predictors, then this model is a <strong>subset model.</strong></p><p><strong><em>The general idea behind subset regression is to find which does better. The subset model or the full model.</em></strong></p><p>We select the subset of predictors that do the best of all the available candidate predictors, such that we have the largest <em>R² </em>value, largest adjusted R², or the smallest <em>MSE</em>.</p><p><em>However, R² is never used for comparing the models as the value of R² increases with the increase in the number of predictors (even if these predictors do not add any value to the model).</em></p><blockquote><strong>Reason for model selection<br></strong>We set out to select the best subset of predictors that explain the data well. <br>A simpler model that adequately explains the relationship is always a better option due to the reduced complexity. The addition of unnecessary regressor variables will add noise.</blockquote><p><strong>We will now look at the most common criteria and strategies for comparing and selecting the best models.</strong></p><h4>Adjusted R-squared — selection criterion</h4><p>The main difference between <strong>adjusted R-squared </strong>and R-square is that <strong>R-squared</strong> describes the amount of variance of the dependent variable represented by every single independent variable, while <strong>adjusted R-squared</strong> measures variation explained by only the independent variables that actually affect the dependent variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*stA8fyU3xZI7sMhzNNeiCA.png" /><figcaption>Adjusted R-squared. Image by the author.</figcaption></figure><p><em>In the equation above, n is the number of data points while k is the number of variables in your model, excluding the constant.</em></p><p>R² tends to increase with an increase in the number of independent variables. This could be misleading. Thus, the adjusted R-squared penalizes the model for adding furthermore independent variables (k in the equation) that do not fit the model.</p><h4>Mallow’s Cp — selection criterion</h4><p>Mallow’s Cp measures the usefulness of the model. It tries to compute the mean squared prediction error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*PP1gP9yeIHW_aMbRE0_MXA.png" /><figcaption>Mallow’s Cp statistic. Image by te author.</figcaption></figure><p>Here <strong><em>p </em></strong>is the number of regressors, <strong><em>RSSₚ</em></strong> is the RSS of the model for the given <strong><em>p</em></strong> number of regressors, <strong><em>MSEₖ </em></strong>is the total MSE for <strong><em>k </em></strong>total number of predictors, and <strong><em>n</em></strong> is the sample size. <strong><em>This is useful when n&gt;&gt;k&gt;p.</em></strong></p><p>Mallow’s Cp compares the full model with a subset model. If <strong><em>Cp</em></strong> is almost equal to <strong><em>p </em></strong>(smaller the better), then the subset model is an appropriate choice.</p><p>One can plot<strong><em> Cp vs p</em> </strong>for every subset model to find out the candidate model.</p><h4>Exhaustive and Best subset searching</h4><p>The <strong>exhaustive search</strong> looks at all the models. If there are <strong><em>k</em></strong> number of regressors, there <strong><em>2ᵏ</em></strong> possible models. This is a very slow process.</p><p>The <strong>best subset strategy</strong> simplifies the search by finding the model that minimizes RSS for every <strong><em>P-value</em></strong>.</p><h4>Stepwise Regression</h4><p>Stepwise Regression is faster than Exhaustive and Best subset searching. It is an iterative procedure to choose the best model. <br><em>Stepwise regression is classified into backward and forward selection. </em><br><strong>Backward selection </strong>starts with a full model, then step by step we reduce the regressor variables and find the model with the least RSS, largest R², or the least MSE. The variables to drop would be the ones with high p-values. It is however important to note that you cannot drop one of the levels of a categorical variable. Doing so would result in a biased model. You either drop all levels of the categorical variable or none. <br><strong>Forward selection </strong>starts with a null model, then step by step we increase the regressor variables until we can no longer improve the error performance of the model. We usually pick the model with the highest adjusted R².</p><p><a href="https://bit.ly/3lSfQM2">The Ultimate Guide to Evaluation and Selection of Models in Machine Learning - neptune.ai</a></p><h3>Conclusion</h3><p>We discussed the most common evaluation metrics used in linear regression. We saw the metrics to use during multiple linear regression and model selection. Having gone over the use cases of most common evaluation metrics and selection strategies, I hope you understood the underlying meaning of the same. See you at the next one. Cheers.</p><h3>Thank you</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73c7573208be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/evaluation-metrics-model-selection-in-linear-regression-73c7573208be">Evaluation metrics &amp; Model Selection in Linear Regression</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Amazon EC2 and how to use it?]]></title>
            <link>https://medium.com/data-science/what-is-amazon-ec2-and-how-to-use-it-2f621210cf4a?source=rss-7bd459d521f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f621210cf4a</guid>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[NVS Yashwanth]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 15:38:30 GMT</pubDate>
            <atom:updated>2020-10-01T16:11:06.249Z</atom:updated>
            <content:encoded><![CDATA[<h4>Cloud computing</h4><h4>Train your models with GPU instances on the AWS cloud.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QZvOc9yrC_BiTeax" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=medium&amp;utm_medium=referral">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>AWS — Pioneer of cloud computing</h3><p>Cloud computing can be thought of transforming an IT product into an IT service.</p><p>Amazon Web Services (AWS) is an on-demand cloud computing service and Application Programming Interface(APIs) offered by Amazon. Since its inception in 2006, AWS evolved over the years, now offering over 175 fully-featured services from data centers globally.</p><p>In this article, I would go over the basics of<strong> Amazon Elastic Compute Cloud (EC2)</strong>, a web service that allows one to launch instances, which offer secure and resizable compute capacity in the cloud.</p><p>Later we will learn to deploy EC2 instances for ML/DL model training purposes.</p><h3>Features of EC2</h3><ol><li>EC2 instances are on-demand that are reliable and scalable infrastructures with the ability to increase and decrease the capacity within minutes.</li></ol><p>2. Preconfigured AMIs.</p><p>3. Configurable CPUs, memory storage, and networking capacity are called the <strong>instance types,</strong> to run your<strong> </strong>applications or software on the instance.</p><p>4. Public and private key pairs for secure login into instances.</p><p>5.<strong> Instance store volumes</strong> for temporary data that are deleted when you stop or terminate your instance.</p><p>6. Access to Amazon Elastic Block Store (Amazon EBS) for persistent storage volumes.</p><p>7. Static IPv4 addresses called <strong>Elastic IP addresses</strong> for dynamic cloud computing.</p><p>8. Deploy <strong>Virtual Private Clouds (VPCs) </strong>that are logically isolated from the AWS cloud.</p><p>9. It is an on-demand service and you are charged as per usage until termination of the instance.</p><p>10. When the instance restarts, it moves to a new host computer. It is important to note that you cannot restart a terminated instance but you can make copies of your instance called images and launch new instances from that image.</p><p>11. Amazon EC2 infrastructure is programmable and you can use scripts to automate the deployment process, install and configure.</p><p>12. If you are concerned about sensitive and confidential data on your Amazon EC2 instance, you better encrypt the data before uploading it.</p><h3>Basic Infrastructure</h3><h4>Amazon Machine Image (AMI)</h4><p>In order to use EC2 instances, we need to use Amazon Machine Image to create a virtual machine. These virtual computing environments are called <strong>instances.</strong></p><p>AMI is a template that holds all the information required to launch an EC2 instance. You can think of AMI as a box that has an operating system, an application server, and applications.</p><p>You can launch instances that are copies of AMIs running as virtual servers in the cloud.</p><p>One can access preconfigured AMIs and customize them as well.</p><p>Multiples instances can be launched from a single AMI, whose hardware is determined by the instance types.</p><h4>Location</h4><p>AWS EC2 instances are available worldwide. The locations have Regions, Availability Zones, Local Zones, and Wavelength Zones.</p><p>Regions are distant and separate geographical areas.</p><p>Each Region has multiple Availability Zones that are isolated locations.</p><p>These isolated locations have Local Zones where you place resources, such as compute and storage, in multiple locations closer to your end-users.</p><p>Wavelength zones deploy AWS with ultra-low latencies to 5G devices and end-users.</p><h4>Storage</h4><p>AWS EC2 supports AWS EC2 instance store, AWS EBS, and AWS S3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/0*d7PNBY2RB-cQVZFl.png" /><figcaption><a href="https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/EC2Win_Infrastructure.html#Win_AppDesign">Image from AWS EC2 developer documentation. (Open Source)</a></figcaption></figure><blockquote><strong>AWS EC2 instance store</strong></blockquote><p>AWS EC2 instance store is temporary, block-level storage. It is located on the disks of the host computer. Since it is temporary storage, data doesn’t persist when the associated instance is stopped or terminated. Thus EC2 Instance store is not meant for long-term data storage. One must opt for EBS or S3 in such cases.</p><p>AWS EC2 instance store is not portable. This means you cannot detach from one instance and attach it to a different instance.</p><blockquote><strong>AWS EBS</strong></blockquote><p>AWS Elastic Block Store (AWS EBS) is the recommended storage option. It is persistent storage.</p><p>A single instance can have multiple EBS volumes.</p><blockquote><strong>AWS S3</strong></blockquote><p>AWS Simple Storage Service (AWS S3) is essentially a storage bucket. You can store and retrieve any amount of data from anywhere on the web.</p><p>One can copy data from EBS, called a snapshot, and save it in S3. This can later be used to create a new EBS volume which can be attached to another EC2 instance. Thus you can detach a volume from an instance and attach it to a different instance.</p><h4>Root device volume</h4><p>The Root Device Volume contains the image used to boot the EC2 instance. This volume is deleted when the instance terminates (the DeleteOnTermination attribute is true). However, this behavior can be changed as well.</p><h4>Networking and security</h4><p>EC2 instances by default have IPv4 addresses when launched into default VPC. In the case of non-default VPC, one should specifically assign IPv4 addresses at the launch.<br>When an instance fails, the replaced instance has a different IPv4 address than the original. If your application needs a static IPv4 address, Amazon EC2 offers <em>Elastic IP addresses</em>.</p><p>Security groups can be used to control access to instances. A single instance can be assigned to multiple groups with specific rules.</p><h4>AWS Identity and Access Management (AWS IAM)</h4><p>IAM allows you to add users and groups to your AWS account with specific security credentials assigned to each user. Resources can be shared amongst the users in the same account as well as another AWS account. One can control each user&#39;s permissions to perform tasks using AWS resources.</p><p>By using IAM with Amazon EC2, you have full control over the users performing tasks with Amazon EC2 and specific AWS resources.</p><h3>Setting up your AWS EC2</h3><p>I hope you have registered an account on AWS. If not do the same. Now head over to the AWS management console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AB8EU8GT12ryF8kUfsUTjQ.png" /><figcaption>AWS Management Console home. Image by the author.</figcaption></figure><p>After you log in to your AWS console, select EC2 from the drop-down menu labeled <strong>Services</strong>.</p><p>Before using any AWS service we need to check and if necessary modify the AWS service limit for that particular resource we are planning to use. So let us look into that.</p><h4>GPU Limit Increase Request</h4><p>AWS resources have a default quota know as “<em>limits”</em>. These limits are according to the region of your AWS account. For now, I will talk specifically about EC2 instances only.</p><p><strong>Steps to increase GPU limit:</strong></p><p>1. We first need to select the appropriate AWS region which supports the GPU instances we are choosing to use. We will be using <strong>p2.xlarge. </strong>P2 are powerful and scalable parallel processing GPU instances.</p><p>2 . Make sure your AWS region supports that particular instance. <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html">You can cross-check here</a>.</p><p>3. Now that your region is set, we need to view your <strong>EC2 Service Limit report</strong> at <a href="https://console.aws.amazon.com/ec2/v2/home?#Limits">this link</a> and find your “Current Limit” for <strong>P2</strong>. (Alternatively head over to the EC2 dashboard and click limits and see P2 limit)<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GH6RTMqOZpEW-RhNZMxGQ.png" /><figcaption>AWS EC2 dashboard. Click on limits. Image by the author.</figcaption></figure><p>4. <strong>Your limit will be 0. </strong>What does this mean? AWS sets a limit of 0 on the number of p2.xlarge instances a user can run, which effectively prevents you from launching this instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f-7oryEfoP_FNOY8bldH-g.png" /><figcaption>P2 resource limit 0. Image by the author.</figcaption></figure><p>5. If your limit of p2.xlarge instances is 0, you’ll need to increase the limit before you can launch an instance.</p><p>6. Click on <strong>Calculate vCPU limit</strong> to make a limit increase request. The limit calculator is used to calculate how many vCPUs (virtual central processing unit) you need to launch your On-Demand Instances, in our case P2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*TEB2Ao9z7Rj_URUKl3sKZw.png" /><figcaption>Increasing the limit. Image by the author.</figcaption></figure><p>7. Click on the add instance type and select <strong>p2.xlarge. </strong>Make sure the <strong><em>instance count is 1</em></strong>. Verify the <strong>New limit</strong> is showing <strong>4 vCPUs</strong> and then click on the <strong>Request limit increase. </strong><em>Requesting for limit increase will not charge your card unless you launch an instance. </em>This will open the following screen. Click on the <strong>Service limit increase</strong> if it is not already selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHKV_DaiA2MUVbk_tL9pug.png" /><figcaption>Service limit increase. Image by the author.</figcaption></figure><p>8. Your limit type in case details would be EC2 instances. Now, under <strong>Requests, </strong>select your <strong>region of AWS account, </strong>then select <strong>Primary Instance Type </strong>as <strong><em>All P instances. Set the </em>New limit value<em> </em></strong><em>to</em><strong><em> greater than 4.</em></strong></p><p>9. Scroll down fill the <strong>Case description </strong>your case for the limit increase and click on <strong>submit. You will be sent a mail with the corresponding Case ID. </strong>You must wait for AWS to approve your Limit Increase Request. AWS typically approves these requests within 48 hours.</p><blockquote><strong><em>Note:</em></strong><em> If you have never launched an instance of any type on AWS, you might receive an email from AWS Support asking you to initialize your account by creating an instance before they approve the limit increase.</em></blockquote><h3>Launching our EC2 GPU instance</h3><p>Once AWS approves your GPU Limit Increase Request, you can start the process of launching your instance.</p><p><strong>Steps to launch your EC2 GPU instance:</strong></p><ol><li>Click on launch instance</li><li>Choose an Amazon Machine Image (AMI). We will be using <strong>Deep Learning AMI.</strong></li><li>Choose an Instance Type. As mentioned before, we will be using <strong>p2.xlarge.</strong></li><li>Press review and launch. It would take you to a page where you can further update configuration details, storage volume, etc. For now, let us just edit security groups.</li><li>Configure Security Group — Attach a set of firewall rules to your instances that control the incoming traffic to your instances. Just click on the e<strong>dit security groups</strong> option and select <strong>create a new security group.</strong> Let us name this security group as “<em>Jupyter”. </em>Press on <strong>Add rule. Set a custom TCP rule </strong>with <strong>port range <em>8888 </em></strong>and <strong>source </strong>as <strong><em>anywhere</em>.</strong></li><li>Click on <strong>Launch</strong>.</li><li>Let us now <strong>create an authentication key pair.</strong> This is done in order to access your GPU instance. Click on c<strong>reate a new key pair</strong> and click the <strong>Download Key Pair </strong>button. This will download a<strong> .pem file</strong>, which you’ll need to be able to access your instance.</li><li>Move the downloaded .pem file to a secure location on your computer as you need the same to access your instance through the location you select. After downloading the .pem file, click on l<strong>aunch instances.</strong></li><li>Click the <strong>View Instances</strong> button to go to the EC2 Management Console and watch your instance boot.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ezPSmW9GGSVvi3_3Q-KDSQ.png" /><figcaption>Launch instance (orange button). Image by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wYTlmDCjEfy0wqyJ6V8ukA.png" /><figcaption>Select AMI. Deep Learning AMI. Image by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pM5KKZKw6FumAtz0jR2fPQ.png" /><figcaption>Select GPU. p2.xlarge. Image by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IaSTEc20IqJLlelDgG25vw.png" /><figcaption>Edit security groups. Image by the author.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H4_qKeI6yofKTwxWj4Prxw.png" /><figcaption>Instances launched. Image by the author.</figcaption></figure><blockquote><strong>NOTE: </strong><br>Shutdown any unused instance or other AWS resources or you will be charged by the hour. AWS charges for running instances unitl you stop the instance. However, there are smaller storage charges that continue to accrue until you “terminate” (i.e. delete) the instance.</blockquote><h4>AWS billing alarms</h4><p>There is no way to limit AWS to only a certain budget and have it auto-shutdown when it hits that threshold. However, you can set <a href="http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/free-tier-alarms.html">AWS Billing Alarms</a>.</p><h3>Log into your AWS EC2 instance</h3><ol><li>Go to the EC2 dashboard and click on the <strong>running instance&#39;s</strong> option. Your instance will be displayed.</li><li>Note the IPv4 address.</li><li>From a terminal, navigate to the location where you stored your .pem file. (For example, if you put your .pem file on your Desktop, cd ~/Desktop/ will move you to the correct directory.)</li><li>Type ssh -i YourKeyName.pem ubuntu@X.X.X.X, where: X.X.X.X is the IPv4 Public IP found in AWS, andYourKeyName.pem is the name of your .pem file.</li><li>In your instance, in order to create a config file for your Jupyter notebook settings, type: jupyter notebook --generate-config.</li><li>Open any GitHub repo or just clone into the instance terminal.</li><li>Start Jupyter notebookjupyter notebook --ip=0.0.0.0</li><li>Now your terminal would show a token ID this way:</li></ol><pre>unnecessary_stuff:8888/?token=something_useful_here</pre><p>9. Access the Jupyter notebook index from your web browser by visiting: X.X.X.X:8888/?token=... (where X.X.X.X is the IP address of your EC2 instance and everything starting with :8888/?token= is what you just copied). HURRAY. There you go. Your Jupyter notebook is up and running on your EC2 instance. Congrats.</p><p>10. To close the notebook, press ctrl-c twice and to exit instance terminal type exit.</p><h3>Takeaways</h3><p>You can activate conda on startup by typing<strong> conda config — set auto_activate_base true</strong></p><p>At times your instance might not have the required packages, just <strong>pip install </strong>the same.</p><p>If you have a requirements.txt file, just type sudo python3 -m pip install -r requirements.tx</p><p>Stop and terminate your instances when not in use. You need to understand that AWS charges you even if the instance is not in use. Thus, instances that are On and idle would also burn your pockets. This is one drawback of AWS. Google Cloud on the other hand does not charge you if the instances are idle.</p><h3>Conclusion</h3><p>Congrats! Now you know what is Amazon EC2 and how to use it. AWS is the most used cloud service thus being familiar with 1 or 2 technologies is useful. Amazon EC2 has many more features. Open the EC2 dashboard and learn more. I hope you understood how to deploy a GPU instance. See you at the next one. Cheers!</p><h4>Thank you.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f621210cf4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-is-amazon-ec2-and-how-to-use-it-2f621210cf4a">What is Amazon EC2 and how to use it?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Street View House Number Generation Using DCGAN]]></title>
            <link>https://medium.com/data-science/street-view-house-number-generation-using-dcgan-8cc5222408f3?source=rss-7bd459d521f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cc5222408f3</guid>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[google-street-view]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[NVS Yashwanth]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 13:03:06 GMT</pubDate>
            <atom:updated>2020-09-25T13:03:06.430Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep Learning</h4><h4>Generating new images of house numbers with DCGANs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9QmSMrsHyFz8I_oa" /><figcaption>Photo by <a href="https://unsplash.com/@kmvrlv?utm_source=medium&amp;utm_medium=referral">Karla Alexander</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I’ll walk you through a fun project where you will implement a DCGAN for street view house number generation.</p><p>We will make use of the Street View House Number (SVHN) dataset to train our adversarial networks.</p><blockquote><em>If you are not familiar with GANs and how they work, please read this article featured on Towards Data Science.</em></blockquote><p><a href="https://towardsdatascience.com/generative-adversarial-networks-6a17673db367">Generative Adversarial Networks</a></p><h4>Street View House Number (SVHN) dataset</h4><p>You’ll be training DCGAN on the Street View House Numbers (SVHN) dataset. These are color images of house numbers collected from Google street view. SVHN images are in color and much more variable than MNIST.</p><p>Data can be downloaded from <a href="http://ufldl.stanford.edu/housenumbers/">here</a>.</p><blockquote>We will be making use of Deep Convolutional GANs. If you want to read about DCGANs, check out this article.</blockquote><p><a href="https://towardsdatascience.com/dcgans-deep-convolutional-generative-adversarial-networks-c7f392c2c8f8">DCGANs (Deep Convolutional Generative Adversarial Networks)</a></p><h4>Pre-processing and data loading</h4><p>We just need to convert the data into a tensor and prepare our data loaders.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/518ffbdbb172b314a25dcb735a98ec90/href">https://medium.com/media/518ffbdbb172b314a25dcb735a98ec90/href</a></iframe><h4>Visualizing our training data</h4><p>We will now generate a batch of data and visualize the same. Please note that the np.transpose function translates the image dimension by the order specified. For example, an RGB image of shape 3x32x32 gets transposed to 32x32x3 upon calling the following function:</p><pre>np.transpose(img,(1,2,0))</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e100860f00f7acd40b828a1344697ca5/href">https://medium.com/media/e100860f00f7acd40b828a1344697ca5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPP3hVhhzbAZUlxw0hO2oA.png" /><figcaption>Image by the author.</figcaption></figure><p>Our batch size is 128, so instead of plotting all 128 images of a batch, we only plot 20 in this case.</p><h4>Scaling images</h4><p>It is important to scale the images as the Tanh function has values in the range -1 to 1, so we need to rescale our training images to a range of -1 to 1. (Right now, they are in a range from 0–1.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5586e40df5b5a31b3614873e5dca824b/href">https://medium.com/media/5586e40df5b5a31b3614873e5dca824b/href</a></iframe><h4>Helper functions — Convolutional &amp; Transpose Convolutional</h4><p>To make things easier and simply our code, we will define helper functions for defining our Discriminator &amp; Generator networks.</p><p>The reason for these helper functions? Answer — DRY! 😅</p><p><strong>Convolution helper function</strong></p><blockquote><em>Note: To read about CNNs, check out the Stanford Notes below.</em></blockquote><p><a href="https://cs231n.github.io/">CS231n Deep Learning for Computer Vision</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dbf53f70a7af272d7d7714439bc60c8/href">https://medium.com/media/5dbf53f70a7af272d7d7714439bc60c8/href</a></iframe><p><strong>Transpose Convolution helper function</strong></p><blockquote><em>Note: If you want to read about transpose convolution, check out the article below.</em></blockquote><p><a href="https://towardsdatascience.com/transposed-convolution-demystified-84ca81b4baba">Transposed Convolution Demystified</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd0d9b29c4f8352cf85e313b7af24506/href">https://medium.com/media/bd0d9b29c4f8352cf85e313b7af24506/href</a></iframe><h4>Discriminator Architecture</h4><p>We shall now define our discriminator network. The discriminator as we know is responsible for classifying the images as real or fake. Thus this is a typical classifier network.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ecb810457ccf83de928bd7c0339fff6/href">https://medium.com/media/4ecb810457ccf83de928bd7c0339fff6/href</a></iframe><h4>Generator Architecture</h4><p>The generator network is responsible for generating fake images that could fool the discriminator network into being classified as real. Over time the generator becomes pretty good in fooling the discriminator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf427bef18151501535c13432a860674/href">https://medium.com/media/bf427bef18151501535c13432a860674/href</a></iframe><h4>Parameter initialization</h4><p>We will initialize the weights and biases of our network by sampling random values from a normal distribution. This results in better results. We define a function for the same that takes a layer as an input.</p><p>For weights, I used 0 mean and 0.02 standard deviation.</p><p>For bias, I used 0.</p><blockquote><em>Now this should be in place replacement so the _(underscore) after the function does the same.</em></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db80aef49bd1f3251f395c93bcbd7449/href">https://medium.com/media/db80aef49bd1f3251f395c93bcbd7449/href</a></iframe><h4>Loss functions and optimizer</h4><p>We shall make use of Adam optimizer with a learning rate of 0.002. This is as per the original research paper on DCGANs. You can check it out below.</p><p><a href="https://arxiv.org/abs/1511.06434">Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aba0fe8596a8c0690692e6b29f7dc585/href">https://medium.com/media/aba0fe8596a8c0690692e6b29f7dc585/href</a></iframe><p>We used BCEwithLogitsLoss(), which combines a sigmoid activation function (we want the discriminator to output a value 0–1 indicating whether an image is <em>real or fake</em>) and binary cross-entropy loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*1I9MpiCXDgoY2XvY42tYQA.png" /><figcaption>Equation of Binar Cross-Entropy Loss. Image by the author.</figcaption></figure><h4>Training phase</h4><p>We shall train for 50 epochs for better results.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a32f154fdd4aed8ab937db9fc563511a/href">https://medium.com/media/a32f154fdd4aed8ab937db9fc563511a/href</a></iframe><h4>Plotting losses</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9386aba0c18d18fe10f724402637fecc/href">https://medium.com/media/9386aba0c18d18fe10f724402637fecc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*ghHd20iJvHgJ9wHF7yzH6g.png" /><figcaption>Image by the author.</figcaption></figure><h4>Sample generation</h4><p>Let us generate a few samples now. It is important that we rescale the values back to the pixel range(0–255).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2829766eb429e1b2dfc1a9de0b3f5916/href">https://medium.com/media/2829766eb429e1b2dfc1a9de0b3f5916/href</a></iframe><p>And finally, we have our generated street view hours numbers below. 👀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdVsNGucLsuB730dvaGDwA.png" /><figcaption>Image by the author.</figcaption></figure><h3>Conclusion</h3><p>We have seen how to generate street view house numbers with DCGAN implementation on the SVHN dataset. The images generated can be further improved by tuning the hyperparameters. One could also opt for deeper layers than the one here. Doing so would however result in an increased number of parameters which again would take a lot of time to train. Now open your Jupyter Notebook and implement the same. In the next article, I shall walk you through the image-to-image translation with CycleGANs. Cheers!</p><h3>Thank you.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cc5222408f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/street-view-house-number-generation-using-dcgan-8cc5222408f3">Street View House Number Generation Using DCGAN</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Celebrity Face Generation With Deep Convolutional GANs]]></title>
            <link>https://medium.com/data-science/celebrity-face-generation-with-deep-convolutional-gans-40b96147a1c9?source=rss-7bd459d521f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/40b96147a1c9</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deepfakes]]></category>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[NVS Yashwanth]]></dc:creator>
            <pubDate>Thu, 24 Sep 2020 16:24:05 GMT</pubDate>
            <atom:updated>2020-09-25T06:47:11.882Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep learning</h4><h4>Generating new images of faces with DCGANs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mZhMuhHxtQKlo52m" /><figcaption>Photo by <a href="https://unsplash.com/@johnjac?utm_source=medium&amp;utm_medium=referral">John Jackson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I’ll walk you through a fun project where you will implement a DCGAN for face generation.</p><p>We will make use of the Large-scale CelebFaces Attributes (celebA) dataset to train our adversarial networks.</p><blockquote>If you are not familiar with GANs and how they work, please read this article featured on Towards Data Science.</blockquote><p><a href="https://towardsdatascience.com/generative-adversarial-networks-6a17673db367">Generative Adversarial Networks</a></p><h4>Large-scale CelebFaces Attributes (celebA) dataset</h4><p><strong>CelebFaces Attributes Dataset (CelebA)</strong> is a large-scale face attributes dataset with more than <strong>200K</strong> celebrity images, each with <strong>40</strong> attribute annotations.</p><p>Data can be downloaded from <a href="https://s3.amazonaws.com/video.udacity-data.com/topher/2018/November/5be7eb6f_processed-celeba-small/processed-celeba-small.zip">here</a>.</p><blockquote>We will be making use of Deep Convolutional GANs. If you want to read about DCGANs, check out this article.</blockquote><p><a href="https://towardsdatascience.com/dcgans-deep-convolutional-generative-adversarial-networks-c7f392c2c8f8">DCGANs (Deep Convolutional Generative Adversarial Networks)</a></p><h4>Pre-processing and data loading</h4><p>We don&#39;t need the annotations so we will have to crop images. Now, these are color images. Thus, depth is 3 (RGB — 3 color channels).</p><p>We can resize &amp; crop the images to a size of 32x32. This can be later converted into tensors.</p><p>Note that we user image folder wrapper function here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a960067d4954b6905b094e412f1f91f9/href">https://medium.com/media/a960067d4954b6905b094e412f1f91f9/href</a></iframe><h4>Visualizing our training data</h4><p>We will now generate a batch of data and visualize the same. Please note that the np.transpose function translates the image dimension by the order specified. For example, an RGB image of shape 3x32x32 gets transposed to 32x32x3 upon calling the following function:</p><pre>np.transpose(img,(1,2,0))</pre><p>Our batch size is 128, so instead of plotting all 128 images of a batch, we only plot 20 in this case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebee335807de8ec0b056b82ac8cb23d5/href">https://medium.com/media/ebee335807de8ec0b056b82ac8cb23d5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*46kGgX40UXni9_kbbREGFg.png" /><figcaption>A batch of training images. Image by the author.</figcaption></figure><h4>Scaling images</h4><p>It is important to scale the images as the Tanh function has values in the range -1 to 1, so we need to rescale our training images to a range of -1 to 1. (Right now, they are in a range from 0-1.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdc85aa137a7f5f45897d0562badf870/href">https://medium.com/media/fdc85aa137a7f5f45897d0562badf870/href</a></iframe><h4>Helper functions — Convolutional &amp; Transpose Convolutional</h4><p>To make things easier and simply our code, we will define helper functions for defining our Discriminator &amp; Generator networks.</p><p>The reason for these helper functions? Answer — DRY! 😅</p><p><strong>Convolution helper function</strong></p><blockquote>Note: To read about CNNs, check out the Stanford Notes below.</blockquote><p><a href="https://cs231n.github.io/">CS231n Deep Learning for Computer Vision</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dbf53f70a7af272d7d7714439bc60c8/href">https://medium.com/media/5dbf53f70a7af272d7d7714439bc60c8/href</a></iframe><p><strong>Transpose Convolution helper function</strong></p><blockquote>Note: If you want to read about transpose convolution, check out the article below.</blockquote><p><a href="https://towardsdatascience.com/transposed-convolution-demystified-84ca81b4baba">Transposed Convolution Demystified</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd0d9b29c4f8352cf85e313b7af24506/href">https://medium.com/media/bd0d9b29c4f8352cf85e313b7af24506/href</a></iframe><h4>Discriminator Architecture</h4><p>We shall now define our discriminator network. The discriminator as we know is responsible for classifying the images as real or fake. Thus this is a typical classifier network.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ecb810457ccf83de928bd7c0339fff6/href">https://medium.com/media/4ecb810457ccf83de928bd7c0339fff6/href</a></iframe><h4>Generator Architecture</h4><p>The generator network is responsible for generating fake images that could fool the discriminator network into being classified as real. Over time the generator becomes pretty good in fooling the discriminator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf427bef18151501535c13432a860674/href">https://medium.com/media/bf427bef18151501535c13432a860674/href</a></iframe><h4>Parameter initialization</h4><p>We will initialize the weights and biases of our network by sampling random values from a normal distribution. This results in better results. We define a function for the same that takes a layer as an input.</p><p>For weights, I used 0 mean and 0.02 standard deviation.</p><p>For bias, I used 0.</p><blockquote>Now this should be in place replacement so the _(underscore) after the function does the same.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db80aef49bd1f3251f395c93bcbd7449/href">https://medium.com/media/db80aef49bd1f3251f395c93bcbd7449/href</a></iframe><h4>Loss functions and optimizer</h4><p>We shall make use of Adam optimizer with a learning rate of 0.002. This is as per the original research paper on DCGANs. You can check it out below.</p><p><a href="https://arxiv.org/abs/1511.06434">Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aba0fe8596a8c0690692e6b29f7dc585/href">https://medium.com/media/aba0fe8596a8c0690692e6b29f7dc585/href</a></iframe><p>We used BCEwithLogitsLoss(), which combines a sigmoid activation function (we want the discriminator to output a value 0–1 indicating whether an image is <em>real or fake</em>) and binary cross-entropy loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*1I9MpiCXDgoY2XvY42tYQA.png" /><figcaption>Equation of Binar Cross-Entropy Loss. Image by the author.</figcaption></figure><h4>Training phase</h4><p>We will define a function for training our model. The parameters would be the Discriminator, Generator, epoch number.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/628176a715b7d2bd4cfaa5609b4b7e9a/href">https://medium.com/media/628176a715b7d2bd4cfaa5609b4b7e9a/href</a></iframe><h4>Plotting losses</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9386aba0c18d18fe10f724402637fecc/href">https://medium.com/media/9386aba0c18d18fe10f724402637fecc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*5hyOLWe2k8d8yFpSpLImAw.png" /><figcaption>Image by the author.</figcaption></figure><h4>Sample generation</h4><p>Let us generate a few samples now. It is important that we rescale the values back to the pixel range(0–255).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2829766eb429e1b2dfc1a9de0b3f5916/href">https://medium.com/media/2829766eb429e1b2dfc1a9de0b3f5916/href</a></iframe><p>And finally, we have our generated faces below. 👀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*Kie4Oup4lryoVmtcLnAm5A.png" /><figcaption>Images generated. Image by the author.</figcaption></figure><p>Well, that is pretty good for a small network aye!</p><h4>Takeaways</h4><ol><li>A human face contains multiple features and some of the features are very complicated such as freckles and facial hair. To generate proper images we might need images with high resolution.</li><li>Provided with the high-resolution images for training we might need to build a better and deeper model for better accuracies.</li><li>Based on the input image we can further increase the depth and number of layers of the model.</li><li>Increasing the resolution can surely help us improve the model and capture more features precisely.</li><li>The samples generated can be further improved by tweaking the parameters such as learning rate, batch size, and training for more number of epochs. The loss of the generator is fluctuating and is not decreasing.</li><li>The CelebA data mostly contains images of different celebrities at different angles and lighting conditions.</li></ol><h3>Conclusion</h3><p>We have seen how to generate realistic faces with DCGAN implementation on the celebA dataset. The images generated can be further improved by tuning the hyperparameters. One could also opt for deeper layers than the one here. Doing so would however result in an increased number of parameters which again would take a lot of time to train. Now open your Jupyter Notebook and implement the same. In the next article, I shall walk you through the generation of the Street View House Numbers using the SVHN dataset. See you at the next one. Cheers!</p><h3>Thank you.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40b96147a1c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/celebrity-face-generation-with-deep-convolutional-gans-40b96147a1c9">Celebrity Face Generation With Deep Convolutional GANs</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Things you should know before writing for Medium publications]]></title>
            <link>https://medium.com/analytics-vidhya/things-you-should-know-before-writing-for-medium-publications-8aeba7a5664?source=rss-7bd459d521f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8aeba7a5664</guid>
            <category><![CDATA[médium]]></category>
            <category><![CDATA[publication]]></category>
            <category><![CDATA[writing-tips]]></category>
            <category><![CDATA[blogging]]></category>
            <category><![CDATA[writing]]></category>
            <dc:creator><![CDATA[NVS Yashwanth]]></dc:creator>
            <pubDate>Tue, 22 Sep 2020 17:11:34 GMT</pubDate>
            <atom:updated>2020-09-22T17:11:34.822Z</atom:updated>
            <content:encoded><![CDATA[<h4>Medium</h4><h4>Having patience and keeping it original is the key</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LLrpFfYO_jPET5Oc" /><figcaption>Photo by <a href="https://unsplash.com/@andrewtneel?utm_source=medium&amp;utm_medium=referral">Andrew Neel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Medium — A place to write ❤️</h3><p>I started writing on medium about a month ago. Before that, I was hooked to medium. I made sure I read 1-2 articles a day.</p><p>I am an ECE undergraduate with a passion to build a career in the field of Machine Learning and Data Science. Every time I searched something related to Machine Learning, Deep Learning, and Data Science, I found myself on medium. And from my experience, I understood concepts better via articles on Medium than from videos.</p><p>If you don&#39;t know, there is always an article out there for anything you would want to learn or read about. Go and check for yourself. After knowing this, why should you even bother to write on Medium? One could just read and get done with it. Saves time! 👀</p><h3>So why should you write?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zpej8IGNFnv9cmuA" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I would like to answer this question based on my personal experience. Ever since I decided to build a career in Machine Learning and Data Science, over time I made notes (which is a lot) hoping it would come handy someday.</p><blockquote><em>“If you can’t explain it simply, you don’t understand it well enough.”</em></blockquote><blockquote><em>- Albert Einstein</em></blockquote><p>Read that quote again. It is true. Most of the concepts on ML and other challenging subjects might seem interesting, but when you start learning, the math will really put you off. So it&#39;s better to have a clear understanding of the same. And you always won&#39;t find articles which explain concepts from basics. There is always a prerequisite. So you will end up backtracking.</p><blockquote>“If you want to master something, teach it.”</blockquote><blockquote>— Richard Feyman</blockquote><p>If you really want to understand something better than you already do, write it in the easiest way possible. This will help you look back at concepts and understand them better when needed.</p><h4>What if am wrong at something? 👀</h4><p>Editors here on Medium are amazing. They reach out within 1-2 days, if lucky an hour! Based on the volume of submissions they receive, they would point out your mistakes and give you personalized feedback. So it is very useful.</p><h3>It is not about the money and views</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r4aGAGYhyrR1WgKa" /><figcaption>Photo by <a href="https://unsplash.com/@jpvalery?utm_source=medium&amp;utm_medium=referral">Jp Valery</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you think writing on Medium will make you a good amount of money, then the answer is NO! Check the statistics, just 8% of the writers earn above $100.</p><p>If that is the reason you are writing, then please don&#39;t! ✋</p><blockquote>Write to impress yourself. Write to make yourself understand things better than you did before. Share your work on LinkedIn, Twitter and Quora. Build connections. Share your knowledge. That is what this is all about.</blockquote><h3>Keep it original</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JG9AdMi0EDYZl5vG" /><figcaption>Photo by <a href="https://unsplash.com/@gavla?utm_source=medium&amp;utm_medium=referral">Gavin Allanwood</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Yes, everyone will say the same thing. KEEP IT ORIGINAL. 🙏</p><p>If copy paste aka ctrl-c &amp; ctrl-v is what you are up to, then you should stop right away. Most of the top publications have plagiarism software so you would not make it.</p><h4>Why am I not getting accepted?</h4><p>The top 4 reasons you don&#39;t get accepted are:</p><ol><li>The publication you submitted may not be interested in that particular topic. So check out they&#39;re about page and see what they are looking for.</li><li>Too short or too long. Don&#39;t write a 2min read-time article or a 30min read-time. Usually, 4–8mins is the sweet spot.</li><li>I can’t stress enough on this one. IMAGES! Please make sure you have the right to use the images. Usually, Creatives Common License is something you should look out for. Unsplash is a good place for that. If you want to experiment and have got all the time for it, download Adobe Xd. Make your own images. Although it is meant for UI/UX design, you can use it for pretty much anything.</li><li>Grammatical errors. Please use <a href="https://app.grammarly.com/">Grammarly</a> for the same. <a href="http://www.hemingwayapp.com/">Hemingway Editor</a> is a good choice too.</li></ol><h3>What should you write?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S_R8wMeYYecaTGmX" /><figcaption>Photo by <a href="https://unsplash.com/@hamann?utm_source=medium&amp;utm_medium=referral">niklas_hamann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Anything! Yes, anything!</p><p>I suggest you write something you are already working on or studying. Say a course or a recent project or your experience using software or that one Machine learning concept you really want to understand better.</p><blockquote>“Either write something worth reading or do something worth writing.”</blockquote><blockquote>— Benjamin Franklin</blockquote><h3>At last, have some patience 🙏</h3><p>Please note that the volume of submissions is a lot. So editors take time to review your submission. If you don&#39;t hear from the publication, I suggest you remove it and re-submit.</p><h3>Conclusion</h3><p>Medium is a great place to write and learn things that matter. Writing about things that matter to you or things you want to understand better is the best way to begin your journey as a writer on Medium. Remember to keep it original and make a note of the common mistakes that could get you rejected from being published by top publications. Enjoy writing. Peace.</p><h4>See you at the next one! Thank you</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8aeba7a5664" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/things-you-should-know-before-writing-for-medium-publications-8aeba7a5664">Things you should know before writing for Medium publications</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Bias-Variance Tradeoff?]]></title>
            <link>https://medium.com/data-science/what-is-bias-variance-tradeoff-c8b19772e054?source=rss-7bd459d521f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8b19772e054</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[bias-variance-tradeoff]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[underfitting]]></category>
            <dc:creator><![CDATA[NVS Yashwanth]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 13:00:35 GMT</pubDate>
            <atom:updated>2020-11-06T13:09:39.286Z</atom:updated>
            <content:encoded><![CDATA[<h4>Machine Learning</h4><h4>Avoid the mistake of overfitting and underfitting</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0UIAHXhCs6GtFonk" /><figcaption>Photo by <a href="https://unsplash.com/@visualsbyroyalz?utm_source=medium&amp;utm_medium=referral">Anastase Maragos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a machine learning practitioner, it is important to have a good understanding of how to build effective models with high accuracy. A common pitfall in training a model is overfitting and underfitting.</p><p>Let us look at these topics so the next time you build a model, you would exactly know how to avoid the mistake of overfitting and underfitting.</p><h3>Bias-Variance Trade-off</h3><p><em>The two variables to measure the effectiveness of your model are bias and variance.</em></p><p>Please know that we are talking about the effectiveness of the model. If you are wondering about model validation, that is something we will discuss in another article.</p><p><strong><em>Bias </em></strong><em>is the error or difference between points given and points plotted on the line in your training set.</em></p><p><strong><em>Variance </em></strong><em>is the error that occurs due to sensitivity to small changes in the training set.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*BVhTW4c1FPFa41ReTqIBXQ.jpeg" /><figcaption>Bias-Variance. Image by the author. (Made using Adobe Xd)</figcaption></figure><p>I’ll be explaining bias-variance further with the help of the image above. So please follow along. To simply things, let us say, the error is calculated as the difference between predicted and observed/actual value. Now, say we have a model that is very accurate. This means that the error is very less, indicating a <strong>low bias and low variance. </strong>(As seen on the top-left circle in the image).</p><p><strong>If the variance increases</strong>, the data is spread more which results in lower accuracy. (As seen on the top-right circle in the image).</p><p><strong>If the bias increases</strong>, the error calculated increases. (As seen on the bottom-left circle in the image).</p><p><strong>High variance and high bias</strong> indicate that data is spread with a high error. (As seen on the bottom-right circle in the image)</p><p>This is <strong>Bias-Variance Tradeoff</strong>. Earlier, I defined <strong>bias </strong>as a measure of error between what the model captures and what the available data is showing, and <strong>variance </strong>being the error from sensitivity to small changes in the available data. A model having <strong>high variance</strong> captures random noise in the data.</p><p>We want to find the best fit line that has <strong>low bias and low variance. </strong>(As seen on the top-left circle in the image).</p><p><strong>How do parameters affect our model?</strong></p><p>Model complexity keeps increasing as the number of parameters increase. This could result in <strong>overfitting, </strong>basically <strong>increasing variance and decreasing bias.</strong></p><p>Our aim is to come up with a point in our model where the decrease in bias is equal to an increase in variance. So how do we do this? Let us look at the Model fitting.</p><h3>Model Fitting</h3><p>We can find a line that represents the general direction of the points but might not represent every point in the dataset. This would be the <strong>best fit model.</strong></p><h4>Why not use higher-order polynomials always?</h4><p>Good question. Sadly, the answer is no. By doing so, we would have created a model that fits our training data very well but fails to generalize beyond the training set (say any testing data that the model was not trained on). Therefore our model performs poorly on the test data giving rise to less accuracy. This problem is called <strong>over-fitting.</strong> We also say that the model has <strong>high variance and low bias.</strong></p><p>Similarly, we have another issue. It is called <strong>underfitting.</strong> It occurs when our model neither fits the training data nor generalizes on the new data (say any testing data that the model was not trained on). Our model is underfitting when we have<strong> high bias and low variance.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*NJnMs89pwUO9ZjORpXBohA.png" /><figcaption>Regression line. Image from <a href="https://en.wikipedia.org/wiki/Overfitting#/media/File:Overfitted_Data.png">Wikipedia</a>.</figcaption></figure><blockquote>The image above shows a blue line which is a polynomial regression line. The straight black line is that of a linear function. Although the polynomial function is a perfect fit, the linear function can be expected to generalize better. Thus, we can say that the polynomial function is <strong>overfitting, </strong>on the other hand, the straight line is the <strong>best fit. </strong>Think of an imaginary line that hardly passes through any of those points. That would be <strong>underfitting.</strong></blockquote><h4>How to overcome Underfitting &amp; Overfitting for a regression model?</h4><ul><li><strong>To overcome underfitting</strong> or high bias, we can add new parameters to our model so that the model complexity increases thus reducing high bias.</li><li><strong>To overcome overfitting</strong>, we could use methods like reducing model complexity and regularization.</li><li>We will discuss regularization in another article.</li></ul><h3>Conclusion</h3><p>I hope you understood the tradeoff between a model’s ability to minimize bias and variance, which plays an important role in achieving the best fit for your machine learning model.</p><h4>See you in the next one. Thank you!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8b19772e054" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-is-bias-variance-tradeoff-c8b19772e054">What is Bias-Variance Tradeoff?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative Adversarial Networks]]></title>
            <link>https://medium.com/data-science/generative-adversarial-networks-6a17673db367?source=rss-7bd459d521f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a17673db367</guid>
            <category><![CDATA[gans]]></category>
            <category><![CDATA[mnist]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[NVS Yashwanth]]></dc:creator>
            <pubDate>Sat, 19 Sep 2020 03:48:48 GMT</pubDate>
            <atom:updated>2020-09-19T12:46:11.124Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep Learning</h4><h4>Understanding the GAN game with MNIST</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YitjqXaAUO-97D2x" /><figcaption>Photo by <a href="https://unsplash.com/@amandadalbjorn?utm_source=medium&amp;utm_medium=referral">Amanda Dalbjörn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What are Generative Adversarial Networks (GANs)?</h3><p>Designed by <a href="https://en.wikipedia.org/wiki/Ian_Goodfellow">Ian Goodfellow</a> and his colleagues in 2014, GANs consist of two neural networks that are trained together in a zero-sum game where one player’s loss is the gain of another.</p><p><strong><em>To understand GANs we need to be familiar with generative models and discriminative models.</em></strong></p><p><strong><em>Generative models</em></strong><em> try to output new data points using the distribution from the training set. These models generate new data instances. These models capture joint probability p(X, Y)</em></p><p><strong>Types of Generative models<br></strong>1. Explicit density models<br>2. Implicit density models</p><p><em>Explicit density models define an explicit density function while implicit density models define a stochastic procedure that can directly generate data.</em></p><p>If you are interested in reading more about generative models, check out this popular GitHub repository below.</p><p><a href="https://github.com/wiseodd/generative-models">wiseodd/generative-models</a></p><p><strong><em>On the other hand, Discriminative models </em></strong><em>capture conditional probabilities p(X/Y) and they differentiate different data instances.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*wYEVmlHOfaV1YekJUf4Orw.png" /><figcaption><a href="https://developers.google.com/machine-learning/gan/generative">Image from Source: Google Developers.</a> Licensed under the Creative Commons Attribution 4.0 License.</figcaption></figure><p>Generative models solve difficult tasks. The level of attention detail is more compared to that in discriminative models. Simply speaking generative models do more work. Generative models try to approximate the real data distribution as closely as possible.</p><p>In the figure above we can see that the discriminative model tries to separate 0’s and 1’s data space. Whereas the generative models closely approximate the 0’s and 1’s data space.</p><blockquote>Now that you know the basic definitions of generative and discriminative models, let us learn about GANs.</blockquote><h3>The Discriminator &amp; Generator networks — The GAN Game</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YX9elEWQh5lPqjZ7" /><figcaption>Photo by <a href="https://unsplash.com/@jeshoots?utm_source=medium&amp;utm_medium=referral">JESHOOTS.COM</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>Generative Adversarial Networks (GANs) are generative models. They generate whole images in parallel. GANs consist of 2 networks: Discriminator &amp; Generator networks</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*CNPLBYjVDIAinfI5MPMOjg.png" /><figcaption><a href="https://developers.google.com/machine-learning/gan/gan_structure">Image from Source: Google Developers.</a> Licensed under the Creative Commons Attribution 4.0 License.</figcaption></figure><p><strong><em>GANs use a differentiable function. This is usually a neural network. We call it the generator network.</em></strong><em> This generator network takes random inputs. These inputs are noise. This noise is given to a differentiable function that transforms and reshapes the same into a recognizable structure. This could be an image and the same is highly dependent on the noise at the input of the differentiable function.</em></p><p>For various noise inputs, we can generate many images. However, the generator network immediately doesn&#39;t start giving out realistic images. We need to train it.</p><blockquote>How do we train this generator network? Probably the same way as any other network? Actually no!</blockquote><p>Generator networks see many images and try to output something similar to the same probability distribution. How is that done? 👀</p><p><strong><em>Here comes the Discriminator, a regular neural network classifier. The discriminator guides our generator network.</em></strong></p><p>For the sake of simplicity let us call the <strong>output images of the generator network as fake images.</strong> The output of the generator, the fake images, are given to the discriminator as the input. The <strong>Discriminator also sees so-called real images from the training data. </strong>The discriminator then outputs the probability that the input is a real image. So a 1 for real images, and 0 for fake images. Meanwhile, the generator also tries to output images that could be assigned a probability of 1 by the discriminator.</p><p>Most machine learning models try to minimize some cost function by optimizing the parameters. If we were to assign cost functions to GANs, we can say the cost for the discriminator is negative of the cost of the generator and vice versa.</p><p>So let us try to understand how GANs work by assuming discriminator and generators as 2 players and a say a function f.</p><p>The generator tries to decrease the output value of the function f, while the discriminator tries to increase it. Let us assume this is done until we reach an equilibrium where neither the generator can decrease the output value of the function f, nor the discriminator can increase it. Since we use 2 optimization algorithms simultaneously, one for the generator and the other for the discriminator, we may never reach an equilibrium. Adam optimizer is a good choice.</p><p>Briefly speaking, the generator and discriminator compete, where the generator gives fake data to the discriminator. The discriminator which also sees training data, predicts if the received image is real or fake.</p><p>Look at this example below from google developers&#39; machine learning crash course.</p><p>The generator begins with unrealistic images and quickly learns to fool the discriminator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*YgRW9RZTPMnl4c3mDqlHkw.png" /><figcaption><a href="https://developers.google.com/machine-learning/gan/gan_structure">Image from Source: Google Developers.</a> Licensed under the Creative Commons Attribution 4.0 License.</figcaption></figure><p>Thus, the generator is trained over time to fool the discriminator to make it look like the fake images are much like the real ones that the discriminator sees.</p><h4>So how does the training process look like?</h4><p>During the training process of the discriminator, it is shown real images and uses computes the discriminator loss. It classifies both real and fake images from the generator and discriminator loss penalizes the discriminator if any image is incorrectly classified. Through backpropagation, the discriminator updates its weights.</p><p>Similarly, the generator is given noisy inputs to generate fake images. These images are given to the discriminator and the generator loss penalizes the generator for producing a sample that the discriminator network classifies as fake. Weights are updated through backpropagation right from the discriminator into the generator.</p><p>It is important to note that the generator must be constant during the discriminator training phase. Similarly, the discriminator remains constant during the generator training phase. Thus GAN training proceeds in an alternating fashion.</p><h3>MNIST GAN</h3><blockquote>In this section, we will learn to design a GAN that can generate new images of handwritten digits. We will use the famous MNIST dataset. <a href="http://yann.lecun.com/exdb/mnist/">Get it here.</a></blockquote><h4>The Discriminator architecture</h4><p>The discriminator is going to be a typical linear classifier.</p><p>The activation function we will be using is <a href="https://pytorch.org/docs/stable/nn.html#torch.nn.LeakyReLU">Leaky ReLu</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*apKmKLQ0PXZrEVe7H-cx0w.png" /><figcaption><a href="https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html#torch.nn.LeakyReLU">Image from PyTorch documentation</a>. (Open Source)</figcaption></figure><p><strong>Why leaky ReLu?</strong><br>We should use a leaky ReLU to allow gradients to flow backward through the layer unhindered. A leaky ReLU is like a normal ReLU, except that there is a small non-zero output for negative input values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f11b8660c52cd8fbf5d3596ddc2798b6/href">https://medium.com/media/f11b8660c52cd8fbf5d3596ddc2798b6/href</a></iframe><h4>The Generator architecture</h4><p>The generator uses latent samples to make fake images. These latent samples are vectors which are mapped to the fake images. A<strong> </strong>latent vector is just a compressed, feature-level representation of an image!</p><p>To understand what is a latent sample, consider an autoencoder. The outputs that connect the encoder and decoder portion of a network are made up of a compressed representation that could also be referred to as a <strong>latent vector.</strong></p><p>The activation function for all the layers remains the same except we will be using <a href="https://pytorch.org/docs/stable/generated/torch.nn.Tanh.html#torch.nn.Tanh">Tanh</a> at the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*Pq3FdNAzvu_TFAP3j5r3ZA.png" /><figcaption><a href="https://pytorch.org/docs/stable/generated/torch.nn.Tanh.html#torch.nn.Tanh">Image from PyTorch documentation</a>. (Open Source)</figcaption></figure><p><strong>Why Tanh at the output?</strong><br>The generator has been found to perform the best with 𝑡𝑎𝑛ℎtanh for the generator output, which scales the output to be between -1 and 1, instead of 0 and 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eadd2820c1b0f5c419290f70263fcee7/href">https://medium.com/media/eadd2820c1b0f5c419290f70263fcee7/href</a></iframe><h4><strong>Scaling images</strong></h4><p>We want the output of the generator to be comparable to the real images pixel values, which are normalized values between 0 and 1. Thus, we’ll also have to scale our real input images to have pixel values between -1 and 1 when we train the discriminator. <br>This will be done during the training phase.</p><h4>Generalization</h4><p>To help the discriminator generalize better, the labels are <strong>reduced a bit from 1.0 to 0.9</strong>. For this, we’ll use the parameter smooth; if True, then we should smooth our labels. In PyTorch, this looks like:<br>labels = torch.ones(size) * 0.9</p><p>We also made use of dropout layers to avoid overfitting.</p><h4>Loss calculation</h4><p>The discriminator’s goal is to output a 1 for real and 0 for fake images. On the other hand, the generator wants to make fake images that closely resemble the real ones.</p><p><em>Thus we can say if </em><strong><em>“D”</em></strong><em> represents the loss for the discriminator, then the following can be stated:<br></em><strong><em>The goal of discriminator :</em></strong><em> D(real_images)=1 &amp; D(fake_images)=0<br></em><strong><em>The goal of generator:</em></strong><em> D(real_images)=0 &amp; D(fake_images)=1</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0187a1681b2088bf440607ab7a0985c2/href">https://medium.com/media/0187a1681b2088bf440607ab7a0985c2/href</a></iframe><p>We will use <a href="https://pytorch.org/docs/stable/nn.html#bcewithlogitsloss">BCEWithLogitsLoss</a>, which combines a sigmoid activation function (we want the discriminator to output a value 0–1 indicating whether an image is <em>real or fake</em>) and binary cross-entropy loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*1I9MpiCXDgoY2XvY42tYQA.png" /><figcaption>Equation of Binar Cross-Entropy Loss. Image by the author.</figcaption></figure><h4>Training</h4><p>As mentioned earlier, Adam is a suitable optimizer.</p><p>The generator takes in a vector z and outputs fake images. The discriminator alternates between training on the real images and that of the fakes images produced by the generator.</p><h4>Steps involved in discriminator training:</h4><ol><li>We first compute the loss on real images</li><li>Generate fake images</li><li>Compute loss on fake images</li><li>Add the loss of the real and fake images</li><li>Perform backpropagation and update weights of the discriminator</li></ol><h4>Steps involved in generator training:</h4><ol><li>Generate fake images</li><li>Compute loss on fake images with inversed labels</li><li>Perform backpropagation and update the weights of the generator.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f44823093d237f7f4a613ce80bf574a/href">https://medium.com/media/8f44823093d237f7f4a613ce80bf574a/href</a></iframe><h4>Training loss</h4><p>We shall plot generator and discriminator losses against the number of epochs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b8d55daebdb796c75dd5350ca519abc/href">https://medium.com/media/2b8d55daebdb796c75dd5350ca519abc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*ecT7umpag5-76EFjfqySpw.png" /><figcaption>Training losses. Image by the author.</figcaption></figure><h4>Samples generated by the generator</h4><p><strong>At the start</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8a8ee94bc84e22d4cfa4605df4b8989/href">https://medium.com/media/d8a8ee94bc84e22d4cfa4605df4b8989/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*MCaDJSr7SeBcNMUWsJMexw.png" /><figcaption>Image by the author.</figcaption></figure><p><strong>Overtime</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/759f7ee6e6f94d2aa1bd51f05e2e1460/href">https://medium.com/media/759f7ee6e6f94d2aa1bd51f05e2e1460/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*rfpUrVtCrwKIVTJa3IMKuw.png" /><figcaption>Image by the author.</figcaption></figure><p>This way the generator starts out with noisy images and learns over time.</p><blockquote>You can check out the code and readme file on my GitHub profile as well.</blockquote><p><a href="https://github.com/NvsYashwanth/MNIST-GAN">NvsYashwanth/MNIST-GAN</a></p><h3>Conclusions</h3><p>Since the time Ian Goodfellow and his colleagues at the University of Montreal designed GANs, they exploded with popularity. The number of applications is remarkable. GANs were further improved by many variations some of which are CycleGAN, Conditional GAN, Progressive GAN, etc. <a href="https://developers.google.com/machine-learning/gan/applications">To read more about these check out this link</a>. Now open a Jupyter notebook and try to implement whatever you learned.</p><h4>Thank you. See you at the next one.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a17673db367" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/generative-adversarial-networks-6a17673db367">Generative Adversarial Networks</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is batch normalization?]]></title>
            <link>https://medium.com/data-science/what-is-batch-normalization-46058b4f583?source=rss-7bd459d521f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/46058b4f583</guid>
            <category><![CDATA[batch-normalization]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[covariate-shift]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[NVS Yashwanth]]></dc:creator>
            <pubDate>Fri, 18 Sep 2020 18:33:05 GMT</pubDate>
            <atom:updated>2020-09-18T18:33:05.170Z</atom:updated>
            <content:encoded><![CDATA[<h4>Deep learning</h4><h4>How does it help?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rbw91cP12mKPlfC9" /><figcaption>Photo by <a href="https://unsplash.com/@jrarce?utm_source=medium&amp;utm_medium=referral">Ricardo Arce</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Batch Normalization</h3><p>Batch normalization was introduced by Sergey Ioffe’s and Christian Szegedy’s 2015 paper <a href="https://arxiv.org/pdf/1502.03167.pdf">Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift</a>.</p><p><strong><em>Batch normalization scales layers outputs to have mean 0 and variance 1. The outputs are scaled such a way to train the network faster. It also reduces problems due to poor parameter initialization.</em></strong></p><h3>The intuition behind Normalization</h3><p>We know that normalization or feature scaling can speed up the learning process. The intuition behind batch normalization is similar.<strong> Batch normalization does the same for hidden units.</strong></p><p>Why the word batch?<strong> </strong>Because it normalized the values in the current batch. These are sometimes called the <strong>batch statistics</strong>.</p><blockquote>Specifically, batch normalization normalizes the output of a previous layer by <strong>subtracting the batch mean and dividing by the batch standard deviation</strong>.</blockquote><p>This is much similar to feature scaling which is done to speed up the learning process and converge to a solution.</p><h4>Internal Covariance Shift</h4><p>You might have heard a fancy word thrown around when talking about batch normalization, it is the <strong>internal covariance shift</strong>. Consider a network that learns a function that maps x to y. The internal covariance shift refers to the change in the distribution of the input x. If a change occurs, our network will not be efficient enough and cant generalize. Thus we will have to train all over.</p><p>Consider this example to understand the covariance shift. If we train a network to detect brown dog images and later you end applying this network to data with colored dog images it would not be able to perform well and we would have to train again. This change in the distribution of input is the covariance shift. So how does batch normalization help here?</p><h3>Batch normalization to the rescue</h3><p>If the distribution of the inputs to every layer is the same, the network is efficient. <strong>Batch normalization standardizes the distribution of layer inputs to combat the internal covariance shift.</strong> It controls the amount by which the hidden units shift.</p><h3>How to perform batch normalization?</h3><p>We take the average value out of each layer called <strong>μB</strong>. This is called calculated as the sum of all values of layer <strong>x_i </strong>divided by average on all <strong>m </strong>values<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*OpamPv9PZSuQkW62T-6iFQ.png" /><figcaption>Mean. Image by the author.</figcaption></figure><p>We then calculate the variance σ²B as follows:<br>1. Subtracting the μB from every value which is the deviation of every value and ake the square for squared deviation<br>2. Sum up the results of doing that for each of the values, then divide by the number of values <strong>m</strong>, to get the average, or mean squared deviation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Jrb_lcnNIoSrYyt2Up7azg.png" /><figcaption>Variance. Image by the author.</figcaption></figure><p>We then find the standard deviation as the sum of mean squared deviation and epsilon under root. The epsilon is a constant value as small as 0.001. This is added to avoid cases of division by zero and also to increase variance.</p><p><strong>How is the increase in variance helpful? </strong><br>The variance of a population is typically more than the variance for any sample taken from that population, especially in cases of small sample size where values are near the peak of the population distribution, so increasing the variance a little bit for each batch helps take that into account.</p><p>Now that we calculated mean and standard deviation, we can normalize as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*uekEO7cHOTbe6zdNM95ghQ.png" /><figcaption>Normalized value. Image by the author.</figcaption></figure><p>The normalized values are then multiplied by γ and added with β. These are the learnable parameters which serve in further scaling the normalized values. The final batch normalized value is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*EZWSKDZuS3aIDwsKU0DM-g.png" /><figcaption>Batch normalized value. Image by the author.</figcaption></figure><p>The batch normalization can be applied before and after the activation function. However, research shows its best when applied before the activation function.</p><blockquote><em>In PyTorch, you can use </em><strong><em>BatchNorm1d</em></strong><em> to implement batch normalization on linear outputs and </em><strong><em>BatchNorm2d</em></strong><em> for 2D outputs in the case of filtered images from convolutional layers.</em></blockquote><h3>What are the benefits?</h3><ol><li>Train faster.</li><li>Use higher learning rates.</li><li>Parameter initialization is easier.</li><li>Makes activation functions viable by regulating the inputs to them.</li><li>Better results overall.</li><li>It adds noise which reduces overfitting with a regularization effect. Thus make sure to use less dropout when you apply batch normalization as dropout itself adds noise.</li></ol><h3>Conclusion</h3><p>Batch normalization when applied to neural networks produces better results by normalizing the inputs to hidden layers. Fun fact is that batch normalization was introduced after VGG, so VGG can be improved with batch normalization for better results on ImageNet. The ability to use higher learning rates without vanishing or exploding gradients is promising as well. Having noted the issues that batch normalization solves, I hope you now have a better understanding of the same.</p><h4>See you at the next one! Thank you.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46058b4f583" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-is-batch-normalization-46058b4f583">What is batch normalization?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why convexity is the key to optimization]]></title>
            <link>https://medium.com/data-science/understand-convexity-in-optimization-db87653bf920?source=rss-7bd459d521f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/db87653bf920</guid>
            <category><![CDATA[convexity]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[NVS Yashwanth]]></dc:creator>
            <pubDate>Wed, 09 Sep 2020 13:31:56 GMT</pubDate>
            <atom:updated>2020-09-10T09:49:06.486Z</atom:updated>
            <content:encoded><![CDATA[<h4>Machine Learning</h4><h4>It is easy with convex cost functions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*2Pqk33Kv7-Y_BJnfSNcrGg.png" /><figcaption>A Convex function. Source <a href="https://en.wikipedia.org/wiki/Convex_function">Wikipedia</a>.</figcaption></figure><p>The most interesting thing you would first come across when starting out with machine learning is the optimization algorithm and to be specific, it is the gradient descent, which is a first-order iterative optimization algorithm used to minimize the cost function.</p><p>The intuition behind gradient descent is converging to a solution, which could be a local minimum in the neighborhood or in best-case, the global minimum.</p><p>Everything seems fine and okay until you start questioning yourself about the convergence problem. Having a good understanding of convexity helps you prove the intuition behind the idea of gradient descent. So let us discuss the same.</p><blockquote>I hope you have a good understanding of gradient descent. Check out this article for a recap.</blockquote><p><a href="https://nvsyashwanth.github.io/machinelearningmaster/understanding-gradient-descent/">Understanding Gradient Descent</a></p><h3>Convex Sets</h3><p><strong><em>To simply things, think of convex sets as shapes where any line joining 2 points in this set is never outside the set. This is called a convex set.</em></strong></p><p>Take a look at the examples below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*5q6hqLS11phsiIqgnif-BQ.png" /><figcaption>Understanding Convex sets. Image by the author (made using Adobe Xd).</figcaption></figure><p>It is evident that any line joining 2 points on a circle or say a square (the shapes on extreme left and middle), will have all the line segments within the shape. <strong>These are examples of convex sets.</strong></p><p>On the other hand, the shape on the extreme right in the figure above has part of a line outside the shape. <strong>Thus, this is not a convex set.</strong></p><p>A convex set C can be represented as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*l7yHspoNGM5VVZ6mUFib-g.png" /><figcaption>Convex set condition. Image by the author</figcaption></figure><h3>Epigraph</h3><p>Consider the graph of a function f. <br><strong><em>An epigraph is a set of points lying on or above the function’s graph.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*AL1ayCEq6p0vBAqT6ZPiIg.png" /><figcaption>The epigraph of a function. Image by the author (made using Adobe Xd).</figcaption></figure><h3>Convex Function</h3><p>Okay, now that you understand what are convex sets and epigraphs, we can talk about convex functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MXhZhjxj9YZs4DZt.png" /><figcaption>A convex function with its epigraph. Source <a href="https://en.wikipedia.org/wiki/Convex_function">Wikipedia</a>.</figcaption></figure><p><strong><em>A function f is said to be a convex function</em></strong><em> </em><strong><em>if its epigraph is a convex set (as seen in the green figure below on the left)</em></strong><em>. <br>This means that every line segment drawn on this graph</em><strong><em> is always</em></strong><em> equal to or above the function graph. Pause a minute and check for yourself.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*s_cLMrwgbHFyM0bctXuloQ.png" /><figcaption>Understanding convex functions. Image by the author (made using Adobe Xd).</figcaption></figure><p><strong><em>This means that a function f is not convex if there exist two points x, y such that the line segment joining f(x) and f(y), is below the curve of the function f</em></strong><em>. </em><strong><em>This causes the loss of convexity of the epigraph (as seen in the red-figure above on the right ). <br></em></strong><em>This means that every line segment drawn on this graph</em><strong><em> is</em></strong><em> </em><strong><em>not always</em></strong><em> equal to or above the function graph. The same can be proven by taking points on the bends.</em></p><h3>Testing for convexity</h3><p>Most of the cost functions in the case of neural networks would be non-convex. Thus you must test a function for convexity.</p><p><strong><em>A function f is said to be a convex function if the seconder-order derivative of that function is greater than or equal to 0.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*RHFmQjIbJRM0yBsn2DjQ1Q.png" /><figcaption>Condition for convex functions.</figcaption></figure><p><strong>Examples of convex functions:</strong> y=eˣ, y=x². Both of these functions are differentiable twice.</p><p><strong><em>If -f(x) (minus f(x)) is a convex function, then the function is called a concave function.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/124/1*S6jHo3kIqUtT4-uYhEqHfQ.png" /><figcaption>Condition for concave functions.</figcaption></figure><p><strong>Examples of concave functions:</strong> y=-eˣ. The function is differentiable twice.</p><p>Let’s check for convexity by plotting the exponential function eˣ.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d4d0513e471b741c7d0f54319255a71/href">https://medium.com/media/3d4d0513e471b741c7d0f54319255a71/href</a></iframe><p><strong>The code output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*8jP0i51ZRXHSKuxAVnNzaw.png" /><figcaption>Convex and concave functions. Image by the author (code output).</figcaption></figure><h3>Convexity in gradient descent optimization</h3><p>As said earlier, gradient descent is a first-order iterative optimization algorithm that is used to minimize a cost function.</p><p>To understand how convexity plays a crucial role in gradient descent, let us take the example of convex and non-convex cost functions.</p><p>For a Linear Regression model, we define the cost function Mean Square Error(MSE), which measures the average squared difference between actual and predicted values. Our goal is to minimize this cost function in order to improve the accuracy of the model. <strong>MSE is a</strong> <strong>convex function (it is differentiable twice). </strong>This means there is no local minimum, but only the global minimum. Thus gradient descent would converge to the global minimum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*fRHql8UVXObqBN6PUhBGPw.png" /><figcaption>MSE equation. Image by the author.</figcaption></figure><p>Now let us consider a non-convex cost function. In this case, take an arbitrary non-convex function as plotted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*tCmKnUQZ240vkEefxQyilQ.png" /><figcaption>Gradient descent on a non-convex function. Image by the author (made using Adobe Xd).</figcaption></figure><p>Instead of converging to the global minimum, you can see that gradient descent would stop at the local minimum because the gradient at that point is zero (slope is 0) and minimum in the neighborhood. One way to solve this issue is by using the concept <a href="https://distill.pub/2017/momentum/">momentum</a>.</p><h3>Conclusion</h3><p>Convex functions play a huge role in optimization. Optimization is the core of a machine learning model. Understanding convexity is really important for the same, which I believe you did from this article.</p><h4>Thank you. See you at the next one.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db87653bf920" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/understand-convexity-in-optimization-db87653bf920">Why convexity is the key to optimization</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How are learning Curves helpful?]]></title>
            <link>https://pub.towardsai.net/learning-curves-d6cfb49908f0?source=rss-7bd459d521f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6cfb49908f0</guid>
            <category><![CDATA[learning-curve]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[learning]]></category>
            <dc:creator><![CDATA[NVS Yashwanth]]></dc:creator>
            <pubDate>Sat, 05 Sep 2020 19:26:06 GMT</pubDate>
            <atom:updated>2020-09-10T09:46:59.714Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/machine-learning">Machine Learning</a></h4><h4>Evaluating machine learning models the right way</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2xX8TlPO6hURgXZF" /><figcaption>Photo by <a href="https://unsplash.com/@isaacmsmith?utm_source=medium&amp;utm_medium=referral">Isaac Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Learning curves are useful in analyzing a machine learning model’s performance over various sample sizes of the training dataset.</strong></h4><blockquote>To understand learning curves, it is important to have a good understanding of the Bias-Variance Tradeoff. You can check out my article regarding the same.</blockquote><p><a href="https://nvsyashwanth.github.io/machinelearningmaster/bias-variance/">Bias-Variance</a></p><h3>Evaluating Models</h3><blockquote>“Always plot learning curves while evaluating models”</blockquote><p>Okay, so the basic thing we know is, if a model performs well on the training data but generalizes poorly, then the model is <strong>overfitting</strong>. If it performs poorly on both, then it is <strong>underfitting.</strong></p><p>The hyperparameters must be set in such a way that, both bias and variance are as low as possible.</p><h4>How are Learning Curves helpful?</h4><blockquote>“Learning curves are plots of the model’s performance on the training set and the validation set as a function of varying samples of training dataset. “</blockquote><p>To be specific, learning curves show training &amp; validation scores on the y-axis against varying samples of the training dataset on the x-axis.</p><p>The training &amp; validation scores could be any evaluation metric like MSE, RMSE, etc. on your training and validation sets.</p><p>Learning curves can be used to understand the bias and variance errors of a model.</p><h4>Understanding Learning Curves</h4><p>Let’s generate some random data, fit a linear regression model for the same, and plot the learning curves for evaluating the model.</p><pre>from sklearn.linear_model import LinearRegression<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import mean_squared_error as mse<br>import numpy as np<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>plt.style.use(&#39;seaborn&#39;)<br>X = 1 * np.random.rand(100, 1)<br>y = 3 +  3* X + np.random.randn(100, 1)<br>X_train,X_val,y_train,y_val=train_test_split(X,y,test_size=0.2)<br>regressor=LinearRegression()<br>regressor.fit(X_train,y_train)<br>predictions=regressor.predict(X_val)</pre><pre>plt.figure(1,figsize=(15,5))<br>plt.subplot(121)<br>plt.scatter(X,y)<br>plt.plot(X_val,predictions,color=&#39;black&#39;)<br>plt.title(&#39;Scikit Learn Linear Regression&#39;)</pre><pre>train_errors=[]<br>val_errors=[]<br>plt.subplot(122)<br>for i in range(1,len(X_train)):<br>    regressor.fit(X_train[:i],y_train[:i])<br>    train_preds=regressor.predict(X_train[:i])<br>    val_preds=regressor.predict(X_val)<br>    train_errors.append(mse(train_preds,y_train[:i]))<br>    val_errors.append(mse(val_preds,y_val))<br>plt.plot(range(1,len(X_train)),np.sqrt(train_errors),label=&#39;Training error&#39;)<br>plt.plot(range(1,len(X_train)),np.sqrt(val_errors),label=&#39;Validation error&#39;)<br>plt.title(&#39;Learning Curves&#39;)    <br>plt.xlabel(&#39;Train set size&#39;)<br>plt.ylabel(&#39;RMSE&#39;)<br>plt.legend()<br>plt.show()</pre><p>Look at the output of the above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ijTORTMacGpZWc1tRCX4Ig.png" /><figcaption>Left: Regression Line; Right: Learning Curves. Image by the author.</figcaption></figure><p>Okay, nice images. But what is the meaning? It may seem too much at the beginning. Take a look at the following steps to understand the code and the images.</p><ol><li>We generated random data (X,y).</li><li>Derived a training &amp; validation dataset from the same.</li><li>Used Scikit Learn’s LinearRegression class to fit a line for our data, which is what the image on the left is about.</li><li>We then fit the model in the same way as above, but this time, we fit the model for training sample size 1 -&gt; entire training dataset size.</li><li>For every sample size of our training set, we make predictions on our training sample size chosen and the entire validation dataset.</li><li>We calculate the RMSE(Root Mean Square Error) and store the same for plotting later. Done!</li></ol><p>We can see training &amp; validation scores converge at a particular point. As seen in the image on the right, the first point of convergence w.r.t x-axis is about training sample size 10. This means that, beyond this point, the model will not benefit from increasing the training sample size. Considering the y-axis, the point of convergence is about RMSE value 1. Now, this is okay, and the model seems to generalize properly.</p><p>However, take an example where the value at the point of convergence corresponding to the y-axis is high (as seen in the image below). It shows that the model is suffering from high bias. This means that training &amp; validation errors are high and the model doesn’t benefit from increasing the training sample size and thus results in underfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*wdjLxj35npLbBLXMICa58A.png" /><figcaption>Learning curves. High bias. Source: <a href="https://www.coursera.org/learn/machine-learning?utm_source=gg&amp;utm_medium=sem&amp;utm_content=07-StanfordML-IN&amp;campaignid=1950458127&amp;adgroupid=69480953983&amp;device=c&amp;keyword=study%20machine%20learning%20online&amp;matchtype=b&amp;network=g&amp;devicemodel=&amp;adpostion=&amp;creativeid=351281535285&amp;hide_mobile_promo&amp;gclid=Cj0KCQjw7sz6BRDYARIsAPHzrNLkyWNF7MP321zRu0AVtBO6DPIqjMDX53EZpmr3ITLSxO_tFxk9xLcaAmQ4EALw_wcB">Andrew Ng’s ML course</a>.</figcaption></figure><p>On the other hand, if there was no visible point of convergence (as seen in the image below), this shows the model is having high variance and has less data. Meaning, the validation errors could be very high and the model would be overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*udywvNAQ7pRbiuZmJCxjlA.png" /><figcaption>Learning curves. High variance. Source: <a href="https://www.coursera.org/learn/machine-learning?utm_source=gg&amp;utm_medium=sem&amp;utm_content=07-StanfordML-IN&amp;campaignid=1950458127&amp;adgroupid=69480953983&amp;device=c&amp;keyword=study%20machine%20learning%20online&amp;matchtype=b&amp;network=g&amp;devicemodel=&amp;adpostion=&amp;creativeid=351281535285&amp;hide_mobile_promo&amp;gclid=Cj0KCQjw7sz6BRDYARIsAPHzrNLkyWNF7MP321zRu0AVtBO6DPIqjMDX53EZpmr3ITLSxO_tFxk9xLcaAmQ4EALw_wcB">Andrew Ng’s ML course</a>.</figcaption></figure><h4>How to improve model performance?</h4><p>In the case of high bias, increase the number of features, or decrease the regularization parameter, thereby increasing the model complexity.</p><p>In the case of high variance, decrease the number of features, or increase the regularization parameter, thereby decreasing the model complexity. To fill the gap, just increase the data you have (not the features).</p><h3>Conclusion</h3><p>Always plot learning curves. Having a good understanding of learning curves helps you evaluate your model and analyze bias-variance problems. Hope you understood the importance of learning curves. See you at the next one.</p><p><strong>Originally published on </strong><a href="https://nvsyashwanth.github.io/machinelearningmaster/learning-curves/"><strong>machinelearningmaster</strong></a><strong>.</strong></p><blockquote><strong><em>Hey, if you liked this article please show your support by smashing that clap button and sharing this article . Follow me for more articles on Machine Learning, Deep Learning, and Data Science. See you at the next one!</em></strong></blockquote><h3>Find me around the web</h3><p><a href="https://nvsyashwanth.github.io/machinelearningmaster/"><strong>Blog</strong>: MachineLearningMaster</a></p><p><a href="https://github.com/NvsYashwanth"><strong>GitHub Profile: </strong>This is where I fork</a></p><p><a href="https://www.linkedin.com/in/nvsyashwanth/"><strong>LinkedIn Profile: </strong>Connecting and sharing professional updates</a></p><p><a href="https://twitter.com/YashwanthNvs"><strong>Twitter:</strong> Sharing tech tweets</a></p><h3>Thank you</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6cfb49908f0" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/learning-curves-d6cfb49908f0">How are learning Curves helpful?</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>