<?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 Himanshu Sharma on Medium]]></title>
        <description><![CDATA[Stories by Himanshu Sharma on Medium]]></description>
        <link>https://medium.com/@harshsharma1091996?source=rss-5e53c86ec9df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3Sm-emVZ2AEcAjLJ</url>
            <title>Stories by Himanshu Sharma on Medium</title>
            <link>https://medium.com/@harshsharma1091996?source=rss-5e53c86ec9df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 02:39:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshsharma1091996/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[Twitter Microblogging System Design]]></title>
            <link>https://harshsharma1091996.medium.com/twitter-microblogging-system-design-1a940b0b5957?source=rss-5e53c86ec9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a940b0b5957</guid>
            <category><![CDATA[twitte]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[microblogging]]></category>
            <category><![CDATA[system-design-project]]></category>
            <category><![CDATA[database-administration]]></category>
            <dc:creator><![CDATA[Himanshu Sharma]]></dc:creator>
            <pubDate>Sun, 04 Jul 2021 09:06:18 GMT</pubDate>
            <atom:updated>2021-07-04T09:23:29.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*-jjt7MnmMvQJMjOj" /></figure><p>Today, we’re sharing this article that will shed light on how Twitter technology works and how it impacts people&#39;s experiences across the app. This article tries to answer questions like “What is Microblogging?”; ”How twitters get all the tweets for a particular user?”; ” How Twitter gets the data for the home timeline?”; ”How to calculate and display trends? ”; “How search timeline works?”</p><p><strong>What is Microblogging ??</strong></p><p>Microblogging is a combination of blogging and instant messaging that allows users to create short messages to be posted and shared with an audience online. Social platforms like Twitter have become extremely popular forms of this new type of blogging, especially on the mobile web , making it much more convenient to communicate with people than when desktop web browsing and interaction were the norms.</p><p>Twitter is one of the oldest and most well-known social platforms to be put under the “microblogging” category. While the 280-character limit still exists today, you can now also share videos, articles links, photos, <a href="https://www.lifewire.com/gif-file-4116104">GIFs</a>, sound clips, and more through Twitter Cards in addition to regular text.</p><h3>The Benefits of Microblogging Versus Traditional Blogging</h3><ul><li>Less time spent developing content.</li><li>Less time spent consuming individual pieces of content.</li><li>The opportunity for more frequent posts.</li><li>An easier way to share urgent or time-sensitive information.</li><li>An easier, more direct way to communicate with followers.</li><li>Mobile convenience.</li></ul><p><strong>Twitter</strong> is an American microblogging and social networking service on which users post and interact with messages known as “tweets”. Registered users can post, like, and retweet tweets, but unregistered users can only read them. Users access Twitter through its website interface or its mobile-device application software (“app”), though the service could also be accessed via SMS before April 2020. Tweets were originally restricted to 140 characters, but the limit was doubled to 280 for non-CJK languages in November 2017. Audio and video tweets remain limited to 140 seconds for most accounts.</p><blockquote>Traffic: Every second, on average, around 6,000 tweets are tweeted on Twitter, which corresponds to over 350,000 tweets sent per minute, <strong>500 million tweets per day,</strong> and around 200 billion tweets per year.</blockquote><p><strong>User Features?</strong></p><ul><li>The user should be able to tweet as fast as possible</li><li>The user should be able to see Tweet Timeline(s)</li><li>User timeline: Displaying user’s tweets and tweets user retweet</li><li>Home timeline: Displaying Tweets from people users follow</li><li>Search timeline: Display search results based on #tags or search keyword</li><li>The user should be able to follow another user</li><li>Users should be able to tweet millions of followers within a few seconds (5 seconds)</li><li>The user should see trends</li></ul><p><strong>Considerations before designing Twitter</strong></p><ul><li>If you see all of the features, it looks read-heavy, compared to write</li><li>It&#39;s ok to have Eventual consistency, It’s not much of a pain if the user sees the tweet of his follower a bit delayed</li><li>Space is not a problem as tweets are limited to 280 characters</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xWHMUHHVSBx8sU28.png" /><figcaption>Twitter System Design</figcaption></figure><h3>How to get all the tweets for a particular user?</h3><p>As we know Twitter is read-heavy, we need a system that loads the data faster. For this, we can use Redis to store the tweets which store data faster and scales horizontally to enhance the read rate, along with Redis we have to store data in the database since Redis is persistent.</p><p>The basic Architecture of the Twitter service consists of a User Table, Tweet Table, and Followers Table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/0*Pbe0daPN3IvE3mfx" /></figure><p>user_id -&gt; user_tweets [1, 2, 3, …]</p><p>Tweet_id -&gt; tweet “Hello world”</p><p>user_id -&gt; followers [1, 2, 3, …]</p><ul><li>Here first we search for the user_id with the help of username and get all the ID of the tweets.</li><li>Then we go to the tweet_id table to get all the actual tweets mapping to that user.</li><li>When a user follows another user, it gets stored in the follower table, and also cache it Redis.</li></ul><p>Then with the help of additional metadata like “created_time” we can chronologically sort the data.</p><h3>How to build a USER TIMELINE?</h3><ul><li>Fetch all the tweets from the Global Tweet Table/Redis for a particular user</li><li>Which also includes retweets, save retweets as tweets with original tweet reference</li><li>Display it on user timeline, order by date-time</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*dRt5yD5nql4KSXRL" /></figure><p>user_id -&gt; user_tweets [1, 2, 3, …]</p><p>Tweet_id -&gt; tweet “Hello world”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*NsvHHHBavEp8k76R" /><figcaption>User Timeline</figcaption></figure><h3>How to get the data for the Home Timeline?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*THmkdnPCTOodWZEW" /><figcaption>Home timeline</figcaption></figure><p>The home timeline will have all the tweets where the person is following.</p><ul><li>First, get all the followers the user is following</li><li>For each follower get all the latest tweets</li><li>Merge all the tweets and show the tweets sorted by time</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/0*ce-uJQT3JF3VbTv9" /></figure><h3>Is this scalable?</h3><p>This huge search operation on relational DB is not Scalable. Though we can use sharding etc, this huge search operation will take time once the tweet table grows to millions. Therefore we have to come up with a new solution, this approach would be the Fanout approach.</p><p>Suppose if a user is followed by 10 people. The fanout approach works as below:</p><p>1. When a specific user tweets, then first store the tweet in the DB.</p><p>2. Then store the same tweet in the user timeline.</p><p>3. Then fan out the user tweet to all of his followers. Thus the follower home timeline will be having the person’s tweet.</p><p>This approach has a problem. Consider a user is a celebrity and has been followed by millions of users, we cannot possibly update all of the followers’ timeline, it will take time. So what we do is, we maintain another table associated with every user called “celebrity_table”. This table will update every time a user has followed a celebrity. So when the user login to twitter, he will get tweets as generated in the previous step, then Redis checks if he follows any celebrity, if he follows, Redis will get the tweet from the celebrity and display it in this home timeline.</p><p><strong>What are the other optimizations we can make?</strong></p><p>Don’t compute the timeline for inactive users who don’t log in to the system for more than 15 days.</p><h3><strong>How are trending topics calculated?</strong></h3><p>Twitter uses Apache Storm and Heron framework to compute trending topics</p><p>These tasks run on many containers, These applications create a real-time analysis of all tweets sent on the Twitter social network which can be used to determine the so-called trending topics.</p><p>Basically, method implies the counting of the most mentioned terms in the poster tweets in the Twitter social network.</p><p>The method is known in the domain of data analysis for the social network as the “Trending Hashtags” method. Suppose two subjects A and B, the fact that A is more popular than B is equivalent to the fact that the number of mentions of the subject A is greater than the number of mentions of the subject B.</p><p>The information required for this process are -:</p><ol><li>Number of mentions in a subject (hashtag)</li><li>The total amount of time taken to generate the volume of tweets.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pgV2V9f3Y-DN1csg" /></figure><ul><li>TweetSpout: Represents a component used for issuing the tweets in the topology</li><li>TweetFilterBolt: Reads the tweets issued by the TweetSpout and executes the filtering. Only tweets that contain coded messages using the standard Unicode. also, violation and CC checks are made.</li><li>ParseTweetBolt: Processes the filtered tweets issued as tuples by the component TweetFilterBolt. Taking into consideration that the tuple is filtered, at this level we have the guarantee that each tweet contains at least one hashtag</li><li>CountHashtagBolt: Takes the tweets that are parsed through the component ParseTweetBolt and counts each hashtag. This is to get the hashtag and number of references to it</li><li>TotalRankerBolt: Makes a total ranking of all the counted hashtags. It converts count to ranks in one or more pipelines.</li><li>GeoLocationBolt: It takes the hashtag issued by the ParseTweetBolt, with the location of the tweet.</li><li>CountLocationHashtagBolt: Presents a functionality similar to the component CountHashtagBolt uses one more dimension ie. Location</li><li>RedisBolt: inserts into Redis</li></ul><h3><strong>Searching:</strong></h3><p>Early Bird uses an inverted full-text index. This means that it takes all the documents, splits them into words, and then builds an index for each word. Since the index is an exact string-match, unordered, it can be extremely fast. Hypothetically, an SQL unordered index on a varchar field could be just as fast, and in fact, I think you’ll find the big databases can do a simple string-equality query very quickly in that case.</p><p>Lucene does not have to optimize for transaction processing. When you add a document, it need not ensure that queries see it instantly. And it need not optimize for updates to existing documents.</p><p>However, at the end of the day, if you really want to know, you need to read the source. Both things you reference are open source, after all.</p><p>It has to scatter-gather across the data center. It queries every Early Bird shard and asks do you have content that matches this query? If you ask for “New York Times” all shards are queried, the results are returned, sorted, merged, and reranked. Rerank is by social proof, which means looking at the number of retweets, favorites, and replies.</p><h3><strong>Databases:</strong></h3><ul><li>Gizzard is Twitter’s distributed data storage framework built on top of MySQL (InnoDB). InnoDB was chosen because it doesn’t corrupt data. Gizzard us just a datastore. Data is fed in and you get it back out again. To get higher performance on individual nodes a lot of features like binary logs and replication are turned off. Gizzard handles sharding, replicating N copies of the data, and job scheduling.</li><li>Cassandra is used for high velocity writes, and lower velocity reads. The advantage is Cassandra can run on cheaper hardware than MySQL, it can expand easier, and they like schemaless design.</li><li>Hadoop is used to process unstructured and large datasets, hundreds of billions of rows.</li><li>Vertica is being used for analytics and large aggregations and joins so they don’t have to write MapReduce jobs.</li></ul><p>That’s it for this article and we believe this article helps you to learn about how Twitter works, if not completely at least a bit.</p><p>It feels good to operate with a team that is so self-reliant and motivated. I would like to thanks <a href="https://medium.com/u/43a49c7f84f3">Apoorva</a> and <a href="https://medium.com/u/e19c931ca010">Shubham Kumar</a> for their invaluable contribution to this article .</p><p><strong>Happy Learning!!</strong></p><h3><strong>References:</strong></h3><ol><li>Article: <a href="http://blog.gainlo.co/index.php/2016/02/17/system-design-interview-question-how-to-design-twitter-part-1/">http://blog.gainlo.co/index.php/2016/02/17/system-design-interview-question-how-to-design-twitter-part-1/</a></li><li>Twitter news: <a href="https://twitter.com/twitternews?lang=en">https://twitter.com/twitternews?lang=en</a></li><li>Article: <a href="http://blog.gainlo.co/index.php/2016/02/24/system-design-interview-question-how-to-design-twitter-part-2/">http://blog.gainlo.co/index.php/2016/02/24/system-design-interview-question-how-to-design-twitter-part-2/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a940b0b5957" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XGBoost- The Miracle Worker]]></title>
            <link>https://medium.com/almabetter/xgboost-the-miracle-worker-7518dd55abf3?source=rss-5e53c86ec9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/7518dd55abf3</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[boosting]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Himanshu Sharma]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 13:34:18 GMT</pubDate>
            <atom:updated>2021-06-06T17:03:56.350Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is XGBoost?</h3><p>Its name stands for <strong>eXtreme Gradient Boosting, </strong><a href="https://xgboost.ai/">XGBoost</a><strong> </strong>is a decision-tree-based ensemble Machine Learning algorithm that uses a <a href="https://en.wikipedia.org/wiki/Gradient_boosting">gradient boosting</a> framework. In prediction problems involving unstructured data (images, text, etc.) artificial neural networks tend to outperform all other algorithms or frameworks. However, when it comes to small-to-medium structured/tabular data, decision tree-based algorithms are considered best-in-class right now. Please see the chart below for the evolution of tree-based algorithms over the years.</p><p><strong>Evolution of XGBoost</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*m0hnufny3nCxuWUW.jpeg" /><figcaption>Evolution of XGBoost Algorithm from Decision Trees</figcaption></figure><h4><strong>Applications of XGBoost:</strong></h4><p>A wide range of applications: Can be used to solve regression, classification, ranking, and user-defined prediction problems.</p><h3>How to build an intuition for XGBoost?</h3><p>Decision trees, in their simplest form, are easy-to-visualize and fairly interpretable algorithms but building intuition for the next generation of tree-based algorithms can be a bit tricky. See below to better understand the evolution of tree-based algorithms.</p><p><strong>Decision Tree</strong>: Decision Trees are the foundation for many classical machine learning algorithms like Random Forests, Bagging, and Boosted Decision Trees. The idea behind the Decision Tree is to represent data as a tree where each internal node denotes a test on an attribute (basically a condition), each branch represents an outcome of the test, and each leaf node (terminal node) holds a class label. Decision trees are now widely used in many applications for predictive modeling, including both classification and regression. Sometimes decision trees are also referred to as CART, which is short for Classification and Regression Trees.</p><p><strong>Bagging</strong>: Bagging is an ensemble technique used to reduce the variance of our predictions by combining the result of multiple classifiers modeled on different sub-samples of the same data set. The following figure will make it clearer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/0*adq4Q1E_8Zmg3Njr.png" /><figcaption>Bagging approach</figcaption></figure><p><strong>Random Forest</strong>: In Random Forest, we grow multiple trees as opposed to a single tree in CART model.</p><ul><li>We construct trees from the subsets of the original dataset. These subsets can have a fraction of the columns as well as rows.</li><li>To classify a new object based on attributes, each tree gives a classification and we say that the tree “votes” for that class.</li><li>The forest chooses the classification having the most votes (over all the trees in the forest) and in case of regression, it takes the average of outputs by different trees.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*TEbTKQ8rWw0LaIMb" /></figure><p><strong>Boosting</strong>: Boosting fit a sequence of weak learners − models that are only slightly better than random guessings, such as small decision trees − to weighted versions of the data. More weight is given to examples that were misclassified by earlier rounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*ZwbKhT4bIvRfBFVMM2h4Rg.png" /><figcaption>Boosting approach</figcaption></figure><p><strong>Gradient Boosting</strong>: A special case of boosting where errors are minimized by gradient descent algorithm.</p><p><strong>XGBoost</strong>: Think of XGBoost as gradient boosting on ‘steroids’ (well it is called ‘Extreme Gradient Boosting’ for a reason!). It is a perfect combination of software and hardware optimization techniques to yield superior results using fewer computing resources in the shortest amount of time.</p><h3>Why does XGBoost perform so well?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*SRxEuIvKiU8GiXAe.png" /><figcaption>XGBoost</figcaption></figure><p>Because gradient boosting (GB) methods are powerful classifiers/regressors that typically perform very well on structured data, and the <a href="https://xgboost.readthedocs.io/en/latest/">XGBoost</a> library is an excellent implementation of this algorithm. It’s certainly not the only high-performance boosting library out there (others include <a href="https://lightgbm.readthedocs.io/en/latest/">LightGBM</a> and <a href="https://catboost.ai/">CatBoost</a>), but it’s one of the best and easiest to use.</p><p>More generally, XGBoost tends to work well for the following reasons:</p><ul><li>It is easy to implement. In general, XGBoost is considered to be one of the best out-of-the-box ML algorithms, since it typically performs quite well even with minimal tuning.</li><li>It is <strong>fast</strong>. Modern libraries like XGBoost come equipped with several speed enhancements, making it possible to train a well-performing model in a short amount of time. XGBoost and similar libraries can also be trained on GPUs (some assembly required), making training even faster on larger datasets.</li><li>It is an <a href="https://en.wikipedia.org/wiki/Ensemble_learning">ensemble learning</a> algorithm, which combines the predictions of multiple base learners (usually, each one being a fairly weak performer on its own) to generate one overall prediction for each input/example. This allows it to learn more complex relationships between the features and targets/labels in the training set.</li><li>It is almost always implemented using binary decision trees as base learners, which themselves are highly skilled at learning non-parametric and nonlinear relationships between features and targets.</li><li>It learns in a sequential fashion. In each iteration, it fits a new base learner designed to correct the errors of the previous sequence of learners. As such, the final ensemble sequence can achieve (nearly) arbitrarily good performance on the training set. This of course makes XGBoost susceptible to overfitting, but this is easily mitigated through proper tuning of a small handful of hyper-parameters (learning rate, number of base learners, depth of decision trees, etc).</li><li>It comes equipped with several performance tuning hyper-parameters (some vary by the library), making it a highly versatile learner. This can be a bit overwhelming at first, and it makes the search for a good set of parameters more difficult. But often, one can achieve good performance by tuning just the learning rate, number, and depth of decision trees, early stopping criteria, and L1 or L2 regularization; and leaving other parameters at their default settings.</li></ul><h3>Where is the proof?</h3><p>We Implemented a project on <a href="https://github.com/Harsh1091996/Email_Campaign_Effectiveness_Prediction">Email Campaign Effectiveness Prediction</a> where we tested several algorithms such as Decision Tree, Random Forest, KNN, and XGBoost.Where XGBoost outperformed every algorithm.</p><p>XGBoost model has the best combination of prediction performance and processing time compared to other algorithms. Other rigorous <a href="https://github.com/szilard/benchm-ml">benchmarking</a> studies have produced similar results. No wonder XGBoost is widely used in recent Data Science competitions.</p><blockquote><em>“When in doubt, use XGBoost” — Owen Zhang, Winner of </em><a href="http://blog.kaggle.com/2015/08/26/avito-winners-interview-1st-place-owen-zhang/"><em>Avito</em></a><em> Context Ad Click Prediction competition on Kaggle</em></blockquote><h3>So should we use just XGBoost all the time?</h3><p>When it comes to Machine Learning (or even life for that matter), there is no free lunch. As Data Scientists, we must test all possible algorithms for data at hand to identify the champion algorithm. Besides, picking the right algorithm is not enough. We must also choose the right configuration of the algorithm for a dataset by tuning the <a href="https://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/">hyper-parameters</a>. Furthermore, there are several other considerations for choosing the winning algorithm such as computational complexity, explainability, and ease of implementation. This is exactly the point where Machine Learning starts drifting away from science towards art, but honestly, that’s where the magic happens!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7518dd55abf3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/xgboost-the-miracle-worker-7518dd55abf3">XGBoost- The Miracle Worker</a> was originally published in <a href="https://medium.com/almabetter">AlmaBetter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing(NLP)]]></title>
            <link>https://medium.com/almabetter/natural-language-processing-nlp-36d2c1a9de02?source=rss-5e53c86ec9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/36d2c1a9de02</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[stemming]]></category>
            <category><![CDATA[count-vectorizer]]></category>
            <category><![CDATA[tf-idf-explained]]></category>
            <category><![CDATA[lemmatization]]></category>
            <dc:creator><![CDATA[Himanshu Sharma]]></dc:creator>
            <pubDate>Wed, 28 Apr 2021 09:58:06 GMT</pubDate>
            <atom:updated>2021-05-02T16:13:47.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GF3j2gi0Zbx0F8F-.png" /><figcaption>Natural Language Processing</figcaption></figure><p>Natural Language Processing (NLP), is a subfield of artificial intelligence (AI). It helps machines process and understand the human language in any given context so that they can automatically perform repetitive tasks such as machine translation, summarization, ticket classification, and more.</p><p>Take <a href="https://monkeylearn.com/sentiment-analysis/">sentiment analysis</a>, for example, which uses natural language processing to detect emotions in text. This classification task is one of the most basic challenges of NLP and often used by businesses to automatically <a href="https://monkeylearn.com/blog/brand-sentiment/">detect brand sentiment on social media</a>.</p><p>And another popular application of NLP is <strong>Topic modelling</strong> which can be described as a method for finding a group of words (i.e <strong>topic</strong>) from a collection of documents that best represents the information in the collection. It can also be thought of as a form of text mining — a way to obtain recurring patterns of words in textual material.</p><p>Since the Machine understand only numeric data so the main task of NLP is to convert the textual data to meaningful numeric data.</p><p>Lets take an example of book reviews given to us. Our job is to convert that into numerical data. how we can achieve this?</p><p>Lets create some reviews-:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*7aBtNKj_lPidXHyAbN-9fA.png" /><figcaption>Reviews of a book</figcaption></figure><h3><strong>Step 1: Data Cleaning:</strong></h3><p>First we have to convert our data to lower case then we have to remove all the stopwords and punctuation . <strong>Stopwords</strong> are the most common <strong>words</strong> in any natural language. For the purpose of analyzing text data and building <strong>NLP</strong> models, these <strong>stopwords</strong> might not add much value to the meaning of the document. Generally, the most common <strong>words</strong> used in a text are “the”, “is”, “in”, “for”, “where”, “when”, “to”, “at” etc. We can use<strong> nltk</strong> library for getting the list of all stop words . After removing all the stop words our updated data will be-:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*UvZqD7-vvDgrnlKf8_HGcQ.png" /><figcaption>After removing stop words</figcaption></figure><h3><strong>Step 2: Converting textual data to numeric:</strong></h3><p>There are different techniques to do this task. we will be discussing most commonly used techniques.</p><blockquote><strong>a.) One-Hot Encoding:</strong></blockquote><p>It basically marks the presence and absence of a word by 1’s and 0’s respectively. So how it actually does that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*rBsSDYosA2_vk8WVFt-YqA.png" /><figcaption>One-Hot Encoding</figcaption></figure><p>As you can see in above image, for first review i.e awesome book all other features (i.e words) are marked as 0’s except awesome and book. so this is how we can use one hot encoding to convert our textual data to numeric.</p><p>But there are some cons of One-Hot Encoding -:</p><ol><li>If you have too many unique words in your dataset then the matrix will be so huge .</li><li>It is unable to track how many times a word is occurring because it just marks the presence and absence of a word not the frequency of it.</li></ol><p><strong>How to reduce number of features (i.e words):</strong></p><ol><li><strong>Stemming: </strong>It<strong> </strong>just removes or stems the last few characters of a word, often leading to incorrect meanings and spelling.</li><li><strong>Lemmatization: </strong>It<strong> </strong>considers the context and converts the word to its meaningful base form, which is called Lemma. Sometimes, the same word can have multiple different Lemmas. We should identify the Part of Speech (POS) tag for the word in that specific context.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*xiJK9B0-4_xJb7Q_9IO9Gg.png" /></figure><p>Here are the examples to illustrate all the differences and use cases:</p><p>A. If you lemmatize the word ‘<strong>Caring</strong>’, it would return ‘<strong>Care</strong>’. If you stem, it would return ‘<strong>Car</strong>’ and this is erroneous.</p><p>B. If you lemmatize the word ‘<strong>Stripes</strong>’ in <strong>verb</strong> context, it would return ‘<strong>Strip</strong>’. If you lemmatize it in <strong>noun</strong> context, it would return ‘<strong>Stripe</strong>’. If you just stem it, it would just return ‘<strong>Strip</strong>’.</p><p>C. You would get same results whether you lemmatize or stem words such as <strong>walking, running, swimming</strong>… to <strong>walk, run, swim</strong> etc.</p><p>D. Lemmatization is computationally expensive since it involves look-up tables and what not. If you have large dataset and performance is an issue, go with Stemming. Remember you can also add your own rules to Stemming. If accuracy is paramount and dataset isn’t humongous, go with Lemmatization.</p><p>But if we have very huge data so even after performing Lemmatization or Stemming we won’t be able to reduce the number of features.</p><blockquote><strong>b.) Bag of words or CountVectorizer:</strong></blockquote><p>It is used to transform a given text into a vector on the basis of the frequency (count) of each word that occurs in the entire text. This is helpful when we have multiple such texts, and we wish to convert each word in each text into vectors (for using in further text analysis).</p><p>CountVectorizer creates a matrix in which each unique word is represented by a column of the matrix, and each text sample from the document is a row in the matrix. The value of each cell is nothing but the count of the word in that particular text sample.</p><p>Lets consider our data of book review and apply CountVectorizer, This can be visualized as follows –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*2ABQ8yBN7cYPumkoyssaUQ.png" /></figure><p>Added the last review to get the context of countvectorizer.</p><p>Inside CountVectorizer, these words are not stored as strings. Rather, they are given a particular index value. In this case, ‘awesome’ would have index 0, ‘book’ would have index 1, ‘great’ would have index 2 and so on. The actual representation has been shown in the table below –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*EWIe1BvmTPYQWAQJV5eKmw.png" /></figure><p>So CountVectorizer actually solves one of the limitation of one-hot encoding i.e not able to track how many times a word is occurring.</p><blockquote><strong>c.) TF-IDF</strong> :</blockquote><p>It stands for Term Frequency Inverse Document Frequency of records. It can be defined as the calculation of how relevant a word in a series or corpus is to a text. The meaning increases proportionally to the number of times in the text a word appears but is compensated by the word frequency in the corpus (data-set).</p><ul><li><strong>Term Frequency: </strong>In document d, the frequency represents the number of instances of a given word t. Therefore, we can see that it becomes more relevant when a word appears in the text, which is rational. Since the ordering of terms is not significant, we can use a vector to describe the text in the bag of term models. For each specific term in the paper, there is an entry with the value being the term frequency.</li></ul><p>The weight of a term that occurs in a document is simply proportional to the term frequency.</p><pre>tf(t,d) = count of t in d / number of words in d</pre><ul><li><strong>Document Frequency: </strong>This tests the meaning of the text, which is very similar to TF, in the whole corpus collection. The only difference is that in document d, TF is the frequency counter for a term t, while df is the number of occurrences in the document set N of the term t. In other words, the number of papers in which the word is present is DF.</li></ul><pre>df(t) = occurrence of t in documents</pre><ul><li><strong>Inverse Document Frequency: </strong>Mainly, it tests how relevant the word is. The key aim of the search is to locate the appropriate records that fit the demand. Since tf considers all terms equally significant, it is therefore not only possible to use the term frequencies to measure the weight of the term in the paper. First, find the document frequency of a term t by counting the number of documents containing the term:</li></ul><pre>df(t) = N(t)<br>where<br>df(t) = Document frequency of a term t<br>N(t) = Number of documents containing the term t</pre><p>Term frequency is the number of instances of a term in a single document only; although the frequency of the document is the number of separate documents in which the term appears, it depends on the entire corpus. Now let’s look at the definition of the frequency of the inverse paper. The IDF of the word is the number of documents in the corpus separated by the frequency of the text.</p><pre>idf(t) = N/ df(t) = N/N(t)</pre><p>The more common word is supposed to be considered less significant, but the element (most definite integers) seems too harsh. We then take the logarithm (with base 2) of the inverse frequency of the paper. So the if of the term t becomes:</p><pre>idf(t) = log(N/ df(t))</pre><p>As per our requirement we can use any of the techniques of converting textual data to numeric data because each technique serves different purpose such as TF_IDF balances out the term frequency (how often the word appears in the document) with its inverse document frequency (how often the term appears across all documents in the data set). This means that words like “a” and “the” will have very low scores as they’ll appear in all documents in your set. Rarer words like for instance “machine learning” will be very common in just a handful of documents which talk about computer science or AI. TF-IDF will give higher scores to these words and thus they’ll be the ones that the model identifies as important and tries to learn.</p><p>Enjoy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36d2c1a9de02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/natural-language-processing-nlp-36d2c1a9de02">Natural Language Processing(NLP)</a> was originally published in <a href="https://medium.com/almabetter">AlmaBetter</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hierarchical Clustering]]></title>
            <link>https://harshsharma1091996.medium.com/hierarchical-clustering-996745fe656b?source=rss-5e53c86ec9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/996745fe656b</guid>
            <category><![CDATA[agglomerative-clustering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[hierarchical-clustering]]></category>
            <dc:creator><![CDATA[Himanshu Sharma]]></dc:creator>
            <pubDate>Fri, 23 Apr 2021 16:19:04 GMT</pubDate>
            <atom:updated>2021-04-23T16:19:04.976Z</atom:updated>
            <content:encoded><![CDATA[<p>Hierarchical Clustering groups (Agglomerative or also called as Bottom-Up Approach) or divides (Divisive or also called as Top-Down Approach) the clusters based on the distance metrics. In Agglomerative clustering, each data point acts as a cluster initially, and then it groups the clusters one by one.</p><p>Divisive is the opposite of Agglomerative, it starts off with all the points into one cluster and divides them to create more clusters. These algorithms create a distance matrix of all the existing clusters and perform the linkage between the clusters depending on the criteria of the linkage. The clustering of the data points is represented by using a dendrogram. There are different types of linkages: –</p><p>o Single Linkage: — In single linkage the distance between the two clusters is the shortest distance between points in those two clusters.</p><p>o Complete Linkage: — In complete linkage, the distance between the two clusters is the farthest distance between points in those two clusters.</p><p>o Average Linkage: — In average linkage the distance between the two clusters is the average distance of every point in the cluster with every point in another cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*afzanWwrDq9vd2g-" /></figure><p>Both this algorithm are exactly reverse of each other. So we will be covering Agglomerative Hierarchical clustering algorithm in detail.</p><h3>How Agglomerative Hierarchical clustering Algorithm Works</h3><p>For a set of N observations to be clustered:</p><ol><li>Start assigning each observation as a single point cluster, so that if we have N observations, we have N clusters, each containing just one observation.</li><li>Find the closest (most similar) pair of clusters and make them into one cluster, we now have N-1 clusters.<strong> This can be done in various ways to identify similar and dissimilar measures.</strong></li><li>Find the two closest clusters and make them to one cluster. We now have N-2 clusters. <strong>This can be done using agglomerative clustering linkage techniques</strong></li><li>Repeat steps 2 and 3 until all observations are clustered into one single cluster of size N.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/0*Kij7x4WH00OFGFs_" /></figure><p>Clustering algorithms use various distance or dissimilarity measures to develop different clusters. Lower/closer distance indicates that data or observation are similar and would get grouped in a single cluster. Remember that the higher the similarity depicts observation is similar.</p><p><strong>Step 2</strong> can be done in various ways to identify similar and dissimilar measures. Namely,</p><ul><li>Euclidean Distance</li><li>Manhattan Distance</li><li>Minkowski Distance</li><li>Jaccard Similarity Coefficient</li><li>Cosine Similarity</li><li>Gower’s Similarity Coefficient</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=996745fe656b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross Validation and Hyperparameter Tuning]]></title>
            <link>https://harshsharma1091996.medium.com/cross-validation-and-hyperparameter-tuning-90e4701d228a?source=rss-5e53c86ec9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/90e4701d228a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[gridsearchcv]]></category>
            <category><![CDATA[crossvalidation]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <dc:creator><![CDATA[Himanshu Sharma]]></dc:creator>
            <pubDate>Thu, 08 Apr 2021 13:24:03 GMT</pubDate>
            <atom:updated>2021-04-08T13:24:03.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2yCt60L9c9VjoX6b.jpeg" /></figure><p>Hello everyone! In this blog post, I want to focus on the importance of cross validation and hyperparameter tuning. I will give a short overview of the topic.</p><p>Cross validation is a technique used to identify how well our model performed and there is always a need to test the accuracy of our model to verify that, our model is well trained with data without any overfitting and underfitting. This process of validation is performed only after training the model with data.</p><p>First, let us understand the terms overfitting and underfitting.</p><p>while using statistical methods (like logistic regression, linear regression etc…) on our data, generally we split our data into training and testing samples and fit the model on training samples and make predictions on test samples. Now, there is a possibility of overfitting or underfitting the data.</p><p><strong>Overfitting</strong></p><p>In statistics, <strong>overfitting</strong> means our model fits too closely to our data. The fitted line will go exactly through every point in the graph and this may fail to make predictions on future data reliably.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*c2LiBlLl23JT_IJ1" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*82m_V5ZUS68GLQiF.png" /></figure><p>To lessen the chance of, or amount of, overfitting, several techniques are available (e.g. <a href="https://en.wikipedia.org/wiki/Model_selection">model comparison</a>, <a href="https://en.wikipedia.org/wiki/Cross-validation_(statistics)">cross-validation</a>, <a href="https://en.wikipedia.org/wiki/Regularization_(mathematics)">regularization</a>, <a href="https://en.wikipedia.org/wiki/Early_stopping">early stopping</a>, <a href="https://en.wikipedia.org/wiki/Pruning_(algorithm)">pruning</a>, <a href="https://en.wikipedia.org/wiki/Prior_distribution">Bayesian priors</a>, or <a href="https://en.wikipedia.org/wiki/Dropout_(neural_networks)">dropout</a>)</p><p><strong>Underfitting</strong></p><p>Underfitting means our model doesn’t fit well with the data(i.e, model cannot capture the underlying trend of data, which destroys the model accuracy)and occurs when a statistical model or machine learning algorithm cannot adequately capture the underlying structure of the data.</p><h3>K-fold Cross Validation</h3><p>Our dataset should be as large as possible to train the model and removing considerable part of it for validation poses a problem of losing valuable portion of data that we would prefer to be able to train. In order to address this issue, we use the K-fold Cross validation technique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*s5LB2IJ_MYHbEy8T.png" /></figure><p>In <strong>K Fold cross validation</strong>, the data is divided into k subsets and train our model on k-1 subsets and hold the last one for test. This process is repeated k times, such that <strong><em>each time, one of the k subsets is used as the test set/ validation set and the other k-1 subsets are put together to form a training set</em></strong>. We then average the model against each of the folds and then finalize our model. After that we test it against the test set.</p><p>The more the number of folds, less is value of error due to bias but increasing the error due to variance will increase; the more folds you have, the longer it would take to compute it and you would need more memory. With a lower number of folds, we’re reducing the error due to variance, but the error due to bias would be bigger. It would also computationally cheaper. Therefore, in big datasets, k=3 is usually advised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*snRhsVQJsQDulx8o.png" /></figure><p><strong>Hyperparameter Tuning</strong></p><p>Hyperparameters are hugely important in getting good performance with models. In order to understand this process, we first need to understand the difference between a model parameter and a model hyperparameter.</p><p>Model parameters are internal to the model whose values can be estimated from the data and we are often trying to estimate them as best as possible . whereas hyperparameters are external to our model and cannot be directly learned from the regular training process. These parameters express “higher-level” properties of the model such as its complexity or how fast it should learn. Hyperparameters are model-specific properties that are ‘fixed’ before you even train and test your model on data.</p><p>The process for finding the right hyperparameters is still somewhat of a dark art, and it currently involves either <em>random search</em> or <em>grid search</em> across Cartesian products of sets of hyperparameters.</p><p>There are bunch of methods available for tuning of hyperparameters. In this blog post, I chose to demonstrate using grid search .</p><p><strong>Grid Search</strong></p><p>GridSearch takes a dictionary of all of the different hyperparameters that you want to test, and then feeds all of the different combinations through the algorithm for you and then reports back to you which one had the highest accuracy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90e4701d228a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression and Regularized Linear Regression]]></title>
            <link>https://harshsharma1091996.medium.com/linear-regression-and-regularized-linear-regression-977056f29209?source=rss-5e53c86ec9df------2</link>
            <guid isPermaLink="false">https://medium.com/p/977056f29209</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[lasso-regression]]></category>
            <category><![CDATA[regularization]]></category>
            <dc:creator><![CDATA[Himanshu Sharma]]></dc:creator>
            <pubDate>Wed, 07 Apr 2021 05:07:25 GMT</pubDate>
            <atom:updated>2021-04-07T05:07:25.251Z</atom:updated>
            <content:encoded><![CDATA[<p>Linear regression is generally the first step into anyone’s Data Science journey. When you hear the words Linear and Regression, something like this pops up in your mind:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/0*vi2ewYr1UStsHUq3" /></figure><p><strong>X1, X2, ..Xn</strong> are the independent variables or features. <strong>W1, W2…Wn</strong> are the weights (learned by the model from the data). <strong>Y’</strong> is the model prediction. For a set of say 1000 points, we have a table with 1000 rows, n columns for X and 1 column for Y. Our model learns the weights W from these 1000 points so that it can predict the dependent variable Y for an unseen point (a point for which Xs are available but not Y)</p><p>For these seen points (1000 in this case), the actual value of the dependent variable (Y) and the model’s prediction of the dependent variable (denoted by Y’) are related as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/0*R4WhiqxNzgiHSbP7" /></figure><p>Epsilon (denoted by <em>e </em>henceforth) is the residual error. It captures the difference between models prediction and the actual value of Y. One thing to remember about e is that it follows a normal distribution with 0 mean.</p><p>The weights are learned using OLS or Ordinary Least Squared fitting. Meaning, The cumulative squared error, defined as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/0*JzkmJPrMQCGQ2rHW" /></figure><p>Is minimized. Why do we square the errors and then add? Two reasons.</p><ol><li>If the residual error for a point is -1 and for the other, it is 1 then merely adding them gives 0 error which means the line fits perfectly to the points. This is not true.</li><li>Squaring leads to more importance given to larger errors and less to smaller errors. Intuitively, model weights quickly update to minimize larger errors more than smaller ones.</li></ol><p>Quite often, in the excitement of learning new and advanced models, we usually do not fully explore this model. In this blog, we’ll look at how to analyze and diagnose a linear regression model. This blog is going to be as intuitive as possible. Let’s talk about the model. There are three main assumptions linear regression makes:</p><ol><li>The independent variables have a linear relationship with the dependent variable.</li><li>The variance of the dependent variable is uniform across all combinations of Xs</li><li>The error term e associated with Y and Y’ is independent and identically distributed.</li></ol><p>Do not worry if you don’t correctly understand the above lines. I am yet to simplify them.</p><h3>Linear Relationship</h3><p>Seems quite intuitive. If the independent variables do not have a linear relationship with the dependent variables, there’s no point modeling them using LINEAR regression. So what should one do if that is not the case? Consider a dataset with one independent variable X and dependent variable Y. In this case, Y varies as the square of X (some random noise is added to Y to make it look more realistic).</p><p>If we fit and plot a linear regression line, we can see that it isn’t a good fit. The <strong>MSE (mean squared error) is 0.0102</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/0*3sVFK9M_ATs1M19J" /></figure><p>So what we do here is we transform X such that Y and this transformed X follows a linear relationship. Take a look at the picture below. Y and X might not have a linear relation. However, Y and X² do have a linear relation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/0*Uu-DCutagb5yFBRV" /></figure><p>Next, we build the model, generate the predictions and reverse transform it. Take a look at the code and the plots below to get an idea. <strong>The MSE here is 0.0053 (almost half the previous one)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*XX4soKTLlDyvD4fF" /></figure><p>Isn’t is evident which one fits better. I hope it is a bit more clear why linear relationships are needed. Let’s move on to the next assumption.</p><h3>The variance of the dependent variable is uniform across all combinations of Xs</h3><p>Formally speaking, we need something called <strong>homoscedasticity. </strong>In simple terms, it means that the residuals must have constant variance. Let’s visualize this. Later I’ll explain why it is essential.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*kVn-XmdNqg9VUEQg" /></figure><p>If you notice carefully, the variance among the Y values increases from left to right like a trumpet. Meaning the Y values for lower X values do not vary much concerning the regression line, unlike the ones to the right. We call it <strong>heteroscedasticity</strong> and is something you want to avoid. Why? Well, if there is a pattern among the residuals, like this one (for the above plot)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/0*Bc9MWtb4H4IiJe4G" /></figure><p>It generally means that the model is too simple for the data. The model is unable to capture all the patterns present in the data. When we achieve homoscedasticity, residuals look something like this. Another reason to avoid heteroscedasticity is to save us from unbias results in significance tests. We’ll look at these tests in details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/0*VFlPJnkjA__W-aQU" /></figure><p>As you can see, the residuals are entirely random. One can hardly see any pattern. Now comes the last and the final assumption.</p><h3>The error term e associated with Y and Y’ is independent and identically distributed</h3><p>Sounds similar to the previous one? It kind of does. However, it is a little different. Previously, our residuals had growing variance but there we still independent. One residual did not have anything to do with the other. Here, we analyze what if one residual error has some dependency with the other. Consider the following plot whose data is generated by Y = X + noise (random number). Now, this noise accumulates over different values of X. Meaning noise for an X is a random number + the noise of the previous noise. We deliberately introduce this additive noise for the sake of our experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*uUnqUAr8hd01AtxA" /></figure><p>A linear fit seems a good choice. Let’s check the residual errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*RseKHsMZ2QGXKls8" /></figure><p>They do not look entirely random. Is there some metric we can compute to validate our claim. It turns out we can calculate something called <strong>Autocorrelation</strong>. What is autocorrelation? We know that correlation measures the degree of linear relationship between two variables, say A and B. Autocorrelation measures the correlation of a variable with itself. For example, we want to measure how dependent a particular value of A correlates with the value of A some t steps back.</p><p>In our example, it turns out to be 0.945 which indicates some dependency. Now, why do we need errors to be independent? Again, this means the linear model fails to capture complex patterns in the data. Such type of patterns may frequently occur in time series data (where X is time, and Y is a property that varies with time. Stock prices for instance). The unaccounted patterns here could be some seasonality or trends.</p><p>I hope the three assumptions are a bit clear. Now how do we evaluate our model? Let’s take a look at some metrics.</p><h3>Evaluating a Model</h3><p>Previously, we defined MSE to calculate the errors committed by the model. However, if I tell you that for some data and some model the MSE is 23.223. Is this information alone enough to say something about the quality of our fit? How do we know if it’s the best our model can do? We need some benchmark to evaluate our model against. Hence, we have a metric called R squared (R²).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/0*1cbVCwQVLw3okFjp" /></figure><p>Let’s get the terms right. We know MSE. However, what is TSE or Total Squared Error? Suppose we had no X. We have Y, and we asked to model a line to fit these Y values such that the MSE minimizes. Since we have no X, our line would be of the form <strong>Y’ = a</strong>, where a is a constant. If we substitute <strong>Y’</strong> for <strong>a </strong>in the MSE equation, and minimize it by differentiating with respect to <strong>a </strong>and set equal to zero, it turns out that <strong>a </strong>= <strong>mean(Y) </strong>gives the least error. Think about this — the line <strong>Y’ = a </strong>can be understood as the baseline model for our data. Addition of any independent variable X improves our model. Our model cannot be worse than this baseline model. If our X didn’t help to improve the model, it’s weight or coefficients would be 0 during MSE minimization. This baseline model provides a reference point. Now come back to R squared and take a look at the expression. If our model with all the X and all the Y produces an error same as the baseline model (TSE), R squared = 1–1 = 0. This is the worst case. On the opposite, if MSE =0, R squared = 1 which is the best case scenario.</p><p>Now let’s take a step back and think about the case when we add more independent variables to our data. How would the model respond to it? Suppose we are trying to predict house prices. If we add the area of the house to our model as an independent variable, our R square could increase. It is obvious. The variable does affect house prices. Suppose we add another independent variable. Something garbage, say random numbers. Can our R square increase? Can it decrease?</p><p>Now, if this garbage variable is helping minimize MSE, it’s weight or coefficient is non zero. If it isn’t, the weight is zero. If so, we get back the previous model. We can conclude that adding new independent variable at worst does nothing. It won’t degrade the model R squared. So if I keep adding new variables, I should get a better R squared. And I will. However, it doesn’t make sense. Those features aren’t reliable. Suppose if those set of random numbers were some other set of random numbers, our weights would change. You see, it is all up to chance. Remember that we have a sample of data points on which we build a model. It needs to be robust to new data points out of the sample. That’s why we introduce something called adjusted R squared. Adjusted R squared penalizes any addition of independent variables that do not add a significant improvement to the model. You usually use this metric to compare models after the addition of new features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*7qvrD65VBZk5W9bA" /></figure><p>n is the number of points, k is the number of independent variables. If you add features without a significant increase in R squared, the adjusted R squared decreases.</p><p>So now we know something about linear regression. Now we look at regularization and assessment of coefficients.</p><h3>Motivation</h3><p>What exactly are we trying to improve? Linear regression doesn’t essentially need parameter tuning. Consider the following experiment. We generate 10 evenly spaced numbers, from 0 to 10. We assign these numbers to two variables <em>x </em>and <em>y</em>. Consequently, we can establish a relationship between them as <em>y=x</em>. The relationship is obviously linear. Now we add some random Gaussian noise (mean 0) to our <em>y </em>for the sake of this experiment. So now we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/106/0*g7-M2Fs5qCAlQPLd" /></figure><p>The linearity between <em>y </em>and <em>x </em>is now disrupted. For this experiment, we know the process that generated our data (shown in the picture below). But this might not be the case most of the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*t8iWpuGQAh7gEyNK" /></figure><p>Now, if you recall the from above, a linear model would still fit well. Because the random noise has a mean equal to zero, the standard deviation of the noise is constant and hence there is no heteroskedasticity present. But what if we didn’t know any of this info about our data? Let’s assume that we still go ahead and fit a line (shown in the figure below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*777MsKcCoDI3pO0C" /></figure><p>As we see, the line doesn’t fit well. We go ahead and fit a polynomial of degree 2 (having a squared term and the linear terms). The fit looks something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*2r8ia4oHTwjjuAVG" /></figure><p>For the above fit, our X data has two columns: <em>x </em>and <em>x².</em> We know that the R squared of this curve is at least as good as our linear fit. Because if it weren’t a better fit then the coefficient of the squared term would have been 0. Now let’s take a step ahead and fit a polynomial of degree 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*Az45yGo1QzkTlVqT" /></figure><p>This curve fits the data even better. It seems that the curve is able to capture the irregularities well.</p><p>It can be asserted that adding higher degree polynomials will most of the times give you a better fit for training data. If not better, it won’t degrade the metric you follow (Mean Squared Error). But what about generalization? Adding higher degree polynomials leads to overfitting. Many times, a particular feature(in this case, a particular power of X) dominates the model. The outcome is then dependent largely on this feature. Consequently, the model becomes too sensitive and does not generalize well. Hence, we need a way too control the dominance of our input features. By control, we mean a way to control the coefficients. More specifically, the magnitude of these coefficients. This process is called <strong>Regularization</strong>. In this article, we study two ways to achieve this goal — <strong>LASSO</strong> and <strong>Ridge</strong>.</p><p>These two are not very different except for the way they control the magnitude of the coefficients. Previously, we defined the loss function as follows –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*3__cY7mjbYARpbBY" /></figure><p>Where N is the total number of training points, yi is the actual predicted value, yiis the value predicted by the model. In regularization, we add a term to our existing MSE. We will talk about this term in detail ahead.</p><h4>Least Absolute Shrinkage and Selector Operator (LASSO)</h4><p>In Lasso, the MSE looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*dFR7DCeAR6Xf_9FK" /></figure><p>It is the same expression as before, just that the predicted values are expressed as the sum of input features and their coefficients. Also, the additional term is the sum of magnitudes of coefficients multiplied by lambda, or the strength of regularization. Let’s explore this term in more detail.</p><p>We know that we train the linear regression model using gradient descent. Previously, we tried to minimize the squared difference term (the first term). Now, we also try to minimize the sum of the magnitude of coefficients. If you think carefully, the two terms roughly oppose each other. Consider the following — If some coefficients try to assume large values to minimize the sum of squares of the differences (the first term), the regularization term, or the sum of magnitudes of the coefficients increases. Ultimately, the sum isn’t changed as much as it would without the regularization. Ultimately, we obtain coefficients that generalize well. Now, what’s the role of the strength of regularization you may ask? It helps decide how much importance should be given to the regularization in comparison to the first term. If it is large, the model focuses more on reducing the sum of magnitudes of coefficients.</p><h4>Ridge</h4><p>Ridge differs in the way the regularization term is modeled. In LASSO, we summed the magnitudes of coefficients. Here we sum the squares of the coefficients. The modified loss function looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/0*WuDhLZZDTlb1xOuZ" /></figure><p>The high-level idea remains the same. Just the way gradient descent works changes, mathematically.</p><h4>Analysis</h4><p>One may ask, how do these two methods differ? The answer lies in the graph below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xaeHb2tRrqh_5WaS" /></figure><p>Image credits: <a href="http://freakonometrics.hypotheses.org/files/2018/07/lasso1.png">http://freakonometrics.hypotheses.org/files/2018/07/lasso1.png</a></p><p>Consider the above plot. It represents the coefficient value vs. the regularization strength. After a certain lambda value, the coefficients start to shrink to zero value. Thus getting eliminated from the model itself. But in the case of Ridge,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*xLya7kKh7BiLNMkR.png" /></figure><p>Image credits: <a href="https://i.stack.imgur.com/E7BHo.png">https://i.stack.imgur.com/E7BHo.png</a></p><p>The coefficients do not shrink to absolute zero. They are minimized, but not to absolute zero.</p><h3>Conclusion</h3><p>We have seen why do we need regularization at all, what problems does it solve and what are the methods in which it is implemented. We also saw how does it work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=977056f29209" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>