<?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 Sumeet Agrawal on Medium]]></title>
        <description><![CDATA[Stories by Sumeet Agrawal on Medium]]></description>
        <link>https://medium.com/@Sumeet_Agrawal?source=rss-9c3354409fc7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OQu5XhWqAzhG75eu</url>
            <title>Stories by Sumeet Agrawal on Medium</title>
            <link>https://medium.com/@Sumeet_Agrawal?source=rss-9c3354409fc7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:22:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Sumeet_Agrawal/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[Important Questions on Statistics — Part 2]]></title>
            <link>https://medium.com/@Sumeet_Agrawal/important-questions-on-statistics-part-2-4bd4b58bcae7?source=rss-9c3354409fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bd4b58bcae7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[important-question]]></category>
            <dc:creator><![CDATA[Sumeet Agrawal]]></dc:creator>
            <pubDate>Sat, 08 Jan 2022 11:13:15 GMT</pubDate>
            <atom:updated>2022-01-08T11:13:15.332Z</atom:updated>
            <content:encoded><![CDATA[<h3>Important Questions on Statistics — Part 2</h3><h4>In this blog, I will try to add Statistics Questions that were asked in interviews (Part 2)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*XmSgWZd3rzZB-nqg.png" /></figure><p><strong>For Part 1 (Question 1 to 6) refer to this link</strong> — <a href="https://medium.com/@Sumeet_Agrawal/important-questions-on-statistics-7b6f5226cd87">Important Questions Part 1</a></p><h4>Ques 7) What do you mean by Sampling Bias?</h4><p><strong>Ans)</strong> Before explaining Sampling Bias, let’s first understand what is sample and sampling.</p><p>A sample is a subset of individuals from a larger population.</p><p>Sampling is a technique of selecting individual members or a subset of the population to make statistical inferences from them and estimate characteristics of the whole population.</p><blockquote>Sampling bias is a bias in which a sample is collected in such a way that some members of the intended population have a lower or higher sampling probability than others. It results in a biased sample of a population in which all individuals, or instances, were not equally likely to have been selected.</blockquote><h4>Ques 8) What do you understand by Type 1 and Type 2 Error?</h4><p><strong>Ans)</strong> <strong>Type 1 Error - </strong>When the null hypothesis is true and you reject it, you make a type I error.</p><p>The probability of making a type I error is α, which is the level of significance you set for your hypothesis test. An α of 0.05 indicates that you are willing to accept a 5% chance that you are wrong when you reject the null hypothesis. To lower this risk, you must use a lower value for α. However, using a lower value for alpha means that you will be less likely to detect a true difference if one really exists.</p><p><strong>Type 2 Error — </strong>When the null hypothesis is false and you fail to reject it, you make a type II error.</p><p>The probability of making a type II error is β, which depends on the power of the test. You can decrease your risk of committing a type II error by ensuring your test has enough power. The probability of rejecting the null hypothesis when it is false is equal to 1–β. This value is the power of the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*5aa42V5OqdOyrtYPh04Nsw.png" /></figure><h4>Ques 9) From Type 1 and Type 2 error, which one is more worse?</h4><p><strong>Ans)</strong> Type 1 and Type 2 error completely depends on the scenario or situation. Sometime Type 1 error is more worse and sometime Type 2 error.</p><p>The two types of error are inversely related to each other, decreasing type 1 errors will increase type 2 errors, and vice versa. To decide when a type 1 or type 2 error would be safer, let’s go through a couple of scenarios.</p><p><strong>Scenario 1 —</strong> Assume you’re a member of a jury tasked with deciding whether or not someone should be sentenced to prison for a crime. If they were truly innocent, <strong>Type 1 error</strong> would suggest that you would imprison them. While <strong>Type 2 error</strong> here means that someone has actually committed a crime and the jury is letting them get away with it. In this case <strong>Type 1 error</strong> is worse than Type 2 error.</p><p><strong>Scenario 2 —</strong> Example of a medical situation. A patient with migraine headaches is referred to the doctor for an MRI head scan. Here in this case <strong>Type 1 error</strong> would be doctor said that there is brain tumor but in actual there is no tumor to person. <strong>Type 2 error</strong> would be there is a brain tumor in the patient, but the doctor insists that there is nothing wrong with them. So in this scenario<strong> Type 2 error</strong> would be more worse than Type 1 error.</p><h4>Ques 10) Explain Correlation and Co-variance.</h4><p><strong>Ans)</strong> <strong>Correlation</strong> show whether and how strongly pairs of variables are related to each other. Correlation takes values between<strong> -1 to +1</strong>, wherein values close to +1 represents strong positive correlation and values close to -1 represents strong negative correlation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*qutmR_-K28_ivITjYf4jGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/0*CEWm3KMQfeMk_Iyg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/0*_D0jgvZLBhbYE0Tz" /></figure><p>If there is no relationship at all between two variables, then the correlation coefficient will certainly be 0.</p><p><strong>Covariance -</strong> It signifies the direction of the linear relationship between the two variables. By direction we mean if the variables are directly proportional or inversely proportional to each other.</p><p>It can take any value between<strong> -infinity to +infinity</strong>, where the negative value represents the negative relationship whereas positive value represents the<br>positive relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/0*Bs1uiIsc94E5szr0" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*q8QeXuxE-d9IR6Yrs9xSwQ.png" /></figure><h4>Ques 11) Explain Confidence Interval.</h4><p><strong>Ans)</strong> <strong>Confidence intervals</strong> measure the degree of uncertainty or certainty in a sampling method. They can take any number of probability limits, with the most common being a <strong>95% or 99% confidence level</strong>.</p><p>A confidence interval displays the probability that a parameter will fall between a pair of values around the mean. Confidence intervals provide more information than point estimates. By establishing a 95% confidence interval using the sample’s mean and standard deviation, and assuming a normal distribution as represented by the bell curve, the researchers arrive at an upper and lower bound that contains the true mean 95% of the time.</p><p>Let’s understand confidence interval with an example. Suppose, a group of researchers is studying the heights of high school basketball players. Assume the interval is between 70 inches and 75 inches.</p><p>So, <strong>95% confidence interval</strong> means that if the researchers take 100 random samples from the population of high school basketball players as a whole, the mean should fall between 70 and 75 inches in 95 of those samples.</p><h4>Ques 12) Explain the p-value.</h4><p><strong>Ans)</strong> A <strong>p-value</strong>, <strong>or probability value</strong>, is a number describing how likely it is that your data would have occurred by random chance (i.e. that the null hypothesis is true).</p><p>The level of statistical significance is often expressed as a p-value between <strong>0 and 1</strong>. The smaller the p-value, the stronger the evidence that you should reject the null hypothesis.</p><p>Some important points of p-value are-</p><ul><li><strong>p-value less than 0.05</strong> (typically ≤ 0.05) is statistically significant. It indicates strong evidence against the null hypothesis, as there is less than a 5% probability the null is correct. Therefore, we reject the null hypothesis, and accept the alternative hypothesis.</li><li><strong>p-value higher than 0.05</strong> is not statistically significant and indicates strong evidence for the null hypothesis. This means we retain the null hypothesis and reject the alternative hypothesis.</li></ul><p>These were the major questions which I faced on different interviews for data Science. Hopefully, these questions would be helpful to you. Thanks for reading this blog. If you’ll get any more questions on statistics on interviews apart from this then please write in comments.</p><p>Also check this <strong>For Part 1 (Question 1 to 6) refer to this link</strong> — <a href="https://medium.com/@Sumeet_Agrawal/important-questions-on-statistics-7b6f5226cd87">Important Questions Part 1</a></p><p>Follow on <a href="https://www.linkedin.com/in/sumeet6510/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bd4b58bcae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Important functions you need to know about Pandas]]></title>
            <link>https://blog.devgenius.io/important-functions-you-need-to-know-about-pandas-b58d95b5905c?source=rss-9c3354409fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b58d95b5905c</guid>
            <category><![CDATA[pandas-dataframe]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <dc:creator><![CDATA[Sumeet Agrawal]]></dc:creator>
            <pubDate>Fri, 10 Dec 2021 04:49:27 GMT</pubDate>
            <atom:updated>2021-12-10T11:59:31.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*NOBl70FG_yALX4Kl.gif" /></figure><h3>Pandas — Basic Functionality</h3><p>Pandas is a predominantly used python data analysis library. It provides many functions and methods to expedite the data analysis process. What makes pandas so common is their functionality, flexibility, and simple syntax.</p><p>Before explaining the functionalities I will do the examples on the California housing dataset. This Dataset and code are available in this link.</p><p><a href="https://github.com/codingrad1/Pandas-Basic-Functionality">https://github.com/codingrad1/Pandas-Basic-Functionality</a></p><p>Some of the most common functionalities of pandas are-</p><h3>1) Head and Tail</h3><p>Once we read a dataset into a pandas data frame, we want to take a look at it to get an overview. Head allows us to display rows from the top of the data frame.</p><p>Syntax for head — <strong><em>data.head()</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*5BXQMwsiwF43MHbI" /></figure><p><strong>Tail</strong> allows us to display rows from the bottom of the data frame.</p><p>Syntax for tail — <strong><em>data.tail()</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*bFEo9wQaz1nzEnS8" /></figure><p>5 rows are displayed by default but we can adjust it bypassing the number of rows we’d like to display.</p><h3>2. DataFrame.info( )</h3><p>Pandas <strong>dataframe.info()</strong> function is used to get a concise summary of the dataframe. It comes really handy when doing exploratory analysis of the data. To get a quick overview of the dataset we use the dataframe.info() function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*ikAFwLsUXNEhw8Ig" /></figure><h3>3. Dtypes</h3><p><strong>Dtypes </strong>shows the data type of each column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*r13Waby4Oyz_T8U7" /></figure><h3>4. Shape and Size</h3><p>Shape<strong> </strong>can be used on NumPy arrays, pandas series, and dataframes. It shows the number of dimensions as well as the size in each dimension.</p><p>Shape returns the number of rows and columns. It is a measure of how much data we have and a key input to the data analysis process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/0*8IB9n58kzwBKc2qC" /></figure><p>Size, as the name suggests, returns the size of a dataframe which is the number of rows multiplied by the number of columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/0*gx4yweLfeoOI7RVD" /></figure><h3>5. describe( )</h3><p>This method gives the overall descriptive summary of the dataframe. This works only for numerical columns, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QxTgyaxq3PpGsLop" /></figure><h3>6. Sample</h3><p><strong>Sample </strong>method allows you to select values randomly from a <strong>Series </strong>or <strong>DataFrame</strong>. It is useful when we want to select a random sample from a distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Oms7G630ZYfGwcL6" /></figure><h3>7. Identifying Missing Values IsNull</h3><p>Handling missing values is a critical step to building a robust data analysis process. The missing values should be a top priority since they have a significant effect on the accuracy of any analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PZFCfXoDO1I3sM23" /></figure><h3>8. Isna</h3><p><strong>Isna </strong>function returns a dataframe filled with boolean values with true indicating missing values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*P4noC47ByqQVZe-9" /></figure><h3>9. Identifying Missing Values Sum</h3><p>Let’s first compute the total number of missing values in the data frame. You can calculate the number of missing values in each column by <strong>df.isnull().sum()</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*IUsVf6h8qmJn2cAg" /></figure><h3>10. Nunique</h3><p>Nunique counts the number of unique entries over columns or rows. It is very useful in categorical features especially in cases where we do not know the number of categories beforehand. Let’s take a look at our initial dataframe:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/0*6LEKK4fZ6TNq8JFt" /></figure><h3>11.Index( )</h3><p><strong>index()</strong> is an inbuilt function in Python, which searches for a given element from the start of the list and returns the lowest index where the element appears.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/0*jFglsMYS4TEmqR6R" /></figure><h3>12.Memory_usage</h3><p><strong>Memory_usage()</strong> returns how much memory each column uses in bytes. It is useful especially when we work with large dataframes. Consider the following dataframe with 1 million rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*k_RaDLX1aTWZN3C2" /></figure><h3>13. nsmallest() and nlargest()</h3><p>Let’s see how we’d go about finding the 5 observations with the smallest value</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*F1k1Ty0gyk4CaR-Y" /></figure><p>Let’s see how we’d go about finding the 5 observations with the Largest value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*iWbyW2w88aOortpD" /></figure><h3>14. Loc and iloc</h3><p><strong>Loc and iloc</strong> are used to select rows and columns.</p><ul><li>loc: select by labels</li><li>iloc: select by positions</li></ul><p><strong>loc </strong>is used to select data by the label. The labels of columns are the column names. We need to be careful about row labels. If we do not assign any specific indices, pandas create an integer index by default. Thus, the row labels are integers starting from 0 and going up.</p><p>The row positions that are used with <strong>iloc </strong>are also integers starting from 0.</p><p>Selecting first 6 rows and 2 columns with loc:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*ZhA08GY9gkigpzZN" /></figure><p>Selecting first 4 rows and first 6 columns with iloc:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*jbRiQeseoYOEcPA0" /></figure><h3>15. Slicing</h3><p>Slicing Rows and Columns using labels. You can select a range of rows or columns using labels or by position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yiyHj9rJnx8plUgT" /></figure><h3>16. Groupby</h3><p>pandas groupby function makes it easier to unveil the underlying relationships among variables. The figure below shows an overview of what the groupby<strong> </strong>function does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7WA5YoKl0-vmPno6" /></figure><h3>17. Sorting</h3><p>Using the <strong>sort_index() method</strong>, bypassing the axis arguments and the order of sorting, DataFrame can be sorted. By default, sorting is done on row labels in ascending order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*is2rE7pMX7x8x3JK" /></figure><h3>18. Dropna</h3><p>The dropna () function is used to <strong>remove a row or a column from a dataframe that has NaN or no values in it</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fRL2zwxJYoxyNBw1" /></figure><h3>19. Pandas — Reindexing</h3><p>Reindexing changes the row labels and column labels of a DataFrame. To reindex means to conform the data to match a given set of labels along a particular axis.</p><p>Multiple operations can be accomplished through indexing like −</p><ul><li>Reorder the existing data to match a new set of labels.</li><li>Insert missing value (NA) markers in label locations where no data for the label existed.</li></ul><p>For example -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a64bb2c196985d2ef4d4c498ad14a884/href">https://medium.com/media/a64bb2c196985d2ef4d4c498ad14a884/href</a></iframe><p>Output -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54f6d4b846e3659866f5a89ea48b3ec6/href">https://medium.com/media/54f6d4b846e3659866f5a89ea48b3ec6/href</a></iframe><h3>Reindexing the columns using axis keyword</h3><p>One can reindex a single column or multiple columns by using the reindex() method and by specifying the axis we want to reindex. Default values in the new index that are not present in the dataframe are assigned, NaN.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9a9386a0e68996d96e22ccd9b361b7e/href">https://medium.com/media/f9a9386a0e68996d96e22ccd9b361b7e/href</a></iframe><p>Output -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/0*HZswQgS-OWWkGRxg" /></figure><h3>Replacing the missing values</h3><p>Missing values from the dataframe can be filled by passing a value to the keyword fill_value. This keyword replaces the NaN values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bef7ce19d9401e1d1e5c13cef353747/href">https://medium.com/media/1bef7ce19d9401e1d1e5c13cef353747/href</a></iframe><p>Output -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/0*siS3ccVZlmvpGCnR" /></figure><h3>20. Pandas — Iteration</h3><p>Iteration is a general term for taking each item of something, one after another. Pandas DataFrame consists of rows and columns so, in order to iterate over a dataframe, we have to iterate a dataframe like a dictionary.</p><p>Feature engineering and feature explorations require iterating through the data frame. There are various methods to iterate through the data frame.</p><h3>A. Iterrows():</h3><p>Iterrows() is a Pandas inbuilt function to iterate through your data frame. It should be completely avoided as its performance is very slow compared to other iteration techniques. Iterrows() makes multiple function calls while iterating and each row of the iteration has properties of a data frame, which makes it slower.</p><p>Example -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/855edfe18af42941758a104a6198bd8c/href">https://medium.com/media/855edfe18af42941758a104a6198bd8c/href</a></iframe><p>Output -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*EVrhkJv_VDjLK29p" /></figure><h3>B. Itertuples():</h3><p><strong>Itertuples()</strong> is a Pandas inbuilt function to iterate through your data frame. Itertuples() make a comparatively less number of function calls than iterrows() and carry much lesser overhead. Itertuples() iterates through the data frame by converting each row of data as a list of tuples.</p><p>Example -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4eab60242be172504b099aff528e57c8/href">https://medium.com/media/4eab60242be172504b099aff528e57c8/href</a></iframe><p>Output -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/0*jT07-wJBSF6KIreG" /></figure><h3>C. Numpy Array Iteration:</h3><p>NumPy provides an iterator object, i.e., <strong>nditer</strong> which can be used to iterate over the given array using python standard Iterator interface.</p><p>Example -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c174ff043ddc6aaf8850f699075e571/href">https://medium.com/media/5c174ff043ddc6aaf8850f699075e571/href</a></iframe><p>Output -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/0*8FPlE686MrehE7-G" /></figure><p>The order of iteration is chosen to match the memory layout of an array, without considering a particular ordering. This can be seen by iterating over the transpose of the above array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15c3ecb71105efd10b4eac926e15ed3a/href">https://medium.com/media/15c3ecb71105efd10b4eac926e15ed3a/href</a></iframe><p>Output -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/0*6xRvqyGd_5zcHd7Z" /></figure><h3>D. Dictionary Iteration:</h3><p>Dictionary in Python is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds the <strong>key: value</strong> pair.</p><p>There are multiple ways to iterate over a dictionary in Python.</p><ul><li>Iterate through all keys</li><li>Iterate through all values</li><li>Iterate through all key, value pairs</li></ul><h3>Iterate through all keys:</h3><p>The order of states in the below code will change every time because the dictionary doesn’t store keys in a particular order.</p><p>Example -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03848b8e3c1a7d2e4fade679b2f54dc3/href">https://medium.com/media/03848b8e3c1a7d2e4fade679b2f54dc3/href</a></iframe><p>Output -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/0*LWBNG4THpKCCHFf5" /></figure><h3>Iterate through all values:</h3><p>Again, in this case, the order in which the capitals are printed in the below code will change every time because the dictionary doesn’t store them in a particular order.</p><p>Example -</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83edfbf01756761275ee5d3bbd585290/href">https://medium.com/media/83edfbf01756761275ee5d3bbd585290/href</a></iframe><p>Output -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/0*V59XVdMIZ42Qjsxc" /></figure><h3>Iterate through all key, value pairs :</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c98ffa2e1b5f5c5451f79887dec0fb2/href">https://medium.com/media/9c98ffa2e1b5f5c5451f79887dec0fb2/href</a></iframe><p>Output -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/0*Mp4hZAvG4wJ81RRw" /></figure><p>These are some important functions that can be used frequently. There are a lot of other functions also available. For reading all other functions follow Pandas documentation.</p><p>Thanks for reading. Hope you get a lot to know from this blog. Please keep supporting me, very soon I will post a blog on Numpy and the visualization library — Seaborn and Matplotlib.</p><p><em>More content at </em><a href="http://blog.devgenius.io/"><em>blog.devgenius.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b58d95b5905c" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/important-functions-you-need-to-know-about-pandas-b58d95b5905c">Important functions you need to know about Pandas</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Important Questions on Statistics]]></title>
            <link>https://medium.com/@Sumeet_Agrawal/important-questions-on-statistics-7b6f5226cd87?source=rss-9c3354409fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b6f5226cd87</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[central-limit-theorem]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[statistical-test]]></category>
            <dc:creator><![CDATA[Sumeet Agrawal]]></dc:creator>
            <pubDate>Sat, 20 Nov 2021 08:12:55 GMT</pubDate>
            <atom:updated>2022-01-08T11:17:27.388Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this blog, you’ll find Statistics Questions that were asked in interviews (Part 1). For part 2 <a href="https://medium.com/@Sumeet_Agrawal/important-questions-on-statistics-part-2-4bd4b58bcae7">click here</a>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*mVX5NjUltE92AfY36alhBg.png" /></figure><h4>Ques 1) What is the difference between inferential statistics and descriptive statistics?</h4><p><strong>Ans) Inferential statistics </strong>allows you to make predictions (“inferences”) from that data. With inferential statistics, you take data from samples and make generalizations about a population.</p><p>There are two main areas of inferential statistics:</p><ol><li><strong>Estimating parameters</strong>. This means taking a statistic from your sample data (for example the sample mean) and using it to say something about a population parameter (i.e. the population mean).</li><li><strong>Hypothesis tests.</strong> This is where you can use sample data to answer research questions. For example, you might be interested in knowing if a new cancer drug is effective.</li></ol><p><strong>Descriptive statistics</strong> describe data (for example, a chart or graph). It provides exact and accurate information. Let’s say you have some sample data about a potential new cancer drug. You could use descriptive statistics to describe your sample, including:</p><ul><li>Sample mean</li><li>Sample standard deviation</li><li>Making a bar chart or boxplot</li><li>Describing the shape of the sample probability distribution</li></ul><h4><strong>Ques 2) Most common characteristics used in descriptive statistics?</strong></h4><p><strong>Ans) Center —</strong> middle of the data. Mean / Median / Mode is the most commonly used measure.</p><ul><li>Mean — Average of all the numbers</li><li>Median — the number in the middle</li><li>Mode — the number that occurs the most. The disadvantage of using Mode is that there may be more than one mode.</li></ul><p><strong>Spread —</strong> How the data is dispersed. Range / IQR / Standard Deviation / Variance is the most commonly used measure.</p><ul><li>Range = Max — Min</li><li>Inter Quartile Range (IQR) = Q3 — Q1</li><li>Standard Deviation (σ) = √(∑(x-µ)2 / n)</li><li>Variance = σ2</li></ul><p><strong>Shape —</strong> the shape of the data can be symmetric or skewed</p><ul><li>Symmetric — the part of the distribution that is on the left side of the median is the same as the part of the distribution that is on the right side of the median</li><li>Left skewed — the left tail is longer than the right side</li><li>Right skewed — the right tail is longer than the left side</li></ul><p><strong>Outlier —</strong> An outlier is an abnormal value</p><ul><li>Keep the outlier based on judgment</li><li>Remove the outlier based on judgment</li></ul><h4><strong>Ques 3) What are left-skewed distribution and right-skewed distribution?</strong></h4><p>Ans) <strong>Left skewed</strong></p><ul><li>The left tail is longer than the right side</li><li>Mean &lt; median &lt; mode</li></ul><p><strong>Right skewed</strong></p><ul><li>The right tail is longer than the right side</li><li>Mode &lt; median &lt; mean</li></ul><h4><strong>Ques 4) Explain the Statistical test.</strong></h4><p>Ans) <strong>Statistical/Hypothesis Tests</strong> are used to make summarize the population from the sample. These tests are used to check whether there is enough evidence in sample data to conclude/deduce that any particular condition is also true for the entire population. These tests enable us to make decisions on the basis of observed patterns from data.</p><p>There is a wide range of statistical tests. The choice of which statistical test to utilize relies upon the structure of data, the distribution of the data, and variable type. There are many different types of tests in statistics like t-test, Z-test, chi-square test, ANOVA test, binomial test, one sample median test, etc.</p><p><strong>Choosing a Statistical test-</strong></p><p>Parametric tests are used if the data is normally distributed. A <strong>parametric statistical test</strong> makes an assumption about the population parameters and the distributions that the data came from. These types of tests include<strong> t-tests, z-tests,</strong> and <strong>ANOVA tests</strong>, which assume data is from a normal distribution.</p><p><strong>Non-parametric statistical test-</strong> Non-parametric tests are used when data is not normally distributed. Non-parametric tests include the <strong>chi-square test</strong>.</p><h4><strong>Ques 5) When should you use a t-test vs a z-test?</strong></h4><p><strong>Ans)</strong> <strong>Z-test-</strong> A z-test is a statistical test used to determine whether two population means are different when the variances are known and the sample size is large. In the z-test mean of the population is compared. The parameters used are population mean and population standard deviation. Z-test is used to validate a hypothesis that the sample drawn belongs to the same population.</p><p>Ho: Sample mean is same as the population mean(Null hypothesis)</p><p>Ha: Sample mean is not same as the population mean(Alternate hypothesis)</p><p><strong>z = (x — μ) / (σ / √n),</strong></p><p>where , x=sample mean, u=population mean, σ / √n = population standard deviation</p><p><strong>T-test- </strong>In the t-test, the mean of the two given samples is compared. A t-test is used when the population parameters (mean and standard deviation) are not known and also, have a small sample size.</p><p>Types of t-test-</p><p><strong>a) One sample t-test — </strong>The mean of a single group is compared with a given mean. For example to check the increase and decrease in sales if the average sales are given. Here’s the formula to calculate this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/0*FpiaoB9Hrz2RJZb-.png" /></figure><p>where,</p><ul><li>t = t-statistic</li><li>m = mean of the group</li><li>µ = theoretical value or population mean</li><li>s = standard deviation of the group</li><li>n = group size or sample size</li></ul><p><strong>b) Independent sample t-test — </strong>The independent t-test which is also called the two-sample t-test or student’s t-test, is a statistical test that determines whether there is a statistically significant difference between the means in two unrelated groups.</p><p>For example -Let’s say we want to compare the average height of the male employees to the average height of the females. Of course, the number of males and females should be equal for this comparison. This is where a two-sample t-test is used.</p><p>Here’s the formula to calculate the t-statistic for a two-sample t-test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/0*40DtdrNbKRiWjDdb.png" /></figure><p>where,</p><ul><li>mA and mB are the means of two different samples</li><li>nA and nB are the sample sizes</li><li>S2 is an estimator of the common variance of two samples, such as:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/0*EPFJPgNPzLqzidvn.png" /></figure><p><strong>c) Paired sample t-test — </strong>Tests for the difference between two variables from the same population( pre-and post-test score). For example- In a training program performance score of the trainee before and after completion of the program.</p><p>The formula to calculate the t-statistic for a paired t-test is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/0*tYijpGzY1a3cnb--.png" /></figure><p>where,</p><ul><li>t = t-statistic</li><li>m = mean of the group</li><li>s = standard deviation of the group</li><li>n = group size or sample size</li></ul><h4>Ques 5) Explain ANOVA Test and Chi-Square Test.</h4><p>Ans) <strong>ANOVA Test-</strong> Analysis of variance (ANOVA) is a statistical technique that is used to check if the means of two or more groups are significantly different from each other. ANOVA checks the impact of one or more factors by comparing the means of different samples. If we use a t-test instead of an ANOVA test it won’t be reliable as the number of samples is more than two and it will give an error in the result.</p><p>The hypothesis being tested in ANOVA is</p><p><strong>Ho:</strong> All pairs of samples are the same i.e. all sample means are equal</p><p><strong>Ha:</strong> At least one pair of samples is significantly different</p><p>In ANOVA test we calculate F value and compare it with critical value</p><p><strong>F= ((SSE1 — SSE2)/m)/ (SSE2/n-k)</strong></p><p>where</p><p>SSE = residual sum of squares</p><p>m = number of restrictions</p><p>k = number of independent variables</p><p><strong>Chi-square test(</strong> <strong><em>χ</em>2 test)-</strong> chi-square test is used to compare two categorical variables. Calculating the Chi-Square statistic value and comparing it against a critical value from the Chi-Square distribution allows assessing whether the observed frequencies are significantly different from the expected frequency.</p><p>The hypothesis being tested for chi-square is-</p><p><strong>Ho:</strong> Variable x and Variable y are independent</p><p><strong>Ha:</strong> Variable x and Variable y are not independent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/0*k7BSLcCcl_vVMyNB.jpeg" /><figcaption>Chi-square formula</figcaption></figure><p>where o=observed, e=expected.</p><h4>Ques 6) Explain Central Limit Theorem with an example.</h4><p><strong>Ans)</strong> “The Central Limit Theorem (CLT) is a statistical theory states that given a sufficiently large sample size from a population with a finite level of variance, the mean of all samples from the same population will be approximately equal to the mean of the population.”</p><p>Sample sizes equal to or greater than 30 are often considered sufficient for the CLT to hold. A key aspect of CLT is that the average of the sample means and standard deviations will equal the population mean and standard deviation. Sufficiently large sample size can predict the characteristics of a population more accurately.</p><p>Let’s understand the central limit theorem with the help of an example.</p><p>Consider that there are 15 sections in the engineering department of a university and each section hosts around 100 students. Our task is to calculate the average weight of students in the engineering department.</p><p>The basic approach is to simply calculate the average:</p><ul><li>Measure the weights of all the students in the engineering department</li><li>Add all the weights</li><li>Finally, divide the total sum of weights by a total number of students to get the average</li></ul><p>But what if the size of the data is humongous? Does this approach make sense? Not really — measuring the weight of all the students will be a very tiresome and long process. So, what can we do instead? Let’s look at an alternate approach.</p><ul><li>First, draw groups of students at random from the class. We will call this a sample. We’ll draw multiple samples, each consisting of 30 students.</li><li>Calculate the individual mean of these samples</li><li>Calculate the mean of these sample means</li><li>This value will give us the approximate mean weight of the students in the engineering department</li><li>Additionally, the histogram of the sample mean weights of students will resemble a bell curve (or normal distribution)</li></ul><p>This, in a nutshell, is what the central limit theorem is all about.</p><p>Thanks for reading this blog. I will add more statistics interview questions in the <a href="https://medium.com/@Sumeet_Agrawal/important-questions-on-statistics-part-2-4bd4b58bcae7">2nd part</a>. Till then Happy Learning !!!</p><p>Here are links to my other blogs —</p><ul><li><a href="https://medium.com/@Sumeet_Agrawal/activation-function-in-neural-network-dc5e51c80ce8">Activation Function in Neural Network</a></li><li><a href="https://medium.com/@Sumeet_Agrawal/evaluation-metrics-for-classification-problem-41cbd887b1d5">Evaluation Metrics for Classification Problem</a></li><li><a href="https://medium.com/@Sumeet_Agrawal/tf-idf-47f8f2ebd987">TF-IDF</a></li><li><a href="https://medium.com/@Sumeet_Agrawal/item-based-collaborative-filtering-4e64f65ae6ea">Item-Based Collaborative Filtering</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b6f5226cd87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Item-Based Collaborative Filtering]]></title>
            <link>https://medium.com/@Sumeet_Agrawal/item-based-collaborative-filtering-4e64f65ae6ea?source=rss-9c3354409fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e64f65ae6ea</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[collaborative-filtering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[item-based-cf]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <dc:creator><![CDATA[Sumeet Agrawal]]></dc:creator>
            <pubDate>Wed, 13 Oct 2021 10:17:16 GMT</pubDate>
            <atom:updated>2021-10-13T10:17:16.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EoVMjOci5jey5xAw.png" /></figure><p><strong>Item-based collaborative filtering</strong> is the recommendation system to use the similarity between items using the ratings by users.</p><p>The fundamental assumption for this method is that <strong>a user gives similar ratings to similar movies</strong>. Consider the following table for movie ratings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*8rAawQpW67SIJSe1.png" /></figure><p>In this example, the rating for <strong>Movie_1</strong> by<strong> User_1</strong> is empty. Let’s predict this rating using item-based collaborative filtering.</p><ul><li><strong>Step 1: Find the most similar (the nearest) movies to the movie for which you want to predict the rating.</strong></li></ul><p>There are multiple ways to find the nearest movies. Here, I use the <strong>cosine similarity</strong>. In using the cosine similarity, replace the missing value for 0. Look at the graph below. The <em>x-axis</em> represents ratings by <strong>User_0</strong> and the <em>y-axis</em> ratings by <strong>User_1</strong>. Then, we can find points for each movie in the space. For example, <strong>Movie_3</strong> corresponds to the point (5,2) in the space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*sPGL0vQ1VDk_l6px.png" /></figure><p>The cosine similarity uses <strong>cos(θ)</strong> to measure the distance between two vectors. As θ increases, cos(θ) decreases (cos(θ) = 1 when θ = 0 and cos(θ) = 0 when θ = 90). Therefore, as the value of θ is smaller, the two vectors are considered closer (the similarity gets greater). Since θ1 is the smallest and θ3 is the largest, <strong>Movie_3</strong> is the closest to <strong>Movie_1,</strong> and <strong>Movie_2</strong> is the farthest.</p><p><strong>What is noteworthy here is that the similarities between movies are determined by ALL USERS. </strong>For example, the similarity between <strong>Movie_1</strong> and <strong>Movie_3</strong> is calculated using the ratings by both of <strong>User_0</strong> and <strong>User_1</strong>.</p><ul><li><strong>Step 2: Calculate the weighted average of the ratings for the most similar movies by the user.</strong></li></ul><p>A user gives similar ratings to similar movies. Therefore, when we predict a rating for a movie by a user, it is reasonable to use the average of ratings for similar movies by the user. Set the number of the nearest neighbors as 2. Then we use <strong>Movie_3</strong> and <strong>Movie_0</strong> to predict the rating for <strong>Movie_1</strong> by <strong>User_1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*h6gtEp1j1tLg4lbm.png" /></figure><p>The rating for <strong>Movie_3</strong> by <strong>User_1 </strong>is<strong> </strong>2, and the rating for <strong>Movie_0</strong> by <strong>User_1</strong> is 3. If <strong>Movie_3</strong> and <strong>Movie_0</strong> are similar to <strong>Movie_1</strong> at the same distance, we can estimate the rating for <strong>Movie_1</strong> by <strong>User_1</strong> as 2.5. However, if <strong>Movie_3</strong> is considered closer to <strong>Movie_1</strong>, the weight for <strong>Movie_3</strong> should be greater than that for <strong>Movie_0</strong>. Therefore, the predicted rating for <strong>Movie_1</strong> will be closer to the rating for <strong>Movie_3</strong> as the picture below indicates. Using the cosine similarity as the weight, the predicted rating is 2.374.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*EM3owhbBNbL8T2KW.png" /></figure><h3>Making a Movie Recommender</h3><p>For better understanding, the dataset with 10 movies and 10 users is used here. (the numbers are randomly selected.)</p><pre>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*drB1HLyzknajmEyZ.png" /></figure><ul><li>10 movies and 10 users</li><li>0 represents missing values.</li><li>The percentage of users rating movies is 50% (only 50 ratings are given). In real movie datasets, this percentage becomes less than 10%.</li></ul><p>I assume that a user did not watch a movie if the user did not rate the movie.</p><h4>Calculate the Nearest Neighbors</h4><p>The<strong> </strong><strong>NearestNeighbors()</strong> in the <strong>sklearn.neighbors</strong> the library can be used to calculate the distance between movies using the <strong>cosine similarity</strong> and find the nearest neighbors for each movie.</p><pre>from sklearn.neighbors import NearestNeighborsknn = NearestNeighbors(metric=&#39;cosine&#39;, algorithm=&#39;brute&#39;)<br>knn.fit(df.values)<br>distances, indices = knn.kneighbors(df.values, <strong>n_neighbors=3</strong>)</pre><p>The number of the nearest neighbors (<strong>n_neighbors</strong>)is set to be 3. Since this includes the movie itself, generally it finds two nearest movies except for the movie itself.</p><pre>indices<strong>[Out] array([[0, 7, 5],<br>             [1, 3, 7],<br>             [2, 1, 6],<br>              ....<br>             [9, 0, 7]])</strong></pre><p><strong>indices</strong> shows the indices of the nearest neighbors for each movie. Each row corresponds to the row in the <strong>df</strong>. The first element in a row is the most similar (nearest) movie. Generally, it is the movie itself. The second element is the second nearest, and the third is the third nearest. For example, in the first row <strong>[0,7,5]</strong>, the nearest movie to <strong>movie_0</strong> is itself, the second nearest movie is <strong>movie_7</strong>, and the third is <strong>movie_5</strong></p><pre>distances<strong>[Out] array([[0.00000000e+00, 3.19586183e-01, 4.03404722e-01],        [4.44089210e-16, 3.68421053e-01, 3.95436458e-01],        [0.00000000e+00, 5.20766162e-01, 5.24329288e-01],<br> ....<br>[1.11022302e-16, 4.22649731e-01, 4.81455027e-01]])</strong></pre><p><strong>distances</strong> shows the distance between movies. A smaller number means the movie is closer. Each number in this array corresponds to the number in the <strong>indices</strong> array.</p><h3>Example: Predict a Rating for a Movie by a User</h3><p>Predicting a rating for a movie by a user is equivalent to calculating the weighted average of ratings for similar movies by the user.</p><p>For practice, predict the rating for <strong>movie_0</strong> by <strong>user_7</strong>. First, find the nearest neighbors for <strong>movie_0</strong> using <strong>NearestNeighbors()</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/0*cs0mVPC9J9YURojS.png" /></figure><p>The most similar movies to <strong>movie_0</strong> are <strong>movie_7</strong> and <strong>movie_5</strong>, and the distances from <strong>movie_0</strong> are 0.3196 and 0.4034, respectively.</p><p>The formula to calculate the predicted rating is as follows:</p><p><strong><em>R(m, u) = </em>{<em>∑ ⱼ S(m, j)R(j, u)</em>}<em>/ ∑ ⱼ S(m, j)</em></strong></p><ul><li><strong><em>R(m, u)</em></strong>: the rating for movie <strong><em>m</em></strong> by user <strong><em>u</em></strong></li><li><strong><em>S(m, j)</em></strong>: the similarity between movie <strong><em>m</em></strong> and movie <strong><em>j</em></strong></li><li><strong><em>j ∈ J</em></strong> where <strong><em>J</em></strong> is the set of the similar movies to movie <strong><em>m</em></strong></li></ul><p>This formula simply implies that the predicted rating for movie <strong><em>m</em></strong> by user <strong><em>u</em></strong> is <strong>the weighted average of ratings for similar movies</strong> by user <strong><em>u</em></strong>. The weight for each rating, (<strong><em>S(m, k)/∑ ⱼ S(m, j))</em></strong>, becomes greater when movie <strong><em>m</em></strong> and movie <strong><em>k</em></strong> are closer. The denominator of this term makes the sum of all the weights equal to 1.</p><p>Let’s predict the rating for <strong>movie_0</strong> by <strong>user_7</strong>, <strong>R(0,7):</strong></p><p><strong>R(0,7)=[S(0,5)∗R(5,7)+S(0,7)∗R(7,7)]/[S(0,5)+S(0,7)]</strong></p><p>Since the distances between <strong>movie_0</strong> and <strong>movie_5</strong> and between <strong>movie_0</strong> and <strong>movie_7</strong> are 0.4034 and 0.3196, the similarities are</p><ul><li><strong>S(0,5)</strong> = (1–0.4034)</li><li><strong>S(0,7)</strong> = (1–0.3196).</li></ul><p>Because <strong>R(5,7)</strong> = 2 and <strong>R(7,7)</strong> = 3, the predicted <strong>R(0,7)</strong> is 2.5328.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e64f65ae6ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Various Implementations of Collaborative Filtering]]></title>
            <link>https://medium.com/@Sumeet_Agrawal/various-implementations-of-collaborative-filtering-7429eec37ab9?source=rss-9c3354409fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7429eec37ab9</guid>
            <category><![CDATA[collaborative-filtering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sumeet Agrawal]]></dc:creator>
            <pubDate>Wed, 13 Oct 2021 09:03:10 GMT</pubDate>
            <atom:updated>2021-11-22T11:18:15.532Z</atom:updated>
            <content:encoded><![CDATA[<h4>Comparison of different methods to build recommendation system using collaborative filtering</h4><p>We see the use of recommendation systems all around us. These systems are personalizing our web experience, telling us what to buy <strong>(Amazon)</strong><em>, </em>which movies to watch <strong>(Netflix)</strong>, whom to be friends with <strong>(Facebook)</strong>, which songs to listen<em> to </em><strong>(Spotify),</strong> etc. These recommendation systems leverage our shopping/ watching/ listening patterns and predict what we could like in the future based on our behavior patterns. The most basic models for recommendations systems are <strong>collaborative filtering models</strong> which are based on assumption that people like things similar to other things they like, and things that are liked by other people with similar tastes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WAmdB98MCYIaLx3X.png" /><figcaption>figure 1: Example of collaborative filtering. Reference: <a href="https://d4datascience.wordpress.com/category/predictive-analytics/">here</a></figcaption></figure><p><strong>It is easy to build targeted recommendation models, so why not just build one for your own customers. I have written this post to make it even easier for you. </strong>Most of the content of this post is inspired by the <strong>fast.ai Deep Learning part 1 v2 course.</strong></p><p>Here is the <a href="https://github.com/groverpr/Machine-Learning/blob/master/notebooks/02_Collaborative_Filtering.ipynb">link to the notebook</a> with implementations of techniques discussed below.</p><h3>Introduction</h3><p>In this post, I have discussed and compared different collaborative filtering algorithms to predict user ratings for a movie. For comparison, I have used <a href="http://files.grouplens.org/datasets/movielens/ml-latest-small.zip">MovieLens data</a> which has 100,004 ratings from 671 unique users on 9066 unique movies. <strong>The readers can treat this post as a 1-stop source to know how to do collaborative filtering on python and test different techniques on their own dataset. </strong><em>(I have also provided my own recommendation about which technique to use based on my analysis).</em></p><p>Before reading further, I hope that you have a basic understanding of collaborative filtering and its application in recommender systems. If not, I strongly recommend you to go through the below blog posts which are written by a fellow student at USF: Shikhar Gupta</p><p><strong>Blogs: </strong>Collaborative filtering and embeddings — <a href="https://medium.com/@shik1470/collaborative-filtering-and-embeddings-part-1-63b00b9739ce">Part 1</a> and <a href="https://medium.com/@shik1470/collaborative-filtering-and-embeddings-part-2-919da17ecefb">Part 2</a></p><h3>Layout of post</h3><ul><li><strong>Types of collaborative filtering techniques<br>• Memory based<br>• Model-based<br></strong>* Matrix Factorization<br>* Clustering<br><strong>* </strong>Deep Learning</li><li><strong>Python Implementations<br></strong>• Surprise package<br>• fast.ai library</li><li><strong>Comparison and Conclusions</strong></li></ul><h3>Types of collaborative filtering techniques</h3><p>A lot of research has been done on collaborative filtering (CF), and most popular approaches are based on <strong>low-dimensional factor models</strong> (model-based matrix factorization. I will discuss these in detail). The CF techniques are broadly divided into 2-types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*W_MXhxxlf0YLv2AN.png" /><figcaption>Figure 2: Types of collaborative filtering approaches. Reference: <a href="https://en.wikipedia.org/wiki/Collaborative_filtering">Wikipedia</a></figcaption></figure><p>Say we want to recommend a new item to our product users (e.g. movie to subscribers of Netflix or clothing to the online buyers at Amazon)<em>. </em>For that, we can use one of many techniques as discussed below.</p><h3>1. Memory based approach:</h3><p>Quoted by Agnes Johannsdottir in her <a href="https://cambridgespark.com/content/tutorials/implementing-your-own-recommender-systems-in-Python/index.html">blogpost</a></p><blockquote><strong><em>Memory-Based Collaborative Filtering</em></strong><em> approaches can be divided into two main sections:</em><strong><em> </em></strong><em>user-item filtering and item-item filtering. A </em><strong><em>user-item filtering</em></strong><em> takes a particular user, find users that are similar to that user based on similarity of ratings, and recommend items that those similar users liked. In contrast, </em><strong><em>item-item filtering</em></strong><em> will take an item, find users who liked that item, and find other items that those users or similar users also liked. It takes items and outputs other items as recommendations.</em></blockquote><blockquote><em>Item-Item Collaborative Filtering: “Users who liked this item also liked …”<br>User-Item Collaborative Filtering: “Users who are similar to you also liked …”</em></blockquote><p>The key difference of the memory-based approach from the model-based techniques is that we are not learning any parameter using gradient descent (or any other optimization algorithm). The closest user or items are calculated only by using <strong>Cosine similarity or Pearson correlation coefficients</strong>, which are only based on arithmetic operations.</p><blockquote><em>A common distance metric is </em><strong><em>cosine similarity</em></strong><em>. The metric can be thought of geometrically if one treats a given user’s (item’s) row (column) of the ratings matrix as a vector. For user-based collaborative filtering, two users’ similarity is measured as the </em><strong><em>cosine of the angle between the two users’ vectors</em></strong><em>. For users u and u′, the cosine similarity is:</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*_WXsBf9jdEidL0fW.png" /></figure><p>We can predict user-u’s rating for movie-i by taking the weighted sum of movie-i ratings from all other users (u′s) where weighting is the similarity number between each user and user-u.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*sfAnmNtBCm-YoMGc.png" /></figure><p>We should also normalize the ratings by a total number of u′ (other users’) ratings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/0*VT5A7PiMGNGxsyZ9.png" /></figure><p><strong>Final words on the Memory-based approach:</strong> As no training or optimization is involved, it is an easy-to-use approach. But its performance decreases when we have sparse data which hinders the scalability of this approach for most real-world problems.</p><h3>2. Model-based approach</h3><p>In this approach, CF models are developed using machine learning algorithms to predict users’ ratings of unrated items. As per my understanding, the algorithms in this approach can further be broken down into 3 sub-types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*_zm3sFwg6aSp4tqWNgl-7Q.png" /><figcaption>Figure 3. Types of model-based collaborative filtering approaches</figcaption></figure><h3>A brief explanation of the above-mentioned algorithms:</h3><ul><li><strong>Matrix Factorization (MF): </strong>The idea behind such models is that the attitudes or preferences of a user can be determined by a small number of hidden factors. We can call these factors as the <strong>Embeddings.</strong></li></ul><blockquote><strong><em>Matrix decomposition can be reformulated as an optimization problem with loss functions and constraints. </em></strong><em>Now the constraints are chosen based on property of our model. For e.g. for Non negative matrix decomposition, we want non negative elements in resultant matrices.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*p_XjLcWHnodz2TJd.png" /><figcaption>Figure 4. Visualization of matrix factorization</figcaption></figure><p><strong>Embeddings:<br>Intuitively, we can understand embeddings as low-dimensional hidden factors for items and users</strong>. For e.g. say we have 5 dimensional <strong>(i.e. D or n_factors = 5</strong> in the above figure<strong>) </strong>embeddings for both items and users (# 5 chosen randomly). Then for user-X &amp; movie-A, we can say those 5 numbers <strong>might </strong>represent 5 different characteristics about the movie, like<em> </em><strong><em>(i)</em></strong><em> how much movie-A is sci-fi intense </em><strong><em>(ii) </em></strong><em>how recent is the movie </em><strong><em>(iii) </em></strong><em>how much special effects are in the movie A</em><strong><em> (iv) </em></strong><em>how dialogue-driven is the movie </em><strong><em>(v)</em></strong><em> how CGI driven is the movie. Likewise, 5 numbers in the user embedding matrix might represent, </em><strong><em>(i) </em></strong><em>how much does user-X likes sci-fi movies </em><strong><em>(ii)</em></strong><em> how much does user-X likes recent movies …and so on. </em>In the above figure, a higher number from the dot product of user-X and movie-A matrix means that movie-A is a good recommendation for user-X.</p><p><em>(I am not saying these numbers actually represent such information. We don’t actually know what these factors mean. This is just to build an intuition)</em></p><p>Matrix factorization can be done by various methods and there are several research papers out there. In the next section, there is python implementation for orthogonal factorization (SVD) or probabilistic factorization (PMF) or Non-negative factorization (NMF).</p><ul><li><strong>Non-parametric approach (KNN): </strong>The idea is the same as that of memory-based recommendation systems. In memory-based algorithms, we use the similarities between users and/or items and use them as <strong>weights</strong> to predict a rating for a user and an item. The difference is that the similarities in this approach are calculated based on an unsupervised learning model, rather than Pearson correlation or cosine similarity. In this approach, we also limit the number of similar users as <strong>k</strong>, which makes the system more scalable.</li><li><strong>Neural Nets/ Deep Learning: </strong>There is a ton of research material on collaborative filtering using matrix factorization or similarity matrix. But there is a lack of online material to learn how to use deep learning models for collaborative filtering. <strong>This is something that I learned in fast.ai deep learning part 1 v2.</strong></li></ul><p>Below is the visualization to explain what is happening when we are using neural nets for this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*v2q_7qrYvrjC-Srd.png" /><figcaption>Figure 5. Matrix factorization and embeddings for neural net</figcaption></figure><p>We can think of this as an extension to the matrix factorization method. For SVD or PCA, we decompose our original sparse matrix into a product of 2 low-rank orthogonal matrices. For neural net implementation, we don’t need them to be orthogonal, we want our model to learn the values of the embedding matrix itself. The <strong>user latent features</strong> and <strong>movie latent features </strong>are looked up from the embedding matrices for specific movie-user combinations. These are the input values for further linear and non-linear layers. We can pass this input to multiple <strong>relu, linear or sigmoid layers </strong>and learn the corresponding weights by any optimization algorithm (Adam, SGD, etc.).</p><p>___________________________________________________________________</p><h3>Python Implementations</h3><p><strong>Github repo link:</strong> <a href="https://github.com/groverpr/Machine-Learning/blob/master/notebooks/02_Collaborative_Filtering.ipynb">here</a></p><p>Let’s look at the python implementation of the above-discussed <strong>algorithms. </strong>I have explored 2 different python packages which give options of various algorithms to chose from.</p><h3>(a) <a href="http://surprise.readthedocs.io/en/stable/getting_started.html">Surprise package</a>:</h3><p>This package has been specially developed to make recommendations based on collaborative filtering easy. It has default implementation for a variety of CF algorithms.</p><blockquote><strong><em>Step 1:</em></strong><em> Download MovieLens data and read it in pandas df </em><a href="http://files.grouplens.org/datasets/movielens/ml-latest-small.zip"><em>http://files.grouplens.org/datasets/movielens/ml-latest-small.zip</em></a></blockquote><blockquote><strong><em>Step 2:</em></strong><em> Install Surprise package by </em><em>pip install scikit-surprise. Load the data into </em><em>Dataset class</em></blockquote><p>Code chunk 1. Surprise data loader</p><pre># <a href="http://surprise.readthedocs.io/en/stable/getting_started.html#">http://surprise.readthedocs.io/en/stable/getting_started.html<br>#</a> I believe in loading all the datasets from pandas df <br># you can also load dataset from csv and whatever suits </pre><pre>ratings =pd.read_csv(‘ratings_small.csv’) #reading data in pandas df </pre><pre>from surprise import Reader, Dataset </pre><pre># to load dataset from pandas df, we need `load_fromm_df` method in # surprise lib </pre><pre>ratings_dict = {‘itemID’: list(ratings.movieId),<br>                ‘userID’: list(ratings.userId),<br>                ‘rating’: list(ratings.rating)}</pre><pre>df = pd.DataFrame(ratings_dict) </pre><pre># A reader is still needed but only the rating_scale param is required.<br># The Reader class is used to parse a file containing ratings.</pre><pre>reader = Reader(rating_scale=(0.5, 5.0)) </pre><pre># The columns must correspond to user id, item id and ratings(in<br># that order).</pre><pre>data = Dataset.load_from_df(df[[‘userID’, ‘itemID’, ‘rating’]], reader)</pre><blockquote><strong><em>Step 3:</em></strong><em> Now implementing any MF algorithm after data preparation is as simple as running 1 line of code. Below are the codes and outputs of Singular Value Decomposition (SVD) and Non negative Matrix Factorization (NMF). The code can also be used for KNN by just changing </em><em>algo = KNNBasic() in below code. (Please check wikipedia links for </em><a href="https://en.wikipedia.org/wiki/Singular-value_decomposition"><em>SVD</em></a><em> and </em><a href="https://en.wikipedia.org/wiki/Non-negative_matrix_factorization"><em>NMF</em></a><em> )</em></blockquote><p>Code chunk 2. SVD and NMF using Surprise</p><pre># Split data into 5 folds data.</pre><pre>split(n_folds=5) </pre><pre>from surprise import SVD, evaluate<br>from surprise import NMF </pre><pre># svd<br>algo = SVD()<br>evaluate(algo, data, measures=[‘RMSE’]) </pre><pre># nmf<br>algo = NMF()<br>evaluate(algo, data, measures=[‘RMSE’])</pre><p>Validation RMSE scores from SVD and NMF</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*NzyMm-8gGx99x9wt.png" /><figcaption>Figure 6. RMSE scores of SVD and NMF using Surprise</figcaption></figure><p><strong>Best RMSE = 0.8967 (SVD) and corresponding MSE is 0.804</strong></p><h3>(b) <a href="https://github.com/fastai/fastai">fast.ai library</a>:</h3><p>fast.ai is a massive python library that is making machine learning and deep learning easy for people with basic coding skills.</p><h3>Shallow Learning</h3><p>Below are 5 lines of codes that implement <strong>probabilistic matrix factorization</strong> for CF. The implementation leverages the fact that the 2 factorized matrices are just embedding matrices which can be modeled by adding an embedding layer in the neural net (We can call it <strong>Shallow Learning</strong>).</p><pre>ratings = pd.read_csv(‘ratings_small.csv’) # loading data from csv</pre><pre>”””<br>ratings_small.csv has 4 columns — userId, movieId, ratings, and timestammp<br>it is most generic data format for CF related data<br>”””</pre><pre>val_indx = get_cv_idxs(len(ratings)) # index for validation set<br>wd = 2e-4 # weight decay<br>n_factors = 50 # n_factors — dimension of embedding matrix (D) </pre><pre># data loader<br>cf = CollabFilterDataset.from_csv(path, ‘ratings_small.csv’, ‘userId’, ‘movieId’, ‘rating’) </pre><pre># learner initializes model object<br>learn = cf.get_learner(n_factors, val_indx, bs=64,opt_fn=optim.Adam)</pre><pre># fitting model with 1e-2 learning rate, 2 epochs, <br>#(1 cycle length and 2 cycle multiple for learning rate scheduling)<br>learn.fit(1e-2,2, wds = wd, cycle_len=1, cycle_mult=2)</pre><p><em>Code chunk 3. Collaborative filtering using fast.ai (based on the concept of PMF)</em></p><p><strong>Training results:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/0*LGy3s1GAb_XbVWxT.png" /><figcaption>Figure 7. Left: Training MSE, Right: Validation MSE. Rows: Epochs</figcaption></figure><p><strong>The best validation MSE obtained from fast.ai implementation of PMF is 0.801 which is close to what we got from SVD.</strong></p><h3>Deep Learning</h3><p>We can add more linear and non-linear layers to our neural net to make it a deep neural net model.</p><p>Steps to make a deep neural net for collaborative filtering using fast.ai</p><blockquote><strong><em>Step 1:</em></strong><em> Load data into PyTorch data-loader. The fast.ai library is built on top of PyTorch. If you want to customize dataset class for specific format of data, learn it </em><a href="http://pytorch.org/tutorials/beginner/data_loading_tutorial.html#dataset-class"><em>here</em></a><em>.</em></blockquote><p>I used fast.ai’sColumnarModelData.from_data_frame function to load the dataset. You can also define your own data-loader function. <strong>X</strong> has data about <strong>userId, movieId, and timestamp</strong> and <strong>Y</strong> has data about only <strong>ratings (target variable).</strong></p><pre>x = ratings.drop([‘rating’],axis=1)<br>y = ratings[‘rating’].astype(np.float32)<br>data = ColumnarModelData.from_data_frame(path, val_indx, x, y, [‘userId’, ‘movieId’], 64)</pre><p><em>Code chunk 4. Data-loader (fast.ai function)</em></p><blockquote><strong><em>Step 2: </em></strong><em>Defining custom neural net class (The syntax is specific to PyTorch, but same logic can be employed for Keras also).</em></blockquote><p>We have to create 2 functions.<em> </em><strong>__init__ (), </strong>the constructor for the class,<strong> </strong>and<strong> forward(), </strong>the forward pass function.</p><pre># nh = dimension of hidden linear layer<br># p1 = dropout1<br># p2 = dropout2 </pre><pre>class EmbeddingNet(nn.Module): <br>  def __init__(self, n_users, _n_movies, nh=10, p1=0.05, p2=0.5):<br>     super().__init__() <br>     (self.u, self.m, self.ub, self.mb) = [get_emb(*o) for o <br>       in [ (n_users, n_factors), (n_movies, n_factors),<br>       (n_users,1), (n_movies,1) ]] </pre><pre>     self.lin1 = nn.Linear(n_factors*2, nh) #bias is True by default  <br>     self.lin2 = nn.Linear(nh, 1) <br>     self.drop1 = nn.Dropout(p = p1) <br>     self.drop2 = nn.Dropout(p = p2) </pre><pre>  def forward(self, cats, conts): <br>    # forward pass i.e. dot product of vector from movie<br>    # embedding matrix and vector from user embeddings matrix</pre><pre>    # torch.cat : concatenates both embedding matrix to make more <br>    # columns, same rows i.e. n_factors*2, n : rows<br>    # u(users) is doing lookup for indexed mentioned in users <br>    # users has indexes to lookup in embedding matrix. </pre><pre>    users,movies = cats[:,0],cats[:,1] <br>    u2,m2 = self.u(users) , self.m(movies) <br>    x = self.drop1(torch.cat([u2,m2], 1)) # drop initialized weights   <br>    x = self.drop2(F.relu(self.lin1(x))) <br>                          # drop 1st linear + nonlinear wt<br>    r = F.sigmoid(self.lin2(x)) * (max_rating — min_rating)+ <br>        min_rating <br>    return r</pre><p><em>Code chunk 5. Neural net on PyTorch</em></p><p>A little more about <strong>layers</strong> that have been used in forwarding pass:</p><ul><li>dropout This layer will drop the activations with a given probability parameter. The activations have p1, p2 probabilities to be turned to 0. This is done to reduce overfitting.</li><li>embedding This layer creates a lookup table for embeddings corresponding to unique users and unique movies. The values in this layer are updated by back-propagation.</li><li>linear linear matrix multiplication with added bias.</li><li>relu non-linear layers used.</li><li>sigmoid used to restrict predicted ratings b/w minimum and maximum rating from training data.</li></ul><blockquote><strong><em>Step 3:</em></strong><em> Model fitting and prediction.</em></blockquote><pre># n_users: count unique users(671), <br># n_movies: count unique movies(9066)</pre><pre>model = EmbeddingNet(n_users, n_movies) </pre><pre># model.parameters() for back-propagation of weights <br># lr = 1e-3, weight decay = 1e-5 and using adam optimizer <br>opt = optim.Adam(model.parameters(), 1e-3, weight_decay=1e-5) </pre><pre># fitting model,<br>fit(model, data, 3, opt, F.mse_loss) </pre><pre># learning rate annealing (for more, check links at the end)<br>set_lrs(opt, 1e-3)<br>fit(model, data, 3, opt, F.mse_loss)</pre><p><em>Code chunk 6. Training deep neural net (fast.ai functions)</em></p><p><strong>Results:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*CtTvfTm-DKoUNmXH.png" /><figcaption>Figure 8. Left: Training MSE, Right: Validation MSE. Rows: Epochs</figcaption></figure><p><strong>Best validation MSE = 0.7906. This is best among all the models discussed above.</strong></p><h3>Comparisons and Conclusions</h3><p>Below is the plot of MSE obtained from different approaches on MovieLens 100k data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*FqZHG4arKXvJMCkf.png" /><figcaption>Figure 9. Comparison of MSE scores using different CF methods</figcaption></figure><p><strong>Neural net (DL) and SVD give the best results. </strong>Neural net implementation will also perform well on imbalanced data, with infrequent users, unlike other MF algorithms.</p><p>It can be useful to built customer targeted recommendation system for your products/ services. Easiest and well-researched method out there is collaborative filtering. I have written this post with the aim that rather than going through technical research papers and spending hours learning about collaborative filtering, readers can find all the useful materials, together with implementation in just one place.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7429eec37ab9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TF-IDF]]></title>
            <link>https://medium.com/@Sumeet_Agrawal/tf-idf-47f8f2ebd987?source=rss-9c3354409fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/47f8f2ebd987</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[text-processing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tf-idf]]></category>
            <dc:creator><![CDATA[Sumeet Agrawal]]></dc:creator>
            <pubDate>Fri, 01 Oct 2021 04:47:52 GMT</pubDate>
            <atom:updated>2021-10-01T05:23:53.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/697/0*RT32U_XnLemc9EMW.png" /><figcaption>Image Source — <a href="https://mywebxdigital.com/tfidf-for-seo-test-results-and-tool-comparison/">https://mywebxdigital.com/tfidf-for-seo-test-results-and-tool-comparison/</a></figcaption></figure><p>Natural Language Processing (NLP) is a sub-field of artificial intelligence that deals with understanding and processing human language.</p><p><strong>TF*IDF</strong> is an information retrieval technique that weighs a <strong>term’s frequency (TF)</strong> and its <strong>inverse document frequency (IDF)</strong>. Each word or term that occurs in the text has its respective TF and IDF score.<br>The product of the TF and IDF scores of a term is called the TF*IDF weight of that term. Put simply, the higher the TF*IDF score (weight), the rarer the term is in a given document and vice versa.</p><p>For a term <strong>t</strong> in document <strong>d</strong>, the weight <strong>Wt,d</strong> of term t in document d is given by:</p><blockquote><strong>Wt,d = TFt,d log (N/DFt)</strong></blockquote><p>Where:</p><ul><li>TFt,d is the number of occurrences of t in document d.</li><li>DFt is the number of documents containing the term t.</li><li>N is the total number of documents in the corpus.</li></ul><h4>Breaking TF*IDF down</h4><p>How is TF*IDF calculated? The TF (term frequency) of a word is the frequency of a word (i.e. number of times it appears) in a document. <strong>When you know TF, you’re able to see if you’re using a term too much or too little.</strong></p><p>For example, when a <strong>100-word document</strong> contains the term <em>“book”</em> <strong>16 times</strong>, the TF for the word <em>‘book’</em> is</p><p><strong>TF</strong><em>book</em> = 16/100 i.e. <strong>0.16</strong></p><p>The IDF (inverse document frequency) of a word is the measure of how significant that term is in the whole corpus.</p><p>Let’s say the size of the corpus is 10,000,000 million documents. If we assume there are 0.4 million documents that contain the term <em>“book”</em>, then the IDF (i.e. log {DF}) is given by the total number of documents (10,000,000) divided by the number of documents containing the term <em>“book”</em> (400,000).</p><p>IDF (<em>book</em>) = log (10,000,000/400,000) = 1.4</p><p>∴ <strong>W</strong><em>book</em> = (TF*IDF) <em>book</em>= 0.16 * 1.4 = 0.224</p><h3>Coding</h3><p>Let’s get started with some coding right now. We’ll begin by importing the required libraries.</p><pre>import pandas as pd<br>from sklearn.feature_extraction.text import TfidfVectorizer</pre><p>In this article, we’ll be working with two simple documents containing one sentence each.</p><pre>documentA = &#39;the man went out for a walk&#39;<br>documentB = &#39;the children sat around the fire&#39;</pre><p>Machine learning algorithms are unable to deal directly with raw text. Rather, the text must be transformed into numerical vectors. A typical approach for extracting characteristics from the text in natural language processing is to put all of the words that appear in the text in a bucket. This approach is called a <strong>bag of words</strong> model or <strong>BoW</strong> for short. It’s referred to as a <strong><em>“bag” </em></strong>of words because any information about the structure of the sentence is lost.</p><pre>bagOfWordsA = documentA.split(&#39; &#39;)<br>bagOfWordsB = documentB.split(&#39; &#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/0*bzuKrn-p7l_63R9F.png" /></figure><p>By casting the bag of words to a set, we can automatically remove any duplicate words.</p><pre>uniqueWords = set(bagOfWordsA).union(set(bagOfWordsB))</pre><p>Next, we’ll create a dictionary of words and their occurrence for each document in the corpus (collection of documents).</p><pre>numOfWordsA = dict.fromkeys(uniqueWords, 0)for word in bagOfWordsA:<br>    numOfWordsA[word] += 1numOfWordsB = dict.fromkeys(uniqueWords, 0)for word in bagOfWordsB:<br>    numOfWordsB[word] += 1</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/0*vhMLZ-74g5Quy0SC.png" /></figure><p>Another issue with the bag of words method is that it does not take noise into consideration. To put it another way, certain words are utilized to create sentences but contribute no semantic value to the text. For example, the most commonly used word in the English language is ‘<strong><em>the’ </em></strong>that represents 7% of all words written or spoken. You couldn’t make deduce anything about a text given the fact that it contains the word <strong>the</strong>. On the other hand, words like <strong>good</strong> and <strong>awesome</strong> could be used to determine whether a rating was positive or not.</p><p>In natural language processing, useless words are referred to as stop words. The python <strong>natural language toolkit</strong> library provides a list of English stop words.</p><pre>from nltk.corpus import stopwordsstopwords.words(&#39;english&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*2uDIL_ZiYC1e0itv.png" /></figure><p>Oftentimes, when building a model with the goal of the understanding text, you’ll see all of the stop words being removed. Another strategy is to score the relative importance of words using TF-IDF.</p><h3>Term Frequency (TF)</h3><p>The number of times a word appears in a document is divided by the total number of words in the document. Every document has its own term frequency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/0*HHP0rxrEVsXeDJys.png" /></figure><p>The following code implements term frequency in python.</p><pre>def computeTF(wordDict, bagOfWords):<br>    tfDict = {}<br>    bagOfWordsCount = len(bagOfWords)<br>    for word, count in wordDict.items():<br>        tfDict[word] = count / float(bagOfWordsCount)<br>    return tfDict</pre><p>The following lines compute the term frequency for each of our documents.</p><pre>tfA = computeTF(numOfWordsA, bagOfWordsA)<br>tfB = computeTF(numOfWordsB, bagOfWordsB)</pre><h3>Inverse Data Frequency (IDF)</h3><p>The log of the number of documents divided by the number of documents that contain the word <strong><em>w</em></strong>. Inverse data frequency determines the weight of rare words across all documents in the corpus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*NV280JyP7MBoColj.png" /></figure><p>The following code implements inverse data frequency in python.</p><pre>def computeIDF(documents):<br>    import math<br>    N = len(documents)<br>    <br>    idfDict = dict.fromkeys(documents[0].keys(), 0)<br>    for document in documents:<br>        for word, val in document.items():<br>            if val &gt; 0:<br>                idfDict[word] += 1<br>    <br>    for word, val in idfDict.items():<br>        idfDict[word] = math.log(N / float(val))<br>    return idfDict</pre><p>The IDF is computed once for all documents.</p><pre>idfs = computeIDF([numOfWordsA, numOfWordsB])</pre><p>Lastly, the TF-IDF is simply the TF multiplied by IDF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/0*q3F396dXIrBqdMNU.png" /></figure><pre>def computeTFIDF(tfBagOfWords, idfs):<br>    tfidf = {}<br>    for word, val in tfBagOfWords.items():<br>        tfidf[word] = val * idfs[word]<br>    return tfidf</pre><p>Finally, we can compute the TF-IDF scores for all the words in the corpus.</p><pre>tfidfA = computeTFIDF(tfA, idfs)<br>tfidfB = computeTFIDF(tfB, idfs)df = pd.DataFrame([tfidfA, tfidfB])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*B8FeRc36l5nK2PW5.png" /></figure><p>Rather than manually implementing TF-IDF ourselves, we could use the class provided by sklearn.</p><pre>vectorizer = TfidfVectorizer()vectors = vectorizer.fit_transform([documentA, documentB])feature_names = vectorizer.get_feature_names()dense = vectors.todense()denselist = dense.tolist()df = pd.DataFrame(denselist, columns=feature_names)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*a3IO1_gOnReVYB2B.png" /></figure><p>The values differ slightly because sklearn uses a smoothed version of IDF and various other little optimizations. In an example with more text, the score for the word <strong><em>the</em></strong> would be greatly reduced.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47f8f2ebd987" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Activation Function in Neural Network]]></title>
            <link>https://medium.com/@Sumeet_Agrawal/activation-function-in-neural-network-dc5e51c80ce8?source=rss-9c3354409fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc5e51c80ce8</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[almabetter]]></category>
            <dc:creator><![CDATA[Sumeet Agrawal]]></dc:creator>
            <pubDate>Wed, 01 Sep 2021 07:32:45 GMT</pubDate>
            <atom:updated>2021-09-01T07:32:45.853Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>We used a variety of activation functions in <a href="https://medium.com/@Sumeet_Agrawal/introduction-to-deep-learning-4410c5fb5a9a">deep learning</a>. Activation functions are the most important aspect of any neural network in deep learning. Image classification, language translation, object recognition, and other complex tasks in deep learning require the use of neural networks and activation functions to solve. As a result, these tasks are extremely difficult to handle without it.</p><p>In general, the neural network activation functions, are the most important component of Deep Learning. They are used to determine the output of deep learning models, the performance efficiency of the training model, and its accuracy, which can design or split a massive neural network.</p><p>The Activation functions have a significant impact on the ability and speed with which neural networks converge. Let’s continue reading this blog to understand the activation function, its <strong>types </strong>&amp; <strong>their importance, and their limitations.</strong></p><h3>What is the Activation Function?</h3><blockquote>The Activation Function is a non linear modification used to each neuron in a hidden layer to get output in a normalized form (or in a certain range or scale).</blockquote><p>To produce the desired outcome, they simply determine whether to deactivate or activate neurons. It also applies a nonlinear adjustment to the input in order to improve the performance of a sophisticated <strong>neural network</strong>.</p><p>The activation function also aids in the normalization of any input’s output in the range between <strong>1 to -1</strong>. Because the neural network is occasionally trained on millions of data points, the activation function must be efficient and should reduce the computation time.</p><p>In any neural network,the activation function basically determines whether a given input or receiving information is meaningful or irrelevant.To further understand what a neuron is and how the activation function restricts the output value, consider the following example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*1Xccq6MmgpCzR6OC.gif" /><figcaption>Image Source —<a href="https://machinelearningknowledge.ai/decoding-softmax-activation-function-for-neural-network-with-examples-in-numpy-keras-tensorflow-and-pytorch/"> https://machinelearningknowledge.ai</a></figcaption></figure><h3>Why do we use the Activation Function?</h3><ul><li>To normalize data, we employ the activation function .</li><li>To obtain nonlinearity between data in a Feed-Forward Network (FFN), we execute a nonlinearization operation on linear data</li></ul><p>They essentially decide whether a neuron should be activated or not, as well as the information received by neuron is relevant to the provided information or should be ignored.</p><p>Without the activation function, weight and bias would only have a linear transformation, and a neural network would be nothing more than a linear regression model. A linear equation is a one degree polynomial that is simple to solve but limited in its ability to solve complex problems or higher degree polynomials.</p><p>The Activation Functions can be classified into two categories:-</p><ol><li><strong>Linear Activation Function</strong></li><li><strong>Non-linear Activation Functions</strong></li></ol><h3>1. Linear or Identity Activation Function</h3><p>The function is a line or linear, as you can see. As a result, the functions’ output will be unconstrained by any range.</p><p><strong>Equation : </strong>f(x) = x</p><p><strong>Range :</strong> (-infinity to infinity)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6g9TYTVu-v6e6Exn.png" /><figcaption>Image Source — <a href="https://www.geeksforgeeks.org/understanding-activation-functions-in-depth/">https://www.geeksforgeeks.org/understanding-activation-functions-in-depth/</a></figcaption></figure><p>It doesn’t help with the complexities of numerous parameters in the data that is normally provided to neural networks.</p><h3>2. Non-linear Activation Function</h3><p>The most commonly utilised activation functions are nonlinear activation functions. Nonlinearity contributes to the appearance of this graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CBv2a1BVPozqvXir.png" /><figcaption>Image Source — <a href="https://www.geeksforgeeks.org/understanding-activation-functions-in-depth/">https://www.geeksforgeeks.org/understanding-activation-functions-in-depth/</a></figcaption></figure><p>It allows the model to generalise or adapt to a wide range of data while also distinguishing between the outputs.</p><p>The following are the most important nonlinear function terms to know:</p><blockquote><strong><em>Derivative or Differential: </em></strong><em>Change in y-axis w.r.t. change in x-axis.It is also known as slope.</em></blockquote><blockquote><strong><em>Monotonic function:</em></strong><em> A function which is either completely non-increasing or completely non-decreasing.</em></blockquote><h3>Different Activation Functions are -</h3><ol><li>Binary Step</li><li>Linear</li><li>Sigmoid</li><li>Tanh</li><li>ReLU</li><li>LeakyReLU</li></ol><p><strong>1. Binary Step</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sfM1AEBmysWDI2cI.png" /><figcaption>Image source — <a href="https://arshren.medium.com/neural-networks-activation-functions-e371202b56ff">https://arshren.medium.com/neural-networks-activation-functions</a></figcaption></figure><p>This is a pretty basic activation function that comes to mind whenever we try to bind output. It’s essentially a threshold-based classifier in which we choose a threshold value to determine whether a neuron should be activated or deactivated as an output. We set the threshold value to 0 in this case. Classifying binary problems or classifiers is relatively simple and useful.</p><p><strong>2. Linear Activation Function</strong></p><p>It’s a straightforward activation function in which the weighted sum of neurons or input is precisely proportional to our function. A positive sloped line may boost the firing rate as the input rate rises, while linear activation functions provide a larger range of activations.</p><p>A neuron is either firing or not firing in binary. If you’re familiar with gradient descent in deep learning, you’ll notice that the derivative in this function is constant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/0*HtMC5NE6OmVDFHRA.png" /><figcaption>Image Source — <a href="https://www.i2tutorials.com/activation-functions-in-neural-networks/">https://www.i2tutorials.com/activation-functions-in-neural-networks/</a></figcaption></figure><p><strong>Equation : </strong>f(x) = x</p><p><strong>Range :</strong> (-infinity to infinity)</p><p><strong>3. Sigmoid Activation Function</strong></p><p>The Sigmoid Function curve looks like <strong>S-shape</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*Fv6lpHCttKjFbBz7OoktGg.png" /><figcaption>Sigmoid Function</figcaption></figure><p>Output range is between 0 and 1 i.e. [0,1]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*tLL9SubRi2cW2I0U15UHuw.png" /><figcaption>Derivative of Sigmoid Function</figcaption></figure><p>Output range is between 0 and 0.25</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*VBTYqBiELEASfZJp.jpg" /><figcaption>Image Source — <a href="https://saugatbhattarai.com.np/what-is-activation-functions-in-neural-network-nn/">https://saugatbhattarai.com.np/what-is-activation-functions-in-neural-network-nn/</a></figcaption></figure><p>The sigmoid function is used because it exists between two points (0 to 1). As a result, it is particularly useful in models where the probability must be predicted as an output. Because the likelihood of anything only occurs between 0 and 1, sigmoid is the best option.</p><p>It is possible to differentiate the function. That means we can calculate the sigmoid curve’s slope at any two points. Although the function is monotonic, its derivative is not.</p><p><strong>Problems of Sigmoid Function are-</strong></p><p>Vanishing gradient</p><p>Computationally expensive</p><p>The output is not zero centered</p><p>The <strong>softmax function</strong> is a multiclass classification function that is more generalised than the logistic activation function.</p><p><strong>4. TanH (hyperbolic tangent) Activation Function</strong></p><p>TanH is also like logistic sigmoid but better. The range of the tanh function is from (-1 to 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*z7QBIFugIMHlUk8YwV45qg.png" /><figcaption>TanH Function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*AfzeZkzWHvOfKW8hU4XclQ.png" /><figcaption>Derivative of TanH</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/0*86CTdycJSGo1tD-3.png" /><figcaption>Image Source — <a href="https://dothanhblog.wordpress.com/2020/02/19/machine-learning-common-loss-and-activation-functions/">https://dothanhblog.wordpress.com/2020/02/19/machine-learning</a></figcaption></figure><p><strong>Advantages of TanH function</strong></p><ul><li>We can find the differentiation from this function.</li><li>It’s a function that’s centered around zero.</li><li>In comparison to sigmoid, optimization is simple.</li></ul><p><strong>Disadvantages of TanH function</strong></p><ul><li>Because it is a computationally intensive function, the</li><li>conversion will take a long time.</li></ul><p>•Vanishing gradients</p><p><strong>5. ReLU Activation Function</strong></p><p>Right now, the ReLU is the most widely utilized activation function on the planet. It’s used in practically all convolutional neural networks and deep learning algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/0*zFwoGlKoZblBt-0o.png" /><figcaption>ReLU Function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*FPaKb0LMENQ4kVKv.png" /><figcaption>Image Source —<a href="https://towardsdatascience.com/7-popular-activation-functions-you-should-know-in-deep-learning-and-how-to-use-them-with-keras-and-27b4d838dfe6"> activation functions you should know in Deep Learning</a></figcaption></figure><p><strong>Range: </strong>[ 0 to infinity)</p><p><strong>Advantages —</strong></p><ul><li>We can find a differential.</li><li>Solve the problem of vanishing gradients.</li><li>Because there is no exponential calculation here, the calculation is faster than sigmoid or tanh.</li></ul><p><strong>Disadvantages —</strong></p><ul><li>It is not a zero-centric function.</li><li>It is fully inactive for -ve input.</li></ul><p><strong>6. Leaky ReLU Activation Function</strong></p><p>The Leaky ReLU function is superior to the ReLU activation function. It has all of the features of ReLU and will never suffer from the Dying ReLU problem. The term <strong>“leaky ReLU”</strong> is defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/0*9xv7xQgD1s9tOQj4.png" /><figcaption>Equation of Leaky ReLU Function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*L0Ds-6SESgwtu4sX.png" /><figcaption>Image Source — <a href="https://paperswithcode.com/method/leaky-relu">https://paperswithcode.com/method/leaky-relu</a></figcaption></figure><blockquote><strong><em>Dying ReLU</em></strong></blockquote><blockquote>Some neurons effectively die during training, which means they stop producing anything other than zero. In some circumstances, especially if you utilized a high learning rate, you may discover that half of your network’s neurons are dead. When the weights of a neuron are changed to the point where the weighted sum of its inputs is negative for all instances in the training set, the neuron dies. When this happens, it simply continues to output 0s, and gradient descent has no effect because the ReLU function’s gradient is 0 when its input is negative.</blockquote><p>This is all about the activation functions. Hopefully, you have now understood the activation functions. Also, I have written a blog on <a href="https://medium.com/@Sumeet_Agrawal/introduction-to-deep-learning-4410c5fb5a9a">“Introduction to Deep Learning”.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc5e51c80ce8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Deep Learning]]></title>
            <link>https://medium.com/@Sumeet_Agrawal/introduction-to-deep-learning-4410c5fb5a9a?source=rss-9c3354409fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4410c5fb5a9a</guid>
            <category><![CDATA[introduction]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[weight-initialization]]></category>
            <dc:creator><![CDATA[Sumeet Agrawal]]></dc:creator>
            <pubDate>Sat, 28 Aug 2021 13:30:16 GMT</pubDate>
            <atom:updated>2021-08-28T13:30:16.935Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, deep learning has become somewhat of jargon in the tech community. We always seem to hear about it in news regarding AI, and yet most people don’t actually know about it. In this article, I’ll be illustrating an introduction to deep learning and providing an intuition of how it works.</p><p>It also powers some of the most interesting applications in the world, like autonomous vehicles and real-time translation, and many others. There was certainly a bunch of excitement around Google’s Deep Learning-based <a href="https://www.scientificamerican.com/article/how-the-computer-beat-the-go-master/">AlphaGo beating the best Go player</a> in the world, but more importantly, the business applications for this technology are more immediate and potentially more impactful. This post will break down where Deep Learning fits into the ecosystem, working on it, and why it is more important in the recent world.</p><p><strong>So what is deep learning?</strong></p><blockquote><strong>Deep learning is termed as the type of machine learning (or subset of machine learning) and artificial intelligence (AI) that mimic the way humans gain certain types of knowledge. It is an important element of data science, which includes statistics and predictive modeling.</strong></blockquote><p>Some of the most magnificent advances in artificial intelligence in recent years have been in the field of deep learning. Natural language translation, voice and image recognition, face emotion recognition, etc. are all tasks where deep learning models have neared or even exceeded human-level performance.</p><h3>The intuition behind Deep Learning</h3><p>Generally, deep learning is a machine learning method or a subset of machine learning that takes in an input X and uses it to predict an output of Y.</p><p>For example, let’s say that inputs are images of dogs and cats, and outputs are labels for those images. So here, in this case, X is input images and Y is the predicted output i.e. labels for cat or dog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JeblKGSeSsyozlsF.gif" /></figure><p>Image source <a href="https://becominghuman.ai/beginners-guide-cnn-image-classifier-part-1-140c8a1f3c12">becominghuman.ai/beginners-guide-cnn-image-classifier</a></p><h3>How Do Deep Learning algorithms “learn”?</h3><p>Deep Learning Algorithms use a network of structures called a neural network to find associations between a set of inputs and outputs. The basic structure is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*6_u403LO83aMVhc_.jpg" /></figure><p>Image Source — <a href="https://www.researchgate.net/figure/An-artificial-neural-network-with-three-inputs-and-one-output_fig1_327440209">https://www.researchgate.net/figure/An-artificial-neural-network</a></p><p>A neural network is composed of<strong> input layers, hidden layers, and output layers</strong> — all of which are composed of <strong>“nodes”</strong>. The first layer is <strong>input layer</strong> which receives the input information in the form of <strong>texts, numbers, audio, image pixels, etc</strong>. In the middle of the model are the hidden layers. There may be a <strong>single hidden layer,</strong> as in the case of <strong>perception,</strong> or maybe multiple hidden layers. Various mathematical computations performed by the hidden layers on the input data and recognize the patterns from it. In the output layer, we obtain the result that we obtain through meticulous computations performed by the middle layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*JJwHaFsq3NyISth-.PNG" /></figure><p>Image Source — <a href="https://www.simplilearn.com/tutorials/deep-learning-tutorial/deep-learning-algorithm">https://www.simplilearn.com/tutorials/deep-learning-tutorial/</a></p><p>Each node in the layers has some weights assigned to it. A function is used which is called the <strong>transfer function </strong>which is used for calculating the weighted sum of the inputs and the bias.</p><p>After the transfer function has calculated the weighted sum, the activation function obtains the result. Based on the output, the activation functions fire the appropriate result from the node. <strong>For example</strong>, if the output received is above 0.5, the activation function fires the value as 1 otherwise it remains 0.</p><p>The information is passed between network layers through the function and the major points to keep a note here that tunable weight and bias parameters which are represented by <strong>w and b</strong> respectively in the function above. These are the essential for actual “learning” process of a deep learning algorithm.</p><p>After the neural network passes its inputs to its outputs, the network evaluates how good its prediction was (relative to the expected output) through something called a <strong>loss function</strong>. For example, the <strong>“Mean Squared Error”</strong> loss function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/0*Or3z77fnOmDK3x8q" /></figure><p><em>Here in the equation</em><strong><em> Y hat</em></strong><em> represents the prediction, while </em><strong><em>Y</em></strong><em> represents the expected output. A mean is used if inputs and outputs are used in batches simultaneously (n represents sample count)</em></p><p>The goal of the network is ultimately to minimize the loss by adjusting the weights and biases of the network. It uses something which is called <strong>“backpropagation”</strong> through gradient descent. The network backtracks through all the layers in the opposite direction of the loss function to update the weights and biases of each node. in simpler words, every iteration of backpropagation should result in a smaller loss function than before.</p><h3>How does Deep Learning work?</h3><p>The inspiration for<strong> deep learning</strong> is same as the way that the human brain filters information. Its main motive is to simulate decision-making just like human. Neurons in the brain that passes the signals to perform the various actions. Similarly, artificial neurons connect in a neural network to perform tasks such as clustering, classification, or regression. The neural network also try to sorts the unlabeled data according to the similarities of the data. That’s the whole idea behind the deep learning algorithm.</p><p>Neurons are grouped into three different types of layers:</p><p>1. Input Layer</p><p>2. Hidden Layer</p><p>3. Output Layer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*OJ5NS2FuIlyjpOwa.jpg" /></figure><p>Image Source — <a href="https://www.janbasktraining.com/blog/deep-learning-with-keras/">https://www.janbasktraining.com/blog/deep-learning-with-keras/</a></p><h3>1. Input Layer</h3><p>It receives the input data from the observation (in the form of text, image, audio etc). This information breaks into bits of binary data and numbers.Computer can understand the data into numbers only. Variables need to be either standardized or normalized within the same range at each nodes.</p><h3>2. Hidden Layer</h3><p>In this layer various mathematical computations done on the input data. It is challenging process to decide the number of hidden layers and the number of neurons in each layer. Also in this layer, It does the non-linear processing units for feature extraction and transformation. Each following layer uses the output of the previous layer as input.</p><h3>3. Output Layer</h3><p>In the output layer, we get the desired result.</p><p>Consider an example of an image of a face, whose input might be in the form of a matrix of pixels. The first layer encodes the edges by using different filters and tries to composes the pixels. The next layer encodes a nose and eyes or maybe anyone of them. The next layer might recognize the face, and so on.</p><p>The connection between neurons is called <strong>weight</strong>. The weight between neurons decides the learning ability of the neural network. During the learning of neural networks, the weight between the neurons changes. Initial weights are set randomly.</p><p>To standardize the output from the neuron, we use the <strong>“activation function”</strong>. Each neuron has its activation function and this activation function also helps to normalize the output in a range between 0 to 1 or -1 to 1<strong>.</strong></p><h3>How to initialize weight?</h3><p>Techniques generally practiced to initialize parameters are:</p><p><strong>1. Zero Initialization</strong></p><p><strong>2. Random Initialization</strong></p><h3>1. Zero Initialization</h3><p>Generally, biases are initialized with 0, and weights are initialized with random numbers, <strong>what if weights are initialized with 0?</strong></p><p>If all weights are initialized with the value 0, then the derivative with respect to loss function is the same for every weight. This makes the hidden units symmetric for all the n iterations i.e. setting weights value to 0 does not make it better than a linear model. An important thing to note is that biases have no effect when weights are initialized with the value 0.</p><h3>2. Random Initialization</h3><p>In random initialization, we initialize random values to weights which is better than just 0 assignment. But there is one issue with random initialization that if weights are initialized high values or very low values then it suffers from the problem of vanishing gradient.</p><p><strong>a) </strong>If weights are initialized with very high values then the term becomes remarkably higher and if an activation function like sigmoid activation is applied, then the function depicts its value near 1. Due to this the slope of gradient changes slowly and learning takes much more time.</p><p><strong>b)</strong> If weights are initialized with very low values then the term becomes significantly lower and it gets mapped to 0, where the case is the same as above.</p><h3>How to train Neural Network</h3><p>Training the neural network is a difficult task as it requires a huge data set and also a large amount of computational power. Iterating through the observations in the data set and comparing the outputs will produce a <strong>Cost Function</strong>.</p><p>There are two processes for minimizing the cost function.</p><h3>1) Backpropagation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*wtqMyd7PvnRbpCIj.png" /><figcaption>Image Source — <a href="https://www.researchgate.net/figure/A-Feed-forward-network-with-backpropagation-learning-input-data-flows-the-direction_fig4_221983860">https://www.researchgate.net/figure/</a></figcaption></figure><p>Back-propagation is a popular approach that is similar to the gradient descent algorithm. The back-propagation algorithm allows the error to ﬂow backward through the network, in order to compute the gradient. Once we have the gradient of this error as a function of the neuron’s weights, we can generate these output errors <strong>backward to infer errors for the other layers </strong>and adjust its weights in the direction to decreases the error.</p><p>The chain rule of calculus is used to compute the derivatives of functions formed by adding other functions whose derivatives are known. The chain rule states that the right thing to do is to simply multiply the gradients together to chain them.</p><h3>2) Forward propagation</h3><p>The information enters into the input layer and forwards in the network to the hidden layer and finally to the output layer to get the output value. Then we can compare the value to the expected results. After that, the next step is calculating errors and propagating the information back to the input layer to update the weights. This permits the algorithm to train the neural network and modernize the weights. Due to the structured algorithm, the algorithm can adjust weights simultaneously. It will help us to know that which weight of the neural network is responsible for the error.</p><h3>Applications of Deep Learning</h3><ol><li>Self Driving Cars</li><li>News Aggregation and Fraud News Detection</li><li>Natural Language Processing</li><li>Virtual Assistants</li><li>Entertainment</li><li>Visual Recognition</li><li>Fraud Detection</li><li>Healthcare</li><li>Detecting Developmental Delay in Children</li><li>Language Translations</li></ol><h3>Summary</h3><p>In conclusion, Deep Learning has given a boom to the technology industry in recent times. By reading this article, you know how deep learning works like the human brain. It mimics the way our brain works and learns from experiences. You also now know about the different layers of artificial neural networks. Moreover, you now know about the weights, activation functions, and training of neural networks. Hope this article will help you to understand the basis of deep learning and how it works.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4410c5fb5a9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluation Metrics for Classification Problem]]></title>
            <link>https://medium.com/@Sumeet_Agrawal/evaluation-metrics-for-classification-problem-41cbd887b1d5?source=rss-9c3354409fc7------2</link>
            <guid isPermaLink="false">https://medium.com/p/41cbd887b1d5</guid>
            <category><![CDATA[classification-models]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[evaluation-metric]]></category>
            <dc:creator><![CDATA[Sumeet Agrawal]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 03:40:53 GMT</pubDate>
            <atom:updated>2021-07-20T03:40:53.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cn1x03pxWzyKce-7.jpg" /><figcaption>Image Source — <a href="https://www.kaggle.com/nkitgupta/evaluation-metrics-for-multi-class-classification">https://www.kaggle.com/nkitgupta/evaluation-metrics-for-multi-class-classification</a></figcaption></figure><h3>Abstract</h3><p>The most important task in building any machine learning model is to evaluate its performance. So, the question arises that how would one measure the success of a machine learning model? How would we know that when to stop the training and evaluation and when to call it good?</p><p>With the help of this article, I’ll try to answer these questions. This article is organized as follows: In the first section, I’ll start with introducing what we mean by “ML Model Evaluation” and why it’s actually necessary to evaluate any machine learning model. In other subsequent section, we’ll discuss various evaluation metrics available to specific use cases in subsequent sections to better understand these metrics.</p><h3>Introduction</h3><p>Evaluation metrics are tied to machine learning tasks. There are different metrics for the tasks of classification and regression. Some metrics, like precision-recall, are useful for multiple tasks. Classification and regression are examples of supervised learning, which constitutes a majority of machine learning applications. Using different metrics for performance evaluation, we should be able to improve our model’s overall predictive power before we roll it out for production on unseen data. Without doing a proper evaluation of the Machine Learning model by using different evaluation metrics, and only depending on accuracy, can lead to a problem when the respective model is deployed on unseen data and may end in poor predictions.</p><p>In the next section, I’ll discuss the Classification evaluation metrics that could help in the generalization of the ML classification model.</p><h3>Classification Metrics</h3><p>Classification is about predicting the class labels given input data. In binary classification, there are only two possible output classes(i.e., Dichotomy). In multiclass classification, more than two possible classes can be present. I’ll focus only on binary classification.</p><p>A very common example of binary classification is spam detection, where the input data could include the email text and metadata (sender, sending time), and the output label is either <em>“spam” or “not spam.”</em> (<em>See Figure</em>) Sometimes, people use some other names also for the two classes: “positive” and “negative,” or “class 1” and “class 0.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*xgiEyLEym8eh-HeO98WR6w.png" /><figcaption>Figure — Email spam detection is a binary classification problem (source: From Book — Evaluating Machine Learning Model — O&#39;Reilly)</figcaption></figure><p>There are many ways for measuring classification performance. Accuracy, confusion matrix, log-loss, and AUC-ROC are some of the most popular metrics. Precision-recall is a widely used metrics for classification problems.</p><h3>Accuracy</h3><p>Accuracy simply measures how often the classifier correctly predicts. We can define accuracy as the ratio of the number of correct predictions and the total number of predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*R6jP_uvlkcxtQSa264N3Sw.png" /></figure><p>When any model gives an accuracy rate of 99%, you might think that model is performing very good but this is not always true and can be misleading in some situations. I am going to explain this with the help of an example.</p><p>Consider a binary classification problem, where a model can achieve only two results, either model gives a <strong>correct</strong> or <strong>incorrect </strong>prediction. Now imagine we have a classification task to predict if an image is a dog or cat as shown in the image. In a supervised learning algorithm, we first <strong>fit/train </strong>a model on training data, then <strong>test</strong> the model on <strong>testing data</strong>. Once we have the model’s predictions from the <strong>X_test</strong> data, we compare them to the<strong> true y_values</strong> (the correct labels).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*zzR88UEu6A786mPYcRVDhQ.png" /><figcaption>Image Source — <a href="https://www.kdnuggets.com/2020/04/performance-evaluation-metrics-classification.html">https://www.kdnuggets.com/2020/04/performance-evaluation-metrics-classification.html</a></figcaption></figure><p>We feed the image of the dog into the training model. Suppose the model predicts that this is a dog, and then we compare the prediction to the correct label. If the model predicts that this image is a cat and then we again compare it to the correct label and it would be incorrect.</p><p>We repeat this process for all images in X_test data. Eventually, we’ll have a count of correct and incorrect matches. But in reality, it is very rare that all incorrect or correct matches hold <strong>equal value</strong>. Therefore one metric won’t tell the entire story.</p><p>Accuracy is useful when the target class is <strong><em>well balanced</em></strong> but is not a good choice for the unbalanced classes. Imagine the scenario where we had 99 images of the dog and only 1 image of a cat present in our training data. Then our model would always predict the dog, and therefore we got 99% accuracy. In reality, Data is always imbalanced for example Spam email, credit card fraud, and medical diagnosis. Hence, if we want to do a better model evaluation and have a full picture of the model evaluation, other metrics such as recall and precision should also be considered.</p><h3>Confusion Matrix</h3><p>Confusion Matrix is a performance measurement for the machine learning classification problems where the output can be two or more classes. It is a table with combinations of predicted and actual values.</p><blockquote><strong><em>A confusion matrix is defined as the table which is used to describe the performance of a classification model on a set of the test data for which the true values are known</em></strong><em>.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*_JY_jxfndH8oBI3clamifA.png" /><figcaption>Image Source — <a href="https://www.roelpeters.be/glossary/what-is-a-confusion-matrix/">https://www.roelpeters.be/glossary/what-is-a-confusion-matrix/</a></figcaption></figure><p>It is extremely useful for measuring the Recall, Precision, Accuracy, and AUC-ROC curves.</p><p>Let’s try to understand TP, FP, FN, TN with an example of pregnancy analogy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*UnezxOaQyU6Fb6D3" /><figcaption>Image Source- <a href="https://dzone.com/articles/understanding-the-confusion-matrix">https://dzone.com/articles/understanding-the-confusion-matrix</a></figcaption></figure><p><strong>True Positive: </strong>We predicted positive and it’s true. In the image, we predicted that a woman is pregnant and she actually is.</p><p><strong>True Negative: </strong>We predicted negative and it’s true. In the image, we predicted that a man is not pregnant and he actually is not.</p><p><strong>False Positive (Type 1 Error)- </strong>We predicted positive and it’s false. In the image, we predicted that a man is pregnant but he actually is not.</p><p><strong>False Negative (Type 2 Error)- </strong>We predicted negative and it’s false. In the image, we predicted that a woman is not pregnant but she actually is.</p><p><strong>We discussed Accuracy, now let’s discuss some other metrics of the confusion matrix</strong></p><p><strong>1. Precision — </strong>Precision explains how many of the correctly predicted cases actually turned out to be positive. Precision is useful in the cases where False Positive is a higher concern than False Negatives. The importance of <em>Precision is in music or video recommendation systems, e-commerce websites, etc. where wrong results could lead to customer churn and this could be harmful to the business.</em></p><blockquote><strong>Precision for a label is defined as the number of true positives divided by the number of predicted positives.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*p1t9CzwpaOXxsx4l.png" /></figure><p><strong>2. Recall (Sensitivity) — </strong>Recall explains how many of the actual positive cases we were able to predict correctly with our model. It is a useful metric in cases where False Negative trumps False Positive. <em>For examle in medical cases it doesn’t matter whether we raise a false alarm but the actual positive cases should not go undetected!</em></p><blockquote><strong>Recall for a label is defined as the number of true positives divided by the total number of actual positives.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/0*XgGoMQLlGGDgpzYa.png" /></figure><p><strong>3. F1 Score </strong>— It gives a combined idea about Precision and Recall metrics. It is maximum when Precision is equal to Recall.</p><blockquote><strong>F1 Score is the harmonic mean of precision and recall.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/0*tu5x_GEgs-iRpJ9H" /></figure><p>The F1 score punishes extreme values more. F1 Score could be an effective evaluation metric in the following cases:</p><ul><li>When FP and FN are equally costly.</li><li>Adding more data doesn’t effectively change the outcome</li><li>True Negative is high</li></ul><p><strong>4. AUC-ROC — </strong>The Receiver Operator Characteristic (ROC) is a probability curve that plots the TPR(True Positive Rate) against the FPR(False Positive Rate) at various threshold values and separates the ‘signal’ from the ‘noise’.</p><p>The <strong>Area Under the Curve (AUC)</strong> is the measure of the ability of a classifier to distinguish between classes. From graph we simply say area of the curve ABDE and X and Y axis.</p><p>From the graph shown below, the greater the AUC, the better is the performance of the model at different threshold points between positive and negative classes. This simply means that When AUC is equal to 1, the classifier is able to perfectly distinguish between all Positive and Negative class points. When AUC is equal to 0, the classifier would be predicting all Negatives as Positives and vice versa. When AUC is 0.5, the classifier is not able to distinguish between the Positive and Negative classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*bpjCSt38NydElzPf6O5Xng.png" /><figcaption>Image Source— <a href="https://www.analyticsvidhya.com/blog/2020/06/auc-roc-curve-machine-learning/">https://www.analyticsvidhya.com/blog/2020/06/auc-roc-curve-machine-learning/</a></figcaption></figure><p><strong>Working of AUC — </strong>In a ROC curve, X-axis value shows False Positive Rate (FPR) and Y axis shows True Positive Rate (TPR). Higher the value of X means higher the number of False Positives(FP) than True Negatives(TN), while a higher Y-axis value indicates a higher number of TP than FN. So, the choice of the threshold depends on the ability to balance between FP and FN.</p><p><strong>5. Log Loss — Log loss (Logistic loss) or Cross-Entropy Loss</strong> is one of the major metrics to assess the performance of a classification problem.</p><p>For a single sample with true label y∈{0,1} and a probability estimate p=Pr(y=1), the log loss is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hGFmvwiq4mmHySvY.png" /></figure><h3>Conclusion</h3><p>Understanding how well a machine learning model will perform on unseen data is the main purpose behind working with these evaluation metrics. Metrics like accuracy, precision, recall are good ways to evaluate classification models for balanced datasets, but if the data is imbalanced then other methods like ROC/AUC perform better in evaluating the model performance.</p><p>ROC curve isn’t just a single number but it’s a whole curve that provides nuanced details about the behavior of the classifier. It is also hard to quickly compare many ROC curves to each other.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41cbd887b1d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>