<?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 Shweta Goyal on Medium]]></title>
        <description><![CDATA[Stories by Shweta Goyal on Medium]]></description>
        <link>https://medium.com/@shwetagoyal41?source=rss-bac014ba4117------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*sETH1IcMN0mT-ZRU</url>
            <title>Stories by Shweta Goyal on Medium</title>
            <link>https://medium.com/@shwetagoyal41?source=rss-bac014ba4117------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:07:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shwetagoyal41/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[How to Create a Table with Multiple Foreign Keys in MySQL]]></title>
            <link>https://medium.com/@shwetagoyal41/how-to-create-a-table-with-multiple-foreign-keys-in-mysql-5845adf5fc00?source=rss-bac014ba4117------2</link>
            <guid isPermaLink="false">https://medium.com/p/5845adf5fc00</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[foreign-key]]></category>
            <dc:creator><![CDATA[Shweta Goyal]]></dc:creator>
            <pubDate>Wed, 07 Aug 2024 08:18:35 GMT</pubDate>
            <atom:updated>2024-08-07T08:24:51.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*mf18M7rJ1zlVCM_Y" /><figcaption><a href="https://images.app.goo.gl/TdA6n3FyAa8Vnvd77">Unsplash</a></figcaption></figure><h3>What are Foreign Keys?</h3><p>A foreign key is an attribute or a set of characteristics in a table that links an attribute or a set of attributes to the primary key of another table. When we create a foreign key in a table. The first table is called the <em>child table</em> or <em>referencing table, and </em>the second table where the foreign key refers to the primary key is called the <em>parent table</em> or <em>referenced table</em>.</p><p><strong>Syntax of Foreign Key</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tivu1QDiePaoEb7q" /></figure><p>Let’s understand what each parameter means:</p><ul><li><strong>Constraint_Name: </strong>This specifies the name of the foreign key constraint.</li><li><strong>Referring_Column_Name: </strong>This specifies the name of the foreign key column.</li><li><strong>Referred_Table: </strong>This specifies the name of the parent table.</li><li><strong>Referred_Column:</strong> This specifies the names of the columns that reference the Foreign Key columns.</li></ul><p><strong>Reference-option: </strong>This option is used to check how the foreign key maintains <em>Referential Integrity</em> between the parent and child table using ON DELETE and ON UPDATE clauses. These are the actions that MySql will take when the values are updated or deleted from the table that holds the foreign key constraints.</p><p><strong>What is Referential Integrity?</strong></p><p>Referential Integrity means that the relationships between the tables must be in a clean and consistent state and we maintain this relationship using foreign key constraints.</p><p>In other words, this helps to maintain data integrity. All the references in the relationship must be valid.</p><p><strong>Why it is important?</strong></p><p>Referential Integrity ensures that when a referenced row is deleted, all the associated dependent rows must be deleted. When referential integrity is violated, the action will be rejected whether it is deletion or updating. Let’s understand what are those actions.</p><p>There are five reference options we have:</p><ul><li><strong>CASCADE: </strong>This clause will automatically update or delete the matching rows from the child table when we update or delete the rows from the parent table.</li><li><strong>RESTRICT: </strong>Mysql will reject any update or delete operation from the parent table if there is any matching foreign key value present in the child table.</li><li><strong>NO ACTION: </strong>This is the same as the RESTRICT option.</li><li><strong>SET NULL: </strong>When we update or delete any row from the parent table then the values from the child table in the foreign key columns are set to NULL.</li><li><strong>SET DEFAULT: </strong>This is supported by Mysql parser but not database engines like InnoDB.</li></ul><p><strong>Note:</strong> When we don’t specify any action for ON DELETE or ON UPDATE clause then the default action will always be NO ACTION.</p><h3>Why do we need Foreign Keys?</h3><ul><li>The main purpose of foreign keys is that they add a restriction which is called a foreign key constraint. This constraint helps us to avoid those actions that would break up the links between the tables.</li><li>Foreign keys help us to maintain data integrity for both the linked tables.</li></ul><h3>Foreign key relationships</h3><p>A Foreign key relationship can be:</p><ul><li><strong>One-to-One Relationship (1:1): </strong>It is straightforward when one row in one table is linked with one and only one row in another table and vice-versa which is created using the Primary key and unique Foreign key constraint.</li><li><strong>One-to-Many Relationship (1:M):</strong> In this relationship when one row in one table is linked with multiple rows in another table which is created using the Primary key and Foreign key constraint.</li><li><strong>Many to Many Relationship (M: M):</strong> In this relationship when multiple rows in one table are linked with multiple rows in another table.</li></ul><p>In other words, when one row in one table is linked with multiple rows in another table and a row from the other table is linked with multiple rows in the first table.</p><p>This relationship can be created using a third table called the <strong>Junction table</strong> or <strong>Bridge table. </strong>This third table bridges the two tables together by referencing the Primary keys of each table.</p><p>In this article, we will implement a many-to-many relationship. For simplicity, we will create two foreign keys in one table. We need two different parent tables for primary keys.</p><p><strong>Note:</strong> When we create multiple foreign keys in a child table then each foreign key must have a different parent table.</p><h3>Getting Started with Foreign Keys</h3><p>To perform this relation, First, we need to create a new schema and then we will insert some sample data. Below is a sample database of students and book relationships in which students can take several books or one book can be taken by many students. We will create three tables:</p><ul><li>Student: contains data about students enrolled</li><li>Books: contains data about books</li><li>Department: contains data about the department</li></ul><p>First, we will create our primary key tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dwt5nh3ElDieKdb9" /></figure><p>Now, we will create a junction table called the Department for Foreign Keys. This table will connect our two tables by using primary keys from both tables and will create two foreign keys in this table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m-OYtdwshxWvjf3C" /></figure><p>This is the diagram you will get after creating the above tables in MySQL. As you can see both the primary key tables are connected to the foreign keys table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*mOHgF1k2OmjZtnuI" /></figure><p><strong>Why do we use integer numbers as Foreign Keys to reference Primary Keys?</strong></p><p>There are two reasons for using integers rather than strings:</p><ul><li><strong>To minimize disk space — </strong>Integers only take four bytes for storage while strings take space according to their length + 1 byte. So, Integers are less expensive as compared to strings.</li><li><strong>To avoid duplication — </strong>Variables like names, and genders can have similar information whereas IDs will have different information as they are unique. So, it helps to avoid storing duplicate information.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5845adf5fc00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[List Comprehensions and Nested List Comprehensions in Python]]></title>
            <link>https://medium.com/analytics-vidhya/list-comprehensions-and-nested-list-comprehensions-in-python-86520ee16aa5?source=rss-bac014ba4117------2</link>
            <guid isPermaLink="false">https://medium.com/p/86520ee16aa5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nested-list]]></category>
            <category><![CDATA[list-comprehension]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Shweta Goyal]]></dc:creator>
            <pubDate>Fri, 25 Feb 2022 15:26:58 GMT</pubDate>
            <atom:updated>2024-01-23T10:48:08.800Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding List and Nested list comprehensions in Python</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QzpcTWwNTQaaxDjl" /><figcaption>Photo by <a href="https://unsplash.com/@markuswinkler?utm_source=medium&amp;utm_medium=referral">Markus Winkler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The<a href="https://www.analyticsvidhya.com/blog/2021/06/10-examples-you-should-try-to-master-list-comprehensions-in-python/"> <strong>list</strong> </a>is one of the built-in data structures in Python and it is a group of the same or different types of elements. It is a very tedious task to create a list in Python which involves a <strong>for</strong> loop.</p><p>Python is known for its simplicity and easy-to-understand code. If you know the syntax, then Python is extremely easy to use. In this tutorial, we are going to talk about List Comprehensions that make your code more elegant and readable.</p><p>Let’s get started.</p><h3>List Comprehensions</h3><p>One of the best features of Python is List Comprehensions it helps you to write code in a single line.</p><p>But first, we will see an example in a <strong>for</strong> loop of creating an <a href="https://www.analyticsvidhya.com/blog/2021/06/10-examples-you-should-try-to-master-list-comprehensions-in-python/">exponential list</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CJhuLLb1dG3Pti2ZRiu2-w.png" /></figure><p>Let’s see what we have done in the above example. First, we created a list of expo variables. Then, we created an empty list of expon variables than a variable of ex iterate over an iterable of the expo. After that, the exponential of ex is created and stored in ex. Now, we append the ex in the empty list of expon. Finally, we print the list.</p><p>Now, we will implement the same using <strong>map()</strong> function which is an alternative approach with the <strong>lambda</strong> function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wGwzTnI2lpHKIDAVsF-7Qg.png" /></figure><p>You have to use the list before the map function otherwise, it will give you the address of the map() not the desired output. Here, you don’t have to define a function explicitly,<strong> lambda</strong> does it for you.</p><blockquote><em>The</em><strong><em> map() </em></strong><em>function takes a lambda function and a list while the </em><strong><em>lambda</em></strong><em> function takes one expression and any number of arguments.</em></blockquote><p>The map function will return a new list with the modified values which have been modified by the lambda function. Now, let’s talk about list comprehensions:</p><p>List comprehensions provide a short and compact way to create a list. Let’s see the syntax:</p><blockquote><strong>new_list = [expression for item in iterable if condition]</strong></blockquote><ul><li>Square brackets are necessary to get the output as a list.</li><li><strong><em>Expression</em></strong> or operation which is executed for each value inside the iterable and is followed by <strong><em>for</em></strong> loop</li><li>It is an ordinary <strong><em>for</em></strong> loop which is used to iterate over each item in the iterable. Iterable can be a list, set, string, etc.</li><li><strong><em>if</em></strong> a condition is optional.</li></ul><p>Here, new values are created and stored in another list which is new_list. Values in the old list will remain unchanged.</p><p>Let’s see an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c2_IwR913PHuwkRv1_1dEg.png" /></figure><p>Here, each number will be multiplied by itself means we are doing exponentials of each variable, and values are stored in a new list which is called exponentials.</p><p>Conditions are used as a filter to get a customized and precise output while creating a new list. Here, the given expression has to meet certain criteria or a condition specified to get a new list.</p><p>Let’s take an example with an if condition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mz05g7UC4cZskpizbIZ3cQ.png" /></figure><p>Here, the values which are evaluated to True with the given condition will be executed and we get an output in a new list. Only the even numbers enter a new list. You can add more than one condition if you want.</p><h3>Nested List Comprehensions</h3><p>Nested List Comprehensions are used to create combinations of lists within a collection. In other words, nested list comprehensions are list comprehensions within another list comprehensions.</p><p>Let’s go through some examples to see what we can do with nested list comprehensions:</p><p><strong>We take an example to flatten a list of lists:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-iHgQy451KjSM0WpulaE8A.png" /></figure><p>Did you understand anything? No. Here, the first for loop is used to access the outer list, and the second for loop is used to access the values in the inner sublist.</p><p>Let’s see the same example using a for loop and an append() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hl3UhSBQbU2iQ9bDska6bg.png" /></figure><p>You can use filters or conditions with this as well. Let’s see how:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4N3C0iy0jSyy_xs495dLtw.png" /></figure><p>You can see the condition where the length of the sublist should be greater than 2, if it is not then that sublist will be discarded.</p><h3>Conclusion</h3><p>You now know the basics of list comprehension and nested list comprehensions in Python. It offers an elegant and concise syntax for creating new lists based on existing lists or other iterable.</p><p>Using too much List comprehension in python will make your code unreadable.</p><p>Yes, list comprehension is very useful to write more beautiful and pythonic code. It is always recommended to use list comprehension in Python but maintain the code readability. List comprehension makes the code hard to understand, it is always recommended to avoid list compression in complex cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86520ee16aa5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/list-comprehensions-and-nested-list-comprehensions-in-python-86520ee16aa5">List Comprehensions and Nested List Comprehensions in Python</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[Evaluation Metrics for Regression Models]]></title>
            <link>https://medium.com/analytics-vidhya/evaluation-metrics-for-regression-models-c91c65d73af?source=rss-bac014ba4117------2</link>
            <guid isPermaLink="false">https://medium.com/p/c91c65d73af</guid>
            <category><![CDATA[regression-modeling]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[model-performance]]></category>
            <category><![CDATA[evaluation-metric]]></category>
            <dc:creator><![CDATA[Shweta Goyal]]></dc:creator>
            <pubDate>Mon, 16 Aug 2021 04:52:07 GMT</pubDate>
            <atom:updated>2021-08-16T04:52:07.133Z</atom:updated>
            <content:encoded><![CDATA[<h4>Most widely used Regression Metrics for evaluating model performance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s56mOc9NHQMRXzwy" /><figcaption>Photo by <a href="https://unsplash.com/@polarmermaid?utm_source=medium&amp;utm_medium=referral">Anne Nygård</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://medium.com/analytics-vidhya/evaluation-metrics-for-classification-models-e2f0d8009d69">In my previous article</a>, I had talked about various metrics used in classification models for evaluation. In this article, I’ll discuss some metrics that we use in regression models.</p><p>In classification, our model predicts a class label while our model predicts a numeric value in regression. In regression, we can’t use classification accuracy to evaluate our model. There are error metrics designed for regression models. We will discuss more in this article.</p><p>Let’s get started then….</p><h3>Introduction</h3><p>Regression is a problem where we try to predict a continuous dependent variable using a set of independent variables. For example, weather forecasting, market trends, etc. These problems are used to answer “How much?” or “How many?”</p><p>In regression problems, the prediction error is used to define the model performance. The prediction error is also referred to as residuals and it is defined as the difference between the actual and predicted values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/0*ODqRFjovGdBTFg-o.jpg" /><figcaption><a href="http://www.shodor.org/interactivate/discussions/FindingResiduals/">Source</a></figcaption></figure><p>The regression model tries to fit a line that produces the smallest difference between predicted and actual(measured) values.</p><p>Residuals are important when determining the quality of a model. You can examine residuals in terms of their magnitude and/or whether they form a pattern.</p><ul><li>Where the residuals are all 0, the model predicts perfectly. The further residuals are from 0, the less accurate the model is.</li><li>Where the average residual is not 0, it implies that the model is systematically biased (i.e., consistently over-or under-predicting).</li><li>Where residuals contain patterns, it implies that the model is qualitatively wrong, as it is failing to explain some properties of the data.</li></ul><p><strong>Residual = actual value — predicted value</strong></p><p><em>error(e)</em> = <em>y</em> — <em>ŷ</em></p><blockquote><strong>So, the question is when you have residuals then why do we need different metrics? Let’s find out...</strong></blockquote><p>We can calculate the residual for every point in our data set, and each of these residuals will be of use in assessment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*Ut1J25o9MunHKsNf.png" /><figcaption>Source: <a href="https://www.displayr.com/learn-what-are-residuals/">Displayr</a></figcaption></figure><p>Residual = Inflation — Predicted</p><p>We can technically inspect all residuals to judge the model’s accuracy, but this does not scale if we have thousands or millions of data points. That’s why we have summary measurements that take our collection of residuals and condense them into a <em>single</em> value representing our model&#39;s predictive ability.</p><p>Now we’ll turn our focus to metrics of our model.</p><h3>Regression Evaluation Metrics:</h3><p>In this section, we will take a closer look at the popular metrics for regression models.</p><h4>Mean Absolute Error (MAE):</h4><p>It is the average of the absolute differences between the actual value and the model’s predicted value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*c01U4T7kwvGK8cz6.png" /><figcaption><strong>Mean Absolute Error</strong></figcaption></figure><p>where,</p><p><strong>N</strong> = total number of data points</p><p><strong>Yi</strong> = actual value</p><p><strong>Ŷi</strong> = predicted value</p><p>If we don’t take the absolute values, then the negative difference will cancel out the positive difference and we will be left with a zero upon summation.</p><blockquote>A small MAE suggests the model is great at prediction, while a large MAE suggests that your model may have trouble in certain areas. MAE of 0 means that your model is a perfect predictor of the outputs.</blockquote><p>Here’s a Scikit-learn implementation of MAE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qxDvH6JgaHQwo9dqUVlUeg.png" /><figcaption>Mean Absolute Error</figcaption></figure><p>The mean absolute error (MAE) has the same unit as the original data, and it can only be compared between models whose errors are measured in the same units.</p><p>The bigger the MAE, the more critical the error is. It is robust to outliers. Therefore, by taking the absolute values, MAE can deal with the outliers</p><p>Here, a big error doesn’t overpower a lot of small errors and thus the output provides us with a relatively unbiased understanding of how the model is performing. Hence, it fails to punish the bigger error terms.</p><p>MAE is not differentiable so we have to apply various optimizers like Gradient descent which can be differentiable.</p><h4>Mean Squared Error (MSE):</h4><p>It is the average of the squared differences between the actual and the predicted values.</p><p>Lower the value, the better the regression model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*6SpWXBIxjChXiU68.png" /><figcaption><strong>Mean Squared Error</strong></figcaption></figure><p>where,</p><p><strong>n</strong> = total number of data points</p><p><strong>yi</strong> = actual value</p><p><strong>ŷi</strong> = predicted value</p><p>Its unit is the square of the variable’s unit.</p><p>Here’s a Scikit-learn implementation of MSE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-BQMBFiSBjm9ELVSuB5P6w.png" /><figcaption>Mean Squared Error</figcaption></figure><blockquote>If you have outliers in the dataset then it penalizes the outliers most and the calculated MSE is bigger. So, in short, It is not Robust to outliers which were an advantage in MAE.</blockquote><p>MSE uses the square operation to remove the sign of each error value and to punish large errors.</p><p>As we take the square of the error, the effect of larger errors become more pronounced then smaller error, hence the model can now focus more on the larger errors.</p><p>The main reason this is not that useful is that if we make a single very bad prediction, the squaring will make the error even worse and it may skew the metric towards overestimating the model’s badness.</p><p>On the other hand, if all the errors are small, or rather, smaller than 1, then we may underestimate the model’s badness.</p><h4>Root Mean Squared Error (RMSE):</h4><p>It is the average root-squared difference between the real value and the predicted value. By taking a square root of MSE, we get the Root Mean Square Error.</p><p>We want the value of RMSE to be as low as possible, as lower the RMSE value is, the better the model is with its predictions. A Higher RMSE indicates that there are large deviations between the predicted and actual value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/0*RcUIrHnZtglb3uEu.jpg" /><figcaption><strong>Root Mean Squared Error</strong></figcaption></figure><p>where,</p><p><strong>n</strong> = total number of data points</p><p><strong>yj</strong> = actual value</p><p><strong>ŷj</strong>= predicted value</p><p>Here’s a Scikit-learn implementation of RMSE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kdh5dOUx-d7AkADaPzdHmg.png" /><figcaption><strong>Root Mean Squared Error</strong></figcaption></figure><h4>Max Error:</h4><p>While RMSE is the most common metric, it can be hard to interpret. One alternative is to look at quantiles of the distribution of the absolute percentage errors. The Max-Error metric is the <strong>worst-case</strong> error between the predicted value and the true value.</p><p>Here’s a Scikit-learn implementation of Max Error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mz4CakClIvPhOvp4gLdlTQ.png" /><figcaption><strong>Max Error</strong></figcaption></figure><h4>R² score, the coefficient of determination:</h4><p>R-squared explains to what extent the variance of one variable explains the variance of the second variable. In other words, it measures the proportion of variance of the dependent variable explained by the independent variable.</p><p>R squared is a popular metric for identifying model accuracy. It tells how close are the data points to the fitted line generated by a regression algorithm. A larger R squared value indicates a better fit. This helps us to find the relationship between the independent variable towards the dependent variable.</p><blockquote>R² score ranges from 0 to 1. The closest to 1 the R², the better the regression model is. If R² is equal to 0, the model is not performing better than a random model. If R² is negative, the regression model is erroneous.</blockquote><p>It is the ratio of the sum of squares and the total sum of squares</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/0*lj2nSErRL1zwu1e0.jpg" /><figcaption><strong>R2 Score</strong></figcaption></figure><p>where <strong>SSE</strong> is the sum of the square of the difference between the actual value and the predicted value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*HEblCiVlaolkvFCyrhskrQ.png" /><figcaption><strong>Sum of Squared Errors</strong></figcaption></figure><p>and, <strong>SST </strong>is the<strong> </strong>total sum of the square of the difference between the actual value and the mean of the actual value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*afjK2hyXnOeqNvcr-6Rykg.png" /><figcaption><strong>Total sum of squares</strong></figcaption></figure><p>Here,<strong> yi </strong>is the observed target value, <strong>ŷi </strong>is the predicted value, and <strong><em>y-bar</em></strong> is the mean value, <strong><em>m</em></strong> represents the total number of observations.</p><p>When we add new features in our data, R2 score starts increasing or constant but never decreases because It assumes that while adding more data variance of data increases.</p><p>But the problem is when we add an irrelevant feature in the dataset then at that time R2 sometimes starts increasing which is incorrect.</p><p>Here’s a Scikit-learn implementation of R2 Score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DASxqMJfcZvAMDrxhlt-9w.png" /><figcaption><strong>R2 Score</strong></figcaption></figure><p>R2 describes the proportion of variance of the dependent variable explained by the regression model. If the regression model is “perfect”, SSE is zero, and R2 is 1. If the regression model is a total failure, SSE is equal to SST, no variance is explained by the regression, and R2 is zero.</p><h4>Adjusted R-Square:</h4><p><strong>Adjusted R²</strong> is the same as standard R² except that it penalizes models when additional features are added.</p><p>To counter the problem which is faced by R-square, Adjusted r-square penalizes adding more independent variables which don’t increase the explanatory power of the regression model.</p><p>The value of adjusted r-square is always less than or equal to the value of r-square.</p><p>It ranges from 0 to 1, the closer the value is to 1, the better it is.</p><p>It measures the 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/0*IoCv1Ka_c_F2EiR5.png" /><figcaption><strong>Adjusted R-Squared</strong></figcaption></figure><p>where</p><p><strong>n</strong> is the number of data points</p><p><strong>k</strong><em> </em>is the number of independent variables in your model</p><h4>Conclusion:</h4><p>In this article, we discussed several important regression evaluation metrics. Depending on the situation, some metrics might be more relevant than others.</p><p>In all cases, the goal is to estimate the distance between the predicted model and the actual values. The critical point is to have a subtle understanding of these metrics to use them adequately.</p><p>I recommend Scikit-learn official documentation for more metrics: <a href="https://scikit-learn.org/stable/modules/model_evaluation.html#regression-metrics">https://scikit-learn.org/stable/modules/model_evaluation.html#regression-metrics</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c91c65d73af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/evaluation-metrics-for-regression-models-c91c65d73af">Evaluation Metrics for Regression Models</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[Evaluation Metrics for Classification Models]]></title>
            <link>https://medium.com/analytics-vidhya/evaluation-metrics-for-classification-models-e2f0d8009d69?source=rss-bac014ba4117------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2f0d8009d69</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification-metrics]]></category>
            <category><![CDATA[evaluation-metric]]></category>
            <dc:creator><![CDATA[Shweta Goyal]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 05:53:07 GMT</pubDate>
            <atom:updated>2021-07-20T05:53:07.466Z</atom:updated>
            <content:encoded><![CDATA[<h4>Most common metrics that have been used widely while evaluating a classification model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*drpRquRpCdsT8Y7W" /><figcaption>Photo by <a href="https://unsplash.com/@ernestovdp?utm_source=medium&amp;utm_medium=referral">Ernesto Velázquez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Evaluation metrics are used to measure the quality of the model. One of the most important topics in machine learning is how to evaluate your model. When you build your model, it is very crucial to measure how accurately it predicts your expected outcome.</p><p>We have different evaluation metrics for a different set of machine learning algorithms. For evaluating classification models, we use classification metrics and for evaluating regression models, we use regression metrics. In this article, I’ll talk about only classification metrics. Before we dive deep into evaluation metrics, let’s talk about some basics:</p><h3>Some WarmUp:……</h3><p>There are various evaluation metrics available for both <strong>supervised</strong> and <strong>unsupervised</strong> machine learning algorithms.</p><p><strong>Supervised Learning</strong> - We have labeled inputs, the task is to predict labeled outputs by training a model. These algorithms are further classified into two categories: Classification and Regression:-</p><ul><li><strong>Classification: </strong>Based on some inputs, it predicts a category.<strong> </strong>These problems attempt to classify a data point into a specific category/class. Here, the target outcome will be a discrete/categorical value like Yes/No, Spam/Not spam, etc. For example, whether the customer would default on their loan or not.</li><li><strong>Regression:</strong> Based on some inputs, it predicts a certain number. These problems use input variables to predict continuous values by using only training data. Here, the target outcome will always be a quantity/real value like time-series data, sales figures, heights, weights, etc. For example, what is the expected amount of default from their customer or the price of the house?</li></ul><p><strong>Unsupervised Learning </strong>- These algorithms help us to analyze and cluster unlabeled data sets. We don’t have any target labels. These algorithms help us to discover hidden patterns in data.</p><p><strong>Train/Validation/Test Split:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kNv1ue6w7axeQI2y.png" /><figcaption>Source: <a href="https://datascience.stackexchange.com/questions/61467/clarification-on-train-test-and-val-and-how-to-use-implement-it">Stackexchange</a></figcaption></figure><p>Before we dive into metrics, we have certain <strong>model evaluation procedures</strong>. We need to know how well a model will generalize to out-of-sample data.</p><ul><li><strong>Training and Testing on same data: </strong>When you train and test on the same data, you will end up overfitting the training data and it won’t generalize either.</li></ul><blockquote>While evaluating your model, it’s best to not train your model on the entire dataset.</blockquote><ul><li><strong>Train and Test split:</strong> A typical train/test split would be to use 70% of the data for training and 30% of the data for testing. It’s important to evaluate your model to find the best parameters of a model but we can’t use this test set for evaluation because the parameters we get may be the best but may not necessarily generalize well.</li></ul><blockquote>It’s best to split the data into two parts i.e. train and test set. It’s better to split the data into three parts i.e. train, validation and test set.</blockquote><ul><li><strong>Train/Validation/Test split: </strong>To evaluate your model while still building and tuning the model, we need to create a third subset which is the validation set. The split would be to use 60% of the data for training, 20% of the data for validation, and 20% of the data for testing. A validation set is used to evaluate the performance of the model with different hyperparameter values. It is also used to detect overfitting during the training stage.</li></ul><blockquote>It’s useful to shuffle the data before making splits so that each split has accurate representation of the data.</blockquote><p>Let’s dive into metrics.</p><h3>Why do we need evaluation metrics?</h3><p>Evaluation metrics can help you assess your model’s performance, monitor your ML system in production, and control your model to fit your business needs.</p><p>Our goal is to create and select a model which gives high accuracy on out-of-sample data. It’s very crucial to use multiple evaluation metrics to evaluate your model because a model may perform well using one measurement from one evaluation metric while may perform poorly using another measurement from another evaluation metric.</p><h3>Classification Evaluation Metrics</h3><p>Here, I’ll discuss some common classification metrics used to evaluate models.</p><h3><strong>Classification Accuracy:</strong></h3><p>The simplest metric for model evaluation is Accuracy. It is the ratio of the number of correct predictions to the total number of predictions made for a dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/0*DIEn1lXhNseGGAco.gif" /></figure><blockquote>Accuracy is useful when the target class is well balanced but is not a good choice with unbalanced classes.</blockquote><p>For example, A dataset with two target classes containing 100 samples. 98 samples belong to class A and 2 samples belong to class B in our training data, our model would give us 98% accuracy. That’s why we need to look at more metrics to get a better result.</p><p>Here, we have python implementation of Accuracy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8ZsH-sUjc4XOV_FMcMcqg.png" /><figcaption>Computing the Accuracy</figcaption></figure><p>Accuracy gives us an overall picture of how much we can rely on our model’s prediction. This metric is blind to the difference between classes and types of errors. That’s why it is not good enough for imbalanced datasets.</p><h3>Logarithmic Loss or Log Loss:</h3><p>Log Loss can be used when the output of the classifier is a numeric probability instead of a class label. Log loss measures the unpredictability of the extra noise that comes from using a predictor as opposed to the true labels.</p><p><strong>Log loss for a binary classifier:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ty7D6fffk6Tn5-fr.png" /><figcaption>Source: <a href="https://stackoverflow.com/questions/58776695/how-to-calculate-the-log-loss-metric-in-scala-spark">Stackoverflow</a></figcaption></figure><p><strong>Log loss for multi-class classification:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/0*OIMdQ5UWmj7rlc2n.gif" /></figure><p>Consider, N samples belong to the M class. where,</p><p>y_ij indicates whether sample i belongs to class j or not</p><p>p_ij indicates the probability of sample i belonging to class j</p><h4><strong>How does it work?</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r83ICDHSxAfNyMEg.png" /><figcaption><a href="https://emilyswebber.github.io/LogLoss/">Source</a></figcaption></figure><p>The above image is of actual(Target) and Predicted probabilities.</p><ul><li>The top image depicts a poor prediction because of the large difference between the actual and predicted probability which gives us a large log loss. Here, the function penalizes the wrong answer that the model is confident about.</li><li>The bottom image depicts a good prediction because the predicted probability is close to the actual probability which gives us a small log loss. Here, the function is rewarding a correct answer that the model is confident about.</li></ul><p>Log loss doesn’t have an upper bound and it exists on the range [0, ∞). Minimizing log loss gives greater accuracy for the classifier.</p><p>Here, we have a scikit-learn implementation of Log Loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aVjk4v4btCnXvuKay-X5RQ.png" /><figcaption>Computing the Log loss</figcaption></figure><h3>Confusion Matrix:</h3><p>A confusion matrix or error matrix is a table that shows the number of correct and incorrect predictions made by the model compared with the actual classifications in the test set or what type of errors are being made.</p><p>This matrix describes the performance of a classification model on test data for which true values are known. It is a n*n matrix, where n is the number of classes. This matrix can be generated after making predictions on the test data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*l30v6Id3wZrw8FAO" /><figcaption>Source: <a href="https://alearningaday.blog/2016/09/14/confusion-matrix/">alearningaday</a></figcaption></figure><p>Here, columns represent the count of actual classifications in the test data while rows represent the count of predicted classifications made by the model.</p><blockquote>Let’s take an example of a classification problem where we are predicting whether a person is having diabetes or not. Let’s give a label to our target variable:</blockquote><blockquote><strong>1:</strong> A person is having diabetes | <strong>0:</strong> A person is not having diabetes</blockquote><p>Four possible outcomes could occur while performing classification predictions:</p><ul><li><strong>True Positives (TP): </strong>Number of outcomes that are actually positive and are predicted positive.</li></ul><p>For example: In this case, a person is actually having diabetes(1) and the model predicted that the person has diabetes(1).</p><ul><li><strong>True Negatives (TN):</strong> Number of outcomes that are actually negative and are predicted negative.</li></ul><p>For example: In this case, a person actually doesn’t have diabetes(0) and the model predicted that the person doesn’t have diabetes(0).</p><ul><li><strong>False Positives (FP): </strong>Number of outcomes that are actually negative but predicted positive. These errors are also called <strong>Type 1 Errors.</strong></li></ul><p>For example: In this case, a person actually doesn’t have diabetes(0) but the model predicted that the person has diabetes(1).</p><ul><li><strong>False Negatives (FN): </strong>Number of outcomes that are actually positive but predicted negative. These errors are also called <strong>Type 2 Errors.</strong></li></ul><p>For example: In this case, a person actually has diabetes(1) but the model predicted that the person doesn’t have diabetes(0).</p><p>Positive and Negatives refers to the prediction itself. True and False refers to the correctness of the prediction.</p><p>Here, we have a scikit-learn implementation of the Confusion matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxd_NCZJsj9luELMJWMN3Q.png" /><figcaption>Calculating the Confusion matrix</figcaption></figure><blockquote>From Scikit-learn official doc:</blockquote><blockquote>The diagonal elements represent the number of points for which the predicted label is equal to the true label, while off-diagonal elements are those that are mislabeled by the classifier. The higher the diagonal values of the confusion matrix the better, indicating many correct predictions.</blockquote><h4>We can get 4 classification metrics from the Confusion Matrix:</h4><h4>1.) Accuracy:</h4><p>It can also be calculated in terms of positives and negatives for binary classification:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/0*fGfNMrQjBae4mP9C.png" /></figure><p>It doesn’t grant us much information regarding the distribution of false positives and false negatives.</p><p>Here’s a scikit-learn implementation of accuracy score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BX8RaRWYg5gHLNNiA-5_cQ.png" /><figcaption>Calculating the accuracy score</figcaption></figure><h4>2.) Precision or Positive Predictive Value (PPV):</h4><p>It is the ratio of True Positives to all the positives predicted by the model. It is useful for the skewed and unbalanced dataset. The more False positives the model predicts, the lower the precision.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/0*CmLJJbuJtBS1CA5D.png" /></figure><p>For example, we have a medical test of 20 patients and the test identifies 8 of them have the disease. Of the 8 identified by the test, 5 actually had the disease (true positives) while the other 3 did not (false positives). We later find out that the test missed the 4 additional patients who turned out to have the disease (false negatives).</p><p>The values are TP=5, FP=3, FN=4, TN=8.</p><p>Precision = 5/5+3 = 0.625</p><p>Here’s a scikit-learn implementation of Precision:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YybmlMGoihSXOLEs3xkq_A.png" /><figcaption>Calculating the Precision score</figcaption></figure><h4>3.) Recall or Sensitivity or True Positive Rate(TPR):</h4><p>It is the ratio of true positives to all the positives in your dataset. It measures the model’s ability to detect positive samples. The more false negatives the model predicts, the lower the recall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*kqF3PhMMNaMWDnlr.png" /></figure><p>From the previous example of precision, the values are TP=5, FP=3, FN=4, TN=8.</p><p>Recall = 5/5+4 = 0.56</p><p>Here’s a scikit-learn implementation of Recall:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bOYGrUvQsMhsjtYtL16RqA.png" /><figcaption>Calculating the Recall score</figcaption></figure><ul><li>The precision takes into account how both the positive and negative samples were classified, but the recall only considers the positive samples in its calculations. In other words, the precision is dependent on both the negative and positive samples, but the recall is dependent only on the positive samples (and independent of the negative samples).</li><li>The precision considers when a sample is classified as <em>Positive</em>, but it does not care about correctly classifying <em>all </em>positive samples. The recall cares about correctly classifying <em>all</em> positive samples, but it does not care if a negative sample is classified as positive.</li></ul><h4>4.) F1-score or F-measure:</h4><p>It is a single metric that combines both Precision and Recall. The higher the F1 score, the better is the performance of our model. The range for F1-score is [0,1].</p><p>F1 score is the weighted average of precision and recall. The classifier will only get a high F-score if both precision and recall are high. This metric only favors classifiers that have similar precision and recall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/0*QTxXh0usOzRsgK1i.png" /></figure><p>Here’s a scikit-learn implementation of the F1-score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uzrq3A1siQBe7QnIv_KxZw.png" /><figcaption>Calculating the f1-score</figcaption></figure><h4>Special Case: F-score with factor β</h4><p>The F1-score is a generalized case of the overall F-score. The overall F-score has a factor β, which defines how much influence precision/recall has over the evaluation:</p><ul><li>β &lt; 1: Precision oriented evaluation</li><li>β &gt;1: Recall oriented evaluation</li></ul><p>F1 score is a generalized case where β is 1, meaning precision and recall are balanced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*69fFb9DQro6ShxZj.png" /></figure><p>Here’s a scikit-learn implementation of the F-beta score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3tnjGYXUL3eJaFraLJ3OQ.png" /><figcaption>Calculating the fbeta-score</figcaption></figure><h3>ROC Curve:</h3><p>A <strong>ROC curve (Receiver Operating Characteristic curve) </strong>is a graph showing the performance of a classification model. It is a way to visualize the tradeoff between the True Positive Rate (TPR) and False Positive Rate(FPR) using different decision thresholds (the threshold for deciding whether a prediction is labeled “true” or “false”) for our predictive model.</p><p>This threshold is used to control the tradeoff between TPR and FPR. Increasing the threshold will generally increase the precision, but a decrease in recall.</p><p>First, let’s see TPR and FPR:-</p><ul><li><strong>True Positive Rate (TPR / Sensitivity / Recall):</strong> True Positive Rate corresponds to the proportion of positive data points that are correctly considered as positive, for all positive data points.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/0*eo8DI2xhCfceyWEn.gif" /></figure><ul><li><strong>False Positive Rate (FPR): </strong>False Positive Rate corresponds to the proportion of negative data points that are mistakenly considered as positive, for all negative data points.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*xpo4Rz9LQXmyZfBV.png" /></figure><p>They both have values in the range of [0,1] which are computed at varying threshold values.</p><blockquote>The perfect classifier will have high value of true positive rate and low value of false positive rate.</blockquote><p>Below is the ROC curve represents a more precise model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*CR1L_wNQbbzEU1Ej.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Receiver_operating_characteristic">Wikipedia</a></figcaption></figure><ul><li>Any model with a ROC curve above the random guessing classifier line can be considered as a better model.</li><li>Any model with a ROC curve below the random guessing classifier line can outrightly be rejected.</li></ul><p>This curve plots TPR and FPR at different classification thresholds but this is inefficient because we have to evaluate our model at various thresholds. There’s an efficient, sorting-based algorithm that can provide us this information which is AUC.</p><p>Here’s a scikit-learn implementation of the ROC Curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QX_9LxCT7sBpWVztOZ5HGg.png" /><figcaption>Computing the ROC Curve</figcaption></figure><h3>AUC:</h3><p>An <strong>AUC (Area Under the Curve)</strong> or Area Under the ROC Curve, thus the term is short for roc_auc.</p><p>AUC is a metric used to summarize a graph by using a single number. It is used for binary classification problems.</p><p>Note: AUC is a function that gives points on a curve.</p><blockquote>AUC is equal to the probability that the classifier ranks a random positive example more highly than a random negative example.</blockquote><p>Here’s a scikit-learn implementation of AUC:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ecC-Q_McMi60gv9FrIyb3Q.png" /><figcaption>Computing the AUC</figcaption></figure><p>AUC helps compare different models since it summarizes the data from the whole ROC curve. AUC has a range of [0,1]. The greater the value, the better is the performance of our model.</p><h3>Conclusion</h3><p>In this article, we have learned so many things. We learned accuracy is only a part of the story for your model’s performance, especially when the data is not balanced or where a false positive has a larger impact or vice-versa. We discussed some other common metrics that have been widely used.</p><p>Check out the scikit-learn official documentation for other metrics which is not covered in this post.</p><p>Scikit-learn: <a href="https://scikit-learn.org/stable/modules/model_evaluation.html#classification-metrics">https://scikit-learn.org/stable/modules/model_evaluation.html#classification-metrics</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2f0d8009d69" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/evaluation-metrics-for-classification-models-e2f0d8009d69">Evaluation Metrics for Classification Models</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[No need to be perplexed by perplexity]]></title>
            <link>https://medium.com/analytics-vidhya/no-need-to-be-perplexed-by-perplexity-cd4cb71ac97b?source=rss-bac014ba4117------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd4cb71ac97b</guid>
            <category><![CDATA[language-modeling]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[perplexity]]></category>
            <dc:creator><![CDATA[Shweta Goyal]]></dc:creator>
            <pubDate>Fri, 29 Nov 2019 21:03:02 GMT</pubDate>
            <atom:updated>2019-12-02T09:11:37.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*eBLIU3BAgOpR15rp9c2ZDg.jpeg" /></figure><p>I was intrigued by the name of perplexity when I first heard this term in natural language processing. So I thought of writing an article. Trust me on this perplexity is not at all what it sounds.</p><p>Generally, perplexity is a state of confusion or a complicated and difficult situation or thing. Technically, perplexity is used for measuring the utility of a <a href="https://en.wikipedia.org/wiki/Language_model">language model</a>. The language model is to estimate the probability of a sentence or a sequence of words or an upcoming word. In this article, you will get to know what perplexity really is and is really simple to understand.</p><h3>Introduction</h3><p>Perplexity is a measurement of how well a probability model predicts test data. Basically, It’s a probability distribution over a sentence, phrases, a sequence of words, etc. Perplexity is a variant that we use as a metric for evaluating language models. A low perplexity indicates the probability distribution is good at predicting the sample. Let’s see how it is used while evaluating language models.</p><h3>Maths behind perplexity</h3><p>Basically, the best model is the one that best predicts an unseen test set. The perplexity of a language model on a test set is the inverse probability of the test set, normalized by the number of words. For a test set with words W = w_1, w_2, …, w_N, the perplexity of the model on the test set is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*vV0XMYe69LPMlH3fFouDtw.png" /></figure><p>This way the longer the sentence the less probable it will be. Then again by the chain rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*tmWF4HzQatbzViErUXvRIA.png" /></figure><p>Perplexity is a function of the probability of the sentence. The meaning of the inversion in perplexity means that <strong>whenever we minimize the perplexity we maximize the probability.</strong></p><h3>The perplexity of a probability distribution</h3><p>The perplexity of a discrete probability distribution p is defined as the exponentiation of the entropy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*-eBZ2cBL7oQZ60qd9TqVXQ.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Perplexity">https://en.wikipedia.org/wiki/Perplexity</a></figcaption></figure><p>where H(p) is the entropy of the distribution p(x) and x is a random variable over all its possible values</p><blockquote>The entropy is a measure of the expected or average number of bits required to encode the outcome of the random variable. <strong>Entropy can be seen as an information quantity whereas perplexity can be seen as the number of choices the random variable has.</strong></blockquote><p><strong>Example:</strong></p><p>Consider tossing a fair coin, probabilities of coming up heads or tails.</p><p>The entropy of the unknown result of the next toss of the coin is maximized i.e. if heads and tails both have equal probability 1/2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*jUc1XOoFZPEynoArp0tYAw.png" /></figure><p>So<strong>, Entropy</strong> is 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*pMuY1UP5oTv9QorIs3FQFw.png" /></figure><p><strong>Perplexity</strong> is 2.</p><p>Entropy uses logarithms while Perplexity with its <strong>e^ </strong>brings it back to a linear scale. A good language model should predict high word probabilities. Therefore, the smaller the perplexity the better.</p><p><strong>Perplexity as a branching factor</strong></p><p>An interpretation of any exponentiated entropy measure is as a branching factor (the weighted average number of choices a random variable has): entropy measures uncertainty in bits but in the exponentiated form, it’s measured as the size of an equally weighted distribution with equivalent uncertainty. That is, exp(−H(p)) is how many sides you need on a fair die to get the same uncertainty as to the distribution p</p><p>Entropy differs by a constant depending on whether you measured using base-2 or natural logarithms but perplexity is the same with whichever base you want.</p><h3>How perplexity and probability are correlated?</h3><p>Minimizing perplexity is the same as maximizing the probability</p><ul><li>Higher probability means lower Perplexity</li><li>The more information, the lower perplexity</li><li>Lower perplexity means a better model</li><li>The lower the perplexity, the closer we are to the true model</li></ul><h3>References:</h3><ul><li><a href="https://web.stanford.edu/class/cs124/lec/languagemodeling.pdf">https://web.stanford.edu/class/cs124/lec/languagemodeling.pdf</a></li><li><a href="https://en.wikipedia.org/wiki/Perplexity">https://en.wikipedia.org/wiki/Perplexity</a></li></ul><p>Thank you for reading till here. Stay tuned for more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd4cb71ac97b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/no-need-to-be-perplexed-by-perplexity-cd4cb71ac97b">No need to be perplexed by perplexity</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[GANs — A brief introduction to Generative Adversarial Networks]]></title>
            <link>https://medium.com/analytics-vidhya/gans-a-brief-introduction-to-generative-adversarial-networks-f06216c7200e?source=rss-bac014ba4117------2</link>
            <guid isPermaLink="false">https://medium.com/p/f06216c7200e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <dc:creator><![CDATA[Shweta Goyal]]></dc:creator>
            <pubDate>Sun, 02 Jun 2019 10:45:12 GMT</pubDate>
            <atom:updated>2019-12-04T19:37:43.983Z</atom:updated>
            <content:encoded><![CDATA[<h3>GANs — A Brief Introduction to Generative Adversarial Networks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*MpINSPv7UTf9WIS5hXcKvg.png" /></figure><p>Have you ever thought of converting your images of zebras to horses or vice-versa? Have you ever thought of predicting the next frame of a video? What if you can generate an image through a text? Do you want to generate emojis through pictures? Do you want to create an image in different poses or different angles? What if you can create an image of the day to night or vice-versa?</p><p>Yes, you can do all these things. These are some of the coolest applications that fascinated me and inspired me to write this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*GnDby_ZaOth2IREs" /></figure><p>Generative Adversarial Networks (GANs) is one of the most popular topics in Deep Learning. Generative Adversarial Networks or GANs are types of Neural Networks used for Unsupervised learning. There has been a tremendous increase in applications of GANs. Let’s understand what is generative adversarial networks and then we will see how does it work.</p><h3>Introduction</h3><p>To understand Generative Adversarial Networks better, let’s break it down into individual words. So, the first word is Generative which means that there is a network that is constantly generating new data and the second word is Adversarial which means that it involves two networks opposing each other and Network simply means an order of data that is going ahead and generate new data.</p><h3>How does it work?</h3><p>GANs consists of two networks, a Generator <strong>G(x)</strong>, and a Discriminator <strong>D(x)</strong>. They both play an adversarial game where the generator tries to fool the discriminator by generating data similar to those in the training set. The Discriminator tries not to be fooled by identifying fake data from real data. They both work simultaneously to learn and train complex data like audio, video or image files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*tZ5B4AZATTI39kDm.jpg" /><figcaption><strong>Generative Adversarial Network</strong></figcaption></figure><p>The generator model generates images from random noise(z) and then learns how to generate realistic images. Random noise which is input is sampled using uniform or normal distribution and then it is fed into the generator which generates an image. The generator output which are fake images and the real images from the training set is fed into the discriminator that learns how to differentiate fake images from real images. The output D(x) is the probability that the input is real. If the input is real, D(x) would be 1 and if it is generated, D(x) should be 0.</p><h3>The math behind the GANs</h3><p>Let’s dig a little deeper and understand how it works mathematically. The Discriminator and Generator play a two-player minimax game with the value function V(G, D). So, Minimax Objective function is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*Y2PGedZ8d8c0xEMG" /><figcaption><strong>Objective Function</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*rmZEdeF1eJwuvzsw" /><figcaption><strong>Architecture of GANs</strong></figcaption></figure><p>D() gives us the probability that the given sample is from training data X. For the Generator, we want to minimize log(1-D(G(z)) i.e. when the value of D(G(z)) is high then D will assume that G(z) is nothing but X and this makes 1-D(G(z)) very low and we want to minimize it which this even lower. For the Discriminator, we want to maximize D(X) and (1-D(G(z))). So the optimal state of D will be P(x)=0.5. However, we want to train the generator G such that it will produce the results for the discriminator D so that D won’t be able to distinguish between z and X.</p><p>Now the question is why this is a minimax function. Here, the Discriminator tries to maximize the objective which is V while the Generator tries to minimize it, due to this minimizing/maximizing we get the minimax term. They both learn together by alternating gradient descent.</p><p><strong>How to make this work?</strong></p><p>We will perform the iteration of gradient descent on D using real and generated images by fixing G. Then we fix D and train G for another single iteration to fool a fixed D. We want to optimize our minimax function by iterating both G and D in alternating steps until we get good quality images from the generator and discriminator won’t be able to differentiate between real and fake images.</p><p>Below is the pseudo-code which shows how GANs are trained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*hlFyF-klXQunFpmoeA89jQ.png" /></figure><h3>Conclusion</h3><p>GANs are very popular and widely used across various industries in a wide variety of problems. It seems easy to train them but actually, it’s not as it requires two networks to train which makes them unstable.</p><p>This is a simple article which gives you a basic idea of GANs. If you want to know more about it, below are the references which you can read.</p><ul><li><a href="https://arxiv.org/pdf/1406.2661.pdf">https://arxiv.org/pdf/1406.2661.pdf</a></li><li><a href="http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture13.pdf">http://cs231n.stanford.edu/slides/2017/cs231n_2017_lecture13.pdf</a></li></ul><p>I hope you find this article useful. I have implemented GANs using PyTorch. Do check out this repo.</p><p><a href="https://github.com/Shwetago/Generative-model-using-PyTorch">https://github.com/Shwetago/Generative-model-using-PyTorch</a></p><p>Thank you for reading till here. Stay tuned for more articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f06216c7200e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/gans-a-brief-introduction-to-generative-adversarial-networks-f06216c7200e">GANs — A brief introduction to Generative Adversarial Networks</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>