<?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 Sumanta on Medium]]></title>
        <description><![CDATA[Stories by Sumanta on Medium]]></description>
        <link>https://medium.com/@sumanta-skm98?source=rss-5fe9a4ce63c1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*T-HBk6RfjHRbmQA5ZHUDLA.jpeg</url>
            <title>Stories by Sumanta on Medium</title>
            <link>https://medium.com/@sumanta-skm98?source=rss-5fe9a4ce63c1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:22:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sumanta-skm98/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[Amazon Cross selling & Up Selling]]></title>
            <link>https://medium.com/almabetter/amazon-cross-selling-up-selling-8a751c545b75?source=rss-5fe9a4ce63c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a751c545b75</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cross-selling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[upselling]]></category>
            <dc:creator><![CDATA[Sumanta]]></dc:creator>
            <pubDate>Sun, 20 Jun 2021 07:16:27 GMT</pubDate>
            <atom:updated>2021-06-20T10:52:59.647Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Shortest horror story ever: Sold Out</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*cPhhsWSVOSV4BpcA.gif" /></figure><h3>The world’s largest store in every pocket</h3><p>Over the past decade, US e-commerce has grown at an impressive clip of almost 18 percent a year. It now accounts for 8 percent of total retail sales. With the accelerating adoption of mobile — US smartphone penetration exceeds 40 percent today and is projected to reach nearly 60 percent in three years — digital commerce is poised to explode, bringing shopping quite literally into the palms of many consumers’ hands.7 For some retailers, mobile is already a huge factor: at designer-fashion retailer Gilt, for instance, mobile accounts for about 50 percent of daily traffic and more than 30 percent of total sales. Mobile technologies will increasingly influence every stage of the customer’s shopping journey — from personalized promotions prompted by geotargeting to in-store research and price checks, as well as to payment capabilities that offer checkout options beyond waiting in line. A recent McKinsey survey of digital shoppers highlights how mobile technology can complement the in-store experience; for example, almost half of the consumers who conduct research on their mobile phones have done so while in stores, and half say they’re open to the idea of in-store mobile payments.8 Indeed, while just two years ago mobile accounted for only 3 percent of e-commerce sales, that figure will probably rise to 15 percent by the end of 2013.9</p><h3>Highly personalized marketing</h3><p>Habits of consuming content have changed dramatically. US consumers doubled their spending on digital newspapers in the past seven years, for example, while halving their spending on print newspapers.10 As more consumers abandon print media for digital media, marketers follow: 44 percent of them now allocate at least half of their marketing budgets to digital media, up from only 31 percent in 2009.11</p><p>We’re already seeing that direct mail and newspaper circulars are playing a diminished role in retail marketing. Mass advertising will not disappear overnight, but its influence is certainly waning. Ads are shifting toward not just digitization but also personalization, powered by increasingly sophisticated algorithms and predictive models that analyze transaction data and digital-media trends (for example, what topics are hot on social networks). Already, 35 percent of what consumers purchase on Amazon and 75 percent of what they watch on Netflix come from product recommendations based on such algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/0*sO_GOq8Bj1_QkMK0.gif" /></figure><p>Company-directed marketing is also competing for attention with peer recommendations through social networks, user reviews, and the like. Our research shows that for the average consumer, peer recommendations carry ten times more weight than recommendations from salespeople. Indeed, social media could well make up 22 percent of marketing budgets in five years as retailers increase their spending to facilitate and influence peer connections about brands through paid ads and branded pages on social-media platforms such as Facebook, Ibotta, and Pinterest.</p><h3>A distribution revolution</h3><p>Amazon already offers same-day delivery in ten cities and guarantees one- to two-day ground delivery in the continental United States. It is not unreasonable to think that consumers will expect comparable shipping speeds from all retailers — we expect same-day delivery to become available soon in at least the top 150 metropolitan statistical areas, which hold nearly 75 percent of the population.12 Furthermore, we believe retailers will offer shipping free of charge to their most loyal and profitable customers, as opposed to providing it only for those who make minimum purchases. We also expect to see third-party distribution services evolve and expand. Some companies may make big investments in distribution infrastructure and sell it as a service to other retailers, as Amazon and eBay do now. Others are beginning to invest in infrastructure to provide convenient and secure package-delivery locations: lockers and pickup boxes are appearing in groceries, convenience stores, and drugstores nationwide, and new services are sprouting up to let retailers ship packages for pickup at other retail locations or self-storage facilities.</p><p>Consumers have come to expect simple and seamless processes not only for receiving the products they’ve purchased but also for returning unwanted products. Free and easy returns — including the ability to return or exchange online purchases in stores — are becoming table stakes.</p><h3>New retail business models</h3><p>No doubt, retail competition just keeps getting tougher. Consider the ongoing blurring of lines between formats and sectors as retailers try to steal shopping trips and share from one another (for instance, fresh food is no longer the dominion of supermarkets alone but is also increasingly found in warehouse clubs, convenience stores, pharmacies, and even dollar stores). Furthermore, players across the value chain are encroaching on what used to be the exclusive turf of retailers. More manufacturers are selling directly to consumers; examples include Apple, Nike, and — via Vitacost.com — several consumer-product manufacturers. Tech players are also fighting for consumer retail dollars: Google offers more than one billion products for sale on Google Shopping and may soon open retail stores.13 Additionally, companies such as craigslist, eBay, and Etsy (home to almost a million small businesses) are creating marketplaces where individuals and entrepreneurs can sell their wares to the masses. Finally, rental and aftermarket-circulation models, such as Chegg for textbooks or Rent the Runway for designer fashion, are eating into traditional demand for retail goods.</p><p>Competition is coming from near and far as technology makes retailing much more global than it has ever been. UK online retailer ASOS.com, for example, offers free two-day shipping worldwide for a relatively small membership fee, and at times as a promotional offer to all customers. Until recently, retailers didn’t have to worry much about global competition until stores started sprouting down the street — nor did they have an opportunity to access global consumers from North America — but that is changing as technology helps break down barriers and generates new retail business models.</p><h4>Why cross-selling and upselling?</h4><p>We need cross-selling and upselling because there is a very high probability of an existing customer buying a similar product at around 60–70% and around 5–15% for a new customer. If used effectively, they can increase your sales and, therefore, profits. And if backed with machine learning for marketing, cross-sell and upsell campaigns can significantly improve your business’ position on the market.</p><h4><strong>Difference between cross-selling and upselling</strong></h4><p>Let us explain this with an example. If a customer has bought an iPhone 10, he may also be interested in buying AirPods. This would be an example of cross-selling. If he has an iPhone 10, he might be interested in buying an iPhone 12. This would be a classic example of upselling. Conversion to YouTube Premium would also be a very good example of upselling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tqotj2_rekurFDPp.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*7_95KYmEP6OpE87I.png" /><figcaption>Spotify upselling</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*K1l_36aKquSw_KIP.gif" /><figcaption>Cross selling</figcaption></figure><h3>How Machine Learning… ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*7OkgrYv3njzysgay.gif" /></figure><h4>1. Machine Learning is a key to personalized recommendations and improves cross-selling and up-selling opportunities</h4><p>Once we have already collected more than enough data about our customers we have data about your customer’s age, location, gender, hobbies, buying history, marital status, etc. And even did customer segmentation for a better offering. That’s great, but machine learning algorithms can significantly improve our offer of personalization. Thanks to data-driven recommendations, customers will get the right offers at the right time, and, therefore, purchase more products. One example is — Amazon identifies which items are often purchased together. After that shows users potential complementary products. This trick ensures a better customer experience. As users receive exactly those recommendations which they may be waiting for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hONiWYxOAGDlcrwP.png" /></figure><p>Machine learning algorithms are usually divided into two categories: collaborative filtering and content-based filtering. However, combining both of these approaches is also a popular way of building a recommender system.</p><p><strong>2. Machine Learning sharpens sales prediction</strong></p><p>One of the best things about machine learning is that it never stops learning from new data. This ability allows forecasting our customers’ behavior and expectations in the future. On the basis of historical and new data, a machine learning model can increase the accuracy of the sales forecast. This is especially important and useful when you need to<a href="https://addepto.com/how-ltv-and-machine-learning-can-optimise-your-marketing-expenses-and-increase-roi/"> predict how our customers will perceive new products or services. </a>Cross-selling and upselling strategies, and reduces the risk of inefficient marketing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*95FKsaBs3DxJKcTtUDuRDA.png" /></figure><p>Apart from this, using machine learning and customer predictive analytics, it is possible to identify the most effective sources of contact with clients. Again, this can help us to polish your selling strategy and gain more profits.</p><h4>3. Machine Learning makes dynamic pricing possible</h4><p>Dynamic pricing is among the latest pricing trends — it implies continuous altering of product prices, in reaction to real-time demand and supply. This model allows better control of the pricing strategy, gives flexibility without reducing the brand value, and saves budget over the long run. And, dynamic pricing can be a great help when we are cross-selling or upselling our products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JZuuGqA_Op5v7l6x.jpg" /></figure><p>However, it is virtually impossible to efficiently monitor other items and follow the real-time demand and supply manually, since there is too much data to check and analyze. But machine learning can solve the problem — a properly built model will take into account a lot of factors. It will take much more than we would be able to consider without such an algorithm, provide us with precise data, and ensure much faster responses to demand fluctuations.</p><h3>Conclusion</h3><p>We have tried to give you a touch of the ML. We hope you have a great learning through this article.</p><p><em>It feels good to work with a a</em>wesome <em>team. I would like to thank </em><a href="https://medium.com/u/da6a8bfea921"><em>Sanchita Paul</em></a><em> &amp; </em><a href="https://medium.com/u/703e75b9031b">Priyanshi Singh</a> <em>for her invaluable contribution to this article </em>😇.</p><h4>REFERENCES</h4><ul><li>McKinsey &amp; Company- <a href="https://www.mckinsey.com/industries/retail/our-insights/how-retailers-can-keep-up-with-consumers#">https://www.mckinsey.com/industries/retail/our-insights/how-retailers-can-keep-up-with-consumers#</a></li><li>addepto-<a href="https://addepto.com/machine-learning-predict-reduce-customer-churn/"> https://addepto.com/machine-learning-predict-reduce-customer-churn/</a></li></ul><p>You can also follow me on <a href="https://twitter.com/MuduliSumanta">Twitter</a>, <a href="http://sumanta.skm97@gmail.com/"><strong>email me directly</strong> </a>or on <a href="https://www.linkedin.com/in/sumanta-kumar-muduli-08a303198/">LinkedIn</a>. I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a751c545b75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/amazon-cross-selling-up-selling-8a751c545b75">Amazon Cross selling &amp; Up Selling</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[XGBoost by Heart]]></title>
            <link>https://medium.com/almabetter/xgboost-by-heart-b494a471845e?source=rss-5fe9a4ce63c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b494a471845e</guid>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[boosting]]></category>
            <dc:creator><![CDATA[Sumanta]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 17:02:47 GMT</pubDate>
            <atom:updated>2021-06-06T17:10:16.143Z</atom:updated>
            <content:encoded><![CDATA[<p>I know there is no shortage of XGBoost lovers, but today I will make you love this lovely algorithm by showcasing its mathematical beauty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iBZehYAW-cMJOhT5.png" /></figure><h4><strong>What is boosting?</strong></h4><p>The sequential ensemble method, also known as “<a href="https://en.wikipedia.org/wiki/Boosting_%28machine_learning%29#:~:text=In%20machine%20learning%2C%20boosting%20is%20an%20ensemble%20meta-algorithm,algorithms%20that%20convert%20weak%20learners%20to%20strong%20ones.">boosting</a>”, creates a sequence of models that attempt to correct the mistakes of the models before them in the sequence. The first model is built on training data, the second model improves the first model, the third model improves the second, and so on.</p><p>It combines the results of all weak learners to make a more precise prediction. If didn’t understand then don’t worry, suppose 2nd hand car price depends on the age of the car and Km driven. If we predict the price of the car by considering only age then we won’t get a precise prediction because one feature is unable to catch the actual pattern in data, that’s why this model is called a week leaner. Similarly, we could build a model by considering the Km driven feature only but again it would be a weak learner. Individually those weak learners won’t perform well but when we will combine both of them then it will perform well, so we could conclude that combining weak learners result in a strong learner.</p><p>The above example has shown us that boosting combines weak learners to form strict rules. So, how would you identify these weak rules? To find an uncertain rule, you’ll have to use instance-based learning algorithms. Whenever you apply a base learning algorithm, it would produce a weak prediction rule. You’ll repeat this process for multiple iterations, and with each iteration, the boosting algorithm would combine the weak rules to form a strong rule.</p><p>The boosting algorithm chooses the right distribution for every iteration through several steps. First, it’ll take all the various allocations and assign them equal weight. If the first base learning algorithm makes an error, it’ll add more weight to those observations. After assigning weight, we move onto the next step.</p><p>In this step, we’ll keep repeating the process until we increase the accuracy of our algorithm. We’ll then combine the output of the weak learners and create a strong one that would empower our model and help it in making better predictions. A boosting algorithm focuses more on the assumptions that cause high errors due to their weak rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K7wkTFh1NAcpWMDq.png" /></figure><p>In the above image example, the train dataset is passed to the classifier 1. The yellow background indicates that the classifier predicted hyphen and blue background indicates that it predicted plus. The classifier 1 model incorrectly predicts two hyphens and one plus. These are highlighted with a circle. The weights of these incorrectly predicted data points are increased and sent to the next classifier. That is to classifier 2. The classifier 2 correctly predicts the two hyphen which classifier 1 was not able to. But classifier 2 also makes some other errors. This process continues and we have a combined final classifier which predicts all the data points correctly.</p><p>The classifier models can be added until all the items in the training dataset is predicted correctly or a maximum number of classifier models are added. The optimal maximum number of classifier models to train can be determined using hyperparameter tuning.</p><h4>Working Principle:</h4><p>Each tree learns from its previous and updates the residual errors. Hence, the tree that grows next in the sequence will learn from an updated version of the residuals.</p><p>The base learners in boosting are weak learners in which the bias is high, and the predictive power is just a tad better than random guessing. Each of these weak learners contributes some vital information for prediction, enabling the boosting technique to produce a strong learner by effectively combining these weak learners. The final strong learner brings down both the bias and the variance.</p><p>The boosting ensemble technique consists of three simple steps:</p><ul><li>An initial model F0 is defined to predict the target variable y. This model will be associated with a residual (y — F0)</li><li>A new model h1 is fit to the residuals from the previous step</li><li>Now, F0 and h1 are combined to give F1, the boosted version of F0. The mean squared error from F1 will be lower than that from F0:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/0*FS3BKEvbaYKy0bRE.png" /></figure><p>To improve the performance of F1, we could model after the residuals of F1 and create a new model F2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/0*hv8j0NDW76u5nRm8.png" /></figure><p>This can be done for <em>‘m’ </em>iterations, until residuals have been minimized as much as possible:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/0*qXmdT5WfffnS3aeW.png" /></figure><p>Here, the additive learners do not disturb the functions created in the previous steps. Instead, they impart information of their own to bring down the errors.</p><h3>Working of XGBoost</h3><p>Let’s try to understand the working of XGBoost by an example. Here the years of experience is only the feature to predict the salary. Using regression trees as base learners, we can create an <a href="https://www.sciencedirect.com/topics/computer-science/ensemble-modeling">ensemble model </a>to predict the salary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/0*1hziz0A6ThlAcOhu.png" /></figure><p>As the first step, the model should be initialized with a function F0(x). F0(x) should be a function which minimizes the loss function or MSE (mean squared error), in this case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*P8DY44_87yQbPTmM.png" /></figure><p>As we want to minimise the above function, so initialising with mean will give minimal error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/117/0*FzDwT8v3f98PXLr_.png" /></figure><p>F0(x) gives the predictions from the first stage of our model. Now, the residual error for each instance is (yi — F0(x)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/0*t66Wuv9JoCU_BHjL.png" /></figure><p>We can use the residuals from F0(x) to create h1(x). h1(x) will be a regression tree which will try and reduce the residuals from the previous step. The output of h1(x) won’t be a prediction of y; instead, it will help in predicting the successive function F1(x) which will bring down the residuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*0c-HOaVcbjjHWS-cm2jEhg.png" /></figure><p>The additive model h1(x) computes the mean of the residuals (y — F0) at each leaf of the tree. The boosted function F1(x) is obtained by summing F0(x) and h1(x). This way h1(x) learns from the residuals of F0(x) and suppresses it in F1(x).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/0*qVYtQQHkSbUS_CfB.png" /></figure><p>This can be repeated for 2 more iterations to compute h2(x) and h3(x). Each of these additive learners, hm(x), will make use of the residuals from the preceding function, Fm-1(x).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*ZT9Ejnbw_Nnw70tvyAJjCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*4g2ajIaY-4aoGE4D4AE6Vw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*juRWFS3t4Ptd_ZFH.png" /></figure><p>The MSEs for F0(x), F1(x) and F2(x) are 875, 692 and 540. It’s amazing how these simple weak learners can bring about a huge reduction in error!</p><p>Note that each learner, hm(x), is trained on the residuals. All the additive learners in boosting are modelled after the residual errors at each step. Intuitively, it could be observed that the boosting learners make use of the patterns in residual errors. At the stage where maximum accuracy is reached by boosting, the residuals appear to be randomly distributed without any pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kadMixma1pvv97u3.png" /></figure><h3>Using gradient descent for optimizing the loss function</h3><p>For MAE, median will be used instead of mean. For MSE, the change observed would be roughly exponential. Instead of fitting hm(x) on the residuals, fitting it on the gradient of loss function, or the step along which loss occurs, would make this process generic and applicable across all loss functions.</p><p>Gradient descent helps us minimize any differentiable function. Earlier, the regression tree for hm(x) predicted the mean residual at each terminal node of the tree. In gradient boosting, the average gradient component would be computed.</p><p>For each node, there is a factor γ with which hm(x) is multiplied. This accounts for the difference in impact of each branch of the split. Gradient boosting helps in predicting the optimal gradient for the additive model, unlike classical gradient descent techniques which reduce error in the output at each iteration.</p><p>The following steps are involved in gradient boosting:</p><ul><li>F0(x) — with which we initialize the boosting algorithm — is to be defined:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/0*ta9YWlFw0sJN-_iu.png" /></figure><ul><li>The gradient of the loss function is computed iteratively:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*rg6ufHaijAHZipYT.png" /></figure><ul><li>Each hm(x) is fit on the gradient obtained at each step</li><li>The multiplicative factor γm for each terminal node is derived and the boosted model Fm(x) is defined.</li></ul><p>XGBoost is just a faster implementation of Gradient Boosting.</p><h3>Why use XGBoost?</h3><p>The main reason why we use XGBoost is that it’s library rely on:</p><ul><li>model performance</li><li>execution speed.</li></ul><p>As it is proved that XGBoost outperforms several other well-known implementations of gradient tree boosting.</p><h3>What features make XGBoost a leader:</h3><ol><li><strong>Regularization</strong>: XGBoost corrects complex models through regularization. Regularization also helps in preventing overfitting.</li><li><strong>Handling sparse data</strong>: Data processing steps like one-hot encoding make data scattered. XGBoost incorporates a sparsity-aware split finding algorithm to handle different types of sparsity patterns in the data.</li><li><strong>Weighted quantile sketch</strong>: Most of the tree based algorithms can find the split points when the data points are of equal weights. However, they are not capable of handling weighted data. XGBoost has a distributed weighted quantile sketch algorithm to effectively handle weighted data.</li><li><strong>Cache awareness</strong>: In XGBoost, non-continuous memory access is required to get the gradient statistics by row index. Hence, XGBoost has been designed to make optimal use of hardware. This is done by allocating internal buffers in each thread, where the gradient statistics can be stored.</li><li><strong>Block structure for parallel learning</strong>: For faster computing, XGBoost can make use of multiple cores on the CPU. This is possible because of a block structure in its system design. Data is sorted and stored in in-memory units called blocks. Unlike other algorithms, this enables the data layout to be reused by subsequent iterations, instead of computing it again. This feature also serves useful for steps like split finding and column sub-sampling.</li><li><strong>Out-of-core computing</strong>: This feature optimizes the available disk space and maximizes its usage when handling huge datasets that do not fit into memory.</li></ol><h4>Implementation of XGboost on python:</h4><blockquote><em>Loading the appropriate libraries:</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rYcLPskTFx5ulmFL.png" /></figure><blockquote><em>Assuming you have a dataset and have clarified your X, y values, need to split the data into train/test sets.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I7IdHyHG4ga34hCr.png" /></figure><blockquote><em>Training the XGBoost Model</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*X5xOSxcR1eUUDycF.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KqCOIV_3ItUmZOq7.png" /></figure><blockquote><em>Making predictions with the XGBoost model</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Iy_GUClWvmgHF2tz.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*aB2UO6oH1PM63HDt" /></figure><p>If you liked this article, <strong>show your support by clapping</strong> for this article below, <strong>leave a comment.</strong></p><p>You can also follow me on <a href="https://twitter.com/MuduliSumanta">Twitter</a>, <a href="http://sumanta.skm97@gmail.com/"><strong>email me directly</strong> </a>or on <a href="https://www.linkedin.com/in/sumanta-kumar-muduli-08a303198/">LinkedIn</a>. I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b494a471845e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/xgboost-by-heart-b494a471845e">XGBoost by Heart</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[Decision Trees]]></title>
            <link>https://medium.com/almabetter/decision-trees-a8e03ec50965?source=rss-5fe9a4ce63c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8e03ec50965</guid>
            <category><![CDATA[decision-tree-classifier]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree-regressor]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Sumanta]]></dc:creator>
            <pubDate>Sat, 05 Jun 2021 17:43:40 GMT</pubDate>
            <atom:updated>2021-06-06T14:09:22.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nSN4HKmAY3OAHITk" /><figcaption>Photo by <a href="https://unsplash.com/@simone_dalmeri?utm_source=medium&amp;utm_medium=referral">Simone Dalmeri</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Tree Based Algorithms:</h4><p>Decision trees comes under the kingdom of supervised ML. Tree-based models use a series of if-then rules to generate predictions from one or more decision trees. All tree-based models can be used for either regression (predicting numerical values) or classification (predicting categorical values). They can be used for both linear and non-linear data, but they are mostly used for non-linear data. Decision Trees as the name suggests works on a set of decisions derived from the data and its behaviour. It does not use a linear classifier or regressor, so its performance is independent of the linear nature of the data. Boosting and Bagging algorithms have been developed as ensemble models using the basic principle of decision trees compiled with some modifications to overcome some important drawbacks of decision trees and provide better results. One of the other most important reasons to use tree models is that they are very easy to interpret.</p><h4>Decision-Tree Components:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XgAGRqPNTnhSjvyqxyEiyA.png" /></figure><ul><li><strong>Root Node: </strong>Represents the topmost decision node and corresponds to the best predictor in the dataset</li><li><strong>Splitting: </strong>The process of dividing a node into two or more sub-nodes.</li><li><strong>Decision Node: </strong>When a sub-node splits into further sub-nodes.</li><li><strong>Leaf/ Terminal Node: </strong>A node that does not split.</li><li><strong>Pruning: </strong>The process of removing sub-nodes from a decision node.</li><li><strong>Branch / Sub-Tree: </strong>A sub<strong>–</strong>section of entire tree.</li></ul><h4>How Decision Tree Works??</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*t1r4Ss-CcdkPLpwYZie8Zg.png" /></figure><h3>How Tree will decide Which Feature to split upon?</h3><ul><li><strong>Classification-</strong></li></ul><p>Suppose dataset consists of <strong>“n”</strong> attributes then deciding which attribute to keep at the root or at different levels of the tree as internal nodes is a complicated step. we can’t choose any features in random then we could hardly achieve what we are supposed to do.</p><p>For solving this attribute selection problem, researchers worked and devised some solutions. They suggested using some <em>criterion</em> like<em> </em><strong><em>information gain</em>, <em>gini index</em>,</strong> etc. These criterions will calculate values for every attribute. The values are sorted, and attributes are placed in the tree by following the order i.e, the attribute with a high value(in case of information gain) is placed at the root.</p><p>While using information Gain as a criterion, we assume attributes to be <em>categorical</em>, and for gini index, attributes are assumed to be continuous.</p><h3>Information Gain</h3><p>This theorem is based on the principle of <a href="https://en.wikipedia.org/wiki/Information_theory">information theory</a>. By using information gain as a criterion, we try to estimate the information contained by each attribute.</p><p>To measure the randomness or uncertainty of a random variable X is defined by <strong>Entropy</strong>.</p><p><strong>Entropy: </strong>It gives the measure of impurity or randomness in the data. It is given by:</p><blockquote>Entropy= — P(class 1) x Log(P(class 1)) — P(class 2) x Log(P(class 2))</blockquote><p>where P denotes the probability.</p><p>For a binary classification problem with only two classes, positive and negative class.</p><ul><li>If all examples are positive or all are negative then entropy will be zero i.e, low.</li><li>If half of the records are of positive class and half are of negative class then entropy is one i.e, high.</li></ul><p>By calculating <strong>entropy measure</strong> of each attribute we can calculate their <strong>information gain</strong>. Information Gain calculates the expected reduction in entropy due to sorting on the attribute. Information gain can be calculated.</p><p>To get a clear understanding of calculating <strong>information gain &amp; entropy</strong>, we will try to implement it on a sample data.</p><blockquote>On each step or node of a decision tree, used for classification, we try to form a condition on the features to separate all the labels or classes contained in the dataset to the fullest purity. Let’s see how the idea works.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*hCPttnkaVsHfI9fB.png" /></figure><p>Say, the table given above is our dataset. If we try to analyse the dataset and create a decision tree based on the dataset, we will obtain something like the tree given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*EL5hwCJXQ1NTQ82O.png" /></figure><p>In the root node, we are using “Feat 2 ≥3” as the condition to segregate our dataset for the first time. We can see if the answer is false, we reach a leaf, that has only the entries with label 3. So, label 3 is completely separated. But, if the answer is True, we reach an intermediate node. In this case, there are 3 entries, 2 of which belong to label 2 and one belongs to label 1. So, this result has impurity as there are two labels mixed. We apply another condition on the intermediate state and obtain the purely separated labels. On Leaf 2, we have obtained only the Label 1 entry and on leaf 3, we have only the Label 2 entries.</p><p>Now, the questions that may arise are:</p><ol><li>How do we fix the deciding value in case of numerical features, for instance, “feat 2≥3”?</li><li>How do we decide which features should we use to create our internal condition nodes?</li><li>How to decide which feature to use first, for instance, in the previous case, we had feature 1 and feature 2, so, which feature should we use as the root?</li></ol><p>We will see the answers to these questions as we move forward.</p><p>If in a dataset there are a total of 20 entries or rows, and 14 of them belongs to label 1 and 6 of them belongs to label 2, the entropy will be equal to:</p><blockquote><em>= — P(label 1).log(P(label 1)) — P(label 2).log(P(label 2))</em></blockquote><blockquote><em>= — 14/20.log(14/20) — 6/20.log(6/20)</em></blockquote><blockquote><em>=0.880</em></blockquote><p><strong>Information Gain: </strong>The information gain is the decrease in the entropy after the dataset is split on the basis of an attribute. Constructing a decision tree depends on finding the attribute that returns the highest information gain. It helps in choosing which feature or attribute will be used to create the deciding internal node at a particular point.</p><p>It is given by:</p><blockquote><em>Information gain=Entropy(s) — [(Weighted average) x (Entropy of each feature)</em></blockquote><p>Now, how does this actually operate?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/0*f6n5nJSF98BYIeeE.png" /></figure><p>Firstly, we want to check the distribution of the labels based on each feature, in order to get an insight into how much information gain will a feature provide.</p><p>For instance for feature 1,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*CkxcsKr877-himax.png" /></figure><p>We can see if we select the condition “Feature 1==2”, we can successfully separate label 2 from the dataset purely.</p><blockquote><em>Now, Entropy (E(s))= — 4/10*log(4/10) — 6/10*log(6/10)=0.97</em></blockquote><blockquote><em>For Feature 1:</em></blockquote><blockquote><em>E(feature_1==1)= — 3/4*log(3/4) — 1/4*log(1/4)=0.81</em></blockquote><blockquote><em>E(feature_1==2)= — 3/3log(3/3) = — 1log1=0</em></blockquote><blockquote><em>E(feature_1==3)= — 2/3*log(2/3) — 1/3*log(1/3)=0.91</em></blockquote><blockquote><em>For Feature 1, the weighted average=</em></blockquote><blockquote><em>4/10*0.81+3/10*0+3/10*0.91=0.597</em></blockquote><blockquote><em>Information Gain= 0.97–0.597=0.313</em></blockquote><p>Again, let’s do the same for feature 2:</p><p>For Feature 2:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/0*bEufxK9_o268kbVk.png" /></figure><blockquote><em>For Feature 2:</em></blockquote><blockquote><em>E(feature_2==1)= — 2/3*log(2/3) — 1/3*log(1/3)=0.91</em></blockquote><blockquote><em>E(feature_2==2)= — 2/3*log(2/3) — 1/3*log(1/3)=0.91</em></blockquote><blockquote><em>E(feature_2==3)= — 3/4*log(3/4) — 1/4*log(1/4)=0.81</em></blockquote><blockquote><em>For Feature 2, the weighted average=</em></blockquote><blockquote><em>3/10*0.91+3/10*0.91+4/10*0.81=0.87</em></blockquote><blockquote><em>So, Information Gain for feature 2= 0.97–0.87=0.1</em></blockquote><p>Now, we found information gain at the point for feature 1 is larger than that of feature 2. So, we will use feature 1 to form the root node.</p><p><strong>Gini index: </strong>Gini Index is also a measure of impurity used to build a decision tree using the CART mechanism.</p><p>It is given by:</p><blockquote><em>Gini Impurity= 1 — (Probability of ‘Class 1’)² — (Probability of ‘Class 2’)²</em></blockquote><p>Let’s see its working also,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/0*qSpaAs34Fk1BVu4s.png" /></figure><p>Say, this is our distribution on a dataset of 100 entries. A condition applied to Feature 1 gives the above conclusion.</p><blockquote><em>Gini Impurity of Leaf 1: 1–(35/43)² — (8/43)² =0.302</em></blockquote><blockquote><em>Gini Impurity of Leaf 2: 1 — (15/57)² — (42/57)²=0.38</em></blockquote><blockquote><em>Now, the overall Gini Impurity for Feature 1:</em></blockquote><blockquote><em>The weighted average of Gini impurity:</em></blockquote><blockquote><em>=43/100* 0.30+ 57/100*38=0.34</em></blockquote><p>Similarly, we calculate the Gini impurity index for other features also.</p><p>One thing to notice is that if every entry in a dataset belongs to only 1 class, i.e, either class 1 or class 2,</p><blockquote><em>Gini Impurity: 1-(1/(0+1)²)-(0/(0+1)²)=0</em></blockquote><p>So, we can see for a pure distribution the Gini impurity index is 0.</p><p>Gini Impurity index can also be used to decide which feature should be used to create the condition node. The feature that results in a smaller Gini impurity index is chosen to create the internal condition node at that point.</p><p>How to do it for Continuous features?</p><p>First, we sort the dataset based on the numerical valued feature in an ascending manner. Next, we find the average of the adjacent pairs of numeric values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/0*QG6ZPCSKd717460O.png" /></figure><p>Say, we obtained the averages as shown above. So, avg_1=(val_1+val_2)/2. Next, we fit the average values in the condition to check which provides the minimum Gini Impurity index or which provides the maximum information gain, based on the methods we are using. The average value serves as the cut-off value in our condition formed for the feature.</p><p>Similarly, for discrete value-based or class-based features, we try and fit every value present in the set and create the condition. Finally, we select the value or condition that gives the minimum Gini impurity index. So, this wraps up our first query.</p><p>Now, we have seen we consider the Gini impurity index or Information gain to decide which condition we should consider. In some cases, some features show no improvement at all or 0 information gain, such features are never used in a decision tree. This is how the decision tree does automatic feature selection.</p><ul><li><strong>Regressor-<br></strong>Let’s consider the two conditions:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iryvcL4YfVdbryOd3wzq2Q.png" /></figure><p>In the first distribution, we can see, we can easily fit a function to it. But, in the second case, the distribution is random. In such cases, Regression Trees are used.</p><p>In regression trees, the leaves represent a continuous numeric value in contrast to classification trees which normally represent discrete values at the leaves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/0*Pp8cSU3DnsWhHqN-.png" /></figure><p>The more computation power is needed when we will grow trees on high dimensionality dataset. Now, let’s see how we decide which value we should pick for creating the conditions. It is a bit different from what we did in the case of classification trees.</p><p>Let’s say we have a feature set comprising of three features: Feature 1, feature 2, and feature 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/0*oswM7RXpVRex4EeR.png" /></figure><p>Distribution for Feature 1</p><p>Let’s consider the above image as our distribution for feature 1. Y-axis has the values on which we need to fit the regression and the X-axis has the feature values. So, we consider the values shown in the diagram as Val 1, Val 2, and so on, as the cut-off values to form the condition on Feature 1. These values are nothing but the average of feature 1 values of two corresponding points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/0*rF-MY3EpJabNm7Kl.png" /></figure><p>Now, let’s consider the above diagrams. The diagrams are not to scale, so avg_2 is not equal to avg_4. When we consider the val_1 as the cut-off value for feature 1, we take the average values of all the Y-values for the points to the left of the line as avg_1, and similarly, we take the average values of all the points to the right of the line as avg_2. So, for any value, for which the condition feature 1&gt;val_1 holds True, the tree provides, the avg_2 as the prediction and vice versa.</p><p>Next, we take the squared errors for all the points. So for any point to the right of the line, the squared error of the point is (actual value — predicted value(i.e, avg_2))² and similarly for any point on the left, the squared error of the point is (actual value — predicted value(i.e, avg_1))². So, we find the squared error for all the points and sum them up. This is called the Sum of Squared Error. Say, for value 1 the Sum of Squared error is S_1.</p><p>Similarly, for value 4, the sum of squared error is calculated to say S_4. We can observe that S_4 will be much less than S_1. So, we find the sum of squared errors for all the values we looked at, to be the cut-off to create the condition. If we plot them, we will obtain the plot as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/0*CVey2pBwD_MBh1YR.png" /></figure><p>In the above diagram, we can see that the val_4 for Feature 1 provides the minimum sum of squared error for the point. So, now we have seen how the cut-off value for a particular value is decided.</p><p>Now, if we have multiple features, how to decide which feature should we use to create the node. For this, we create candidates. For instance, say for feature 1, val_4 gives the minimum sum of squared error. So, it is termed as the candidate for feature 1. Similarly, we find candidates for feature 2 and feature 3. Say the SSR corresponding to feature 2’s candidate is S_2_3, and that of feature 3’s candidate is S_3_5. We will compare S_4, S_2_3, and S_3_5 and select the minimum. The feature corresponding to the minimum will be used to create the deciding node.</p><h4><strong>Drawbacks of decision trees:</strong></h4><p>One of the major challenges of the decision tree is tackling overfitting issue. It is rule based algorithms so it will grow as long as condition is satisfied, it starts taking small information gain into consideration, so decision tree is a greedy algorithm. It induces a problem of memorising training data.</p><p><strong>Techniques used to tackle drawbacks of decision trees:</strong></p><ul><li>We can restrict tree grow by setting a threshold on the information gain, such that, if the information gain provided by the condition is less than a given value, we won’t consider the condition. This partially prevents overfitting and helps create a generalized model.</li><li>Pruning is a method of removal of nodes to get the optimal solution and a tree with reduced complexity. It removes branches or nodes in order to create a sub-tree that has reduced overfitting tendency. We will talk about the concept once we are done with Regression trees.</li></ul><p>If you liked this article, <strong>show your support by clapping</strong> for this article below, <strong>leave a comment.</strong></p><p>You can also follow me on <a href="https://twitter.com/MuduliSumanta">Twitter</a>, <a href="http://sumanta.skm97@gmail.com/"><strong>email me directly</strong> </a>or on <a href="https://www.linkedin.com/in/sumanta97/">LinkedIn</a>. I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8e03ec50965" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/decision-trees-a8e03ec50965">Decision Trees</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[Introduction to NLP]]></title>
            <link>https://medium.com/almabetter/introduction-to-nlp-2b5aafbbe428?source=rss-5fe9a4ce63c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b5aafbbe428</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sumanta]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 22:26:50 GMT</pubDate>
            <atom:updated>2021-04-30T14:43:15.472Z</atom:updated>
            <content:encoded><![CDATA[<p>NLP is a subdomain of AI that enables machines to read, understand and analyze human languages like text, speech, etc. The ultimate goal of NLP is to help computers understand language human behavior<strong>.</strong> It is the driving force behind things like virtual assistants, speech recognition, sentiment analysis, automatic text summarization, machine translation and much more.</p><h3>What are some of the applications of NLP?</h3><ol><li>Grammarly, Microsoft Word, Google Docs</li><li>Search engines like DuckDuckGo, Google</li><li>Voice assistants — Alexa, Siri</li><li>News feeds- Facebook, Google News</li><li>Translation systems — Google translate</li></ol><h3>Why text preprocessing ?</h3><p>Computers are great at working with structured data like spreadsheets and database tables, but we humans usually communicate in words, not in tables. Computers couldn’t understand those. To solve this problem, we have to come up with some advanced techniques. In NLP, we use some very smart techniques that convert languages to useful information like numbers or some mathematically interpretable objects so that we could use them in ML algorithms based upon our requirements.</p><p>Machine Learning needs data in numeric form. We first need to clean the textual data and <em>this process to prepare(or clean) text data before encoding is called text preprocessing, </em>this is the very first step to solve the NLP problems. SpaCy, NLTK are some libraries used to make our tasks of preprocessing easier.</p><h4><strong>Steps involved in preprocessing:</strong></h4><h3>Cleaning</h3><ol><li>Removing URL-</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*8iZpGdPTldV7Ki_E5mVYdQ.png" /></figure><pre># Importing re library to remove url.<br>import re</pre><pre><br>def clean_url(https://medium.com/text):<br>  return re.sub(r&#39;http\S+, &quot;&quot;, text)<br>dataset[&#39;Clean_text&#39;]=dataset[&#39;Review&#39;].apply(clean_url)</pre><p>2. Removing punctuations and numbers . Punctuation is basically the set of symbols [!”#$%&amp;’()*+,-./:;&lt;=&gt;?@[\]^_`{|}~]:</p><pre>def clean_punctuations(text):<br>  return re.sub(&#39;[^a-zA-Z]&#39;,&#39; &#39;, text)</pre><pre>dataset[&#39;Clean_text&#39;]=dataset[&#39;Clean_text&#39;].apply(clean_punctuations)</pre><h4>3. Converting all to lower case</h4><pre>def clean_lower(text):<br>  return str(text).lower()<br>dataset[&#39;Clean_text&#39;]=dataset[&#39;Clean_text&#39;].apply(clean_lower)</pre><h4>4. Removing stopwords</h4><pre>import nltk</pre><pre>nltk.download(&#39;stopwords&#39;)</pre><pre>from nltk.corpus import stopwords</pre><pre>stop=set(stopwords.words(&#39;english&#39;))</pre><pre>def clean_stopwords(text):</pre><pre> return &#39; &#39;.join([item for item in text if item not in stop])</pre><pre>dataset[&#39;Clean_text&#39;]=dataset[&#39;Clean_text&#39;].apply(clean_stopwords)</pre><h4>5. Tokenization-</h4><p>It’s a method of splitting a string into smaller units called tokens. A token could be a punctuation, word, mathematical symbol, number etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*GaMrBWjMxvVsMo3S9iLzng.png" /></figure><pre>from nltk.tokenize import word_tokenize</pre><pre>def clean_tokenization(text):<br>  return word_tokenize(text)</pre><pre>dataset[&#39;Clean_text&#39;]=dataset[&#39;Clean_text&#39;].apply(clean_tokenization)</pre><h4>6. Stemming and Lemmatization-</h4><ul><li><strong>Stemming</strong> algorithms work by cutting off the end or the beginning of the word, taking into account a list of common prefixes and suffixes that can be found in an inflected word. This indiscriminate cutting can be successful in some occasions, but not always, and that is why we affirm that this approach presents some limitations.</li></ul><pre>from nltk.stem import PorterStemmer<br>stemmer=PorterStemmer()<br>def Clean_stem(token):<br>  return [stemmer.stem(i) for i in token]</pre><pre>dataset[&#39;Clean_text&#39;]=dataset[&#39;Clean_text&#39;].apply(Clean_stem)</pre><ul><li><strong>Lemmatization</strong>, on the other hand, takes into consideration the morphological analysis of the words. To do so, it is necessary to have detailed dictionaries which the algorithm can look through to link the form back to its lemma. Look into the figure for clear picture.</li></ul><pre>from nltk.stem.snowball import SnowballStemmer</pre><pre>lemma = SnowballStemmer(&quot;english&quot;)</pre><pre>def clean_lemmatization(token):<br>  return [lemma.lemmatize(word=w,pos=&#39;v) for w in token]</pre><pre>dataset[&#39;Clean_text&#39;]=dataset[&#39;Clean_text&#39;].apply(clean_lemmatization)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/0*9BvN65J6sjvA3IzF" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zfXXmhBs5Oe61KAmUzwl8A.png" /></figure><p><strong>7. Removing small words having length ≤2</strong></p><p>After performing all required process in text processing there is some kind of noise is present in our corpus, so like that i am removing the words which have very short length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*u7_mWlExGor58thZ.png" /></figure><pre>def Clean_length(token):<br>  return [i for i in token if len(i)&gt;2]</pre><pre>dataset[&#39;Clean_text&#39;]=dataset[&#39;Clean_text&#39;].apply(Clean_length)</pre><h4>8. Convert the list into string back</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*aIU4HDsck_q86aWF.png" /></figure><pre>def convert_to_string(list1):<br>  return &#39; &#39; .join(list1)<br>dataset[&#39;Clean_text&#39;]=dataset[&#39;Clean_text&#39;].apply(convert_to_string)</pre><p>Now we are all set to vectorize our text.</p><h3>Vectorizing</h3><ol><li><strong>CountVectorizer- </strong>It<strong> </strong>converts a collection of text documents to a matrix of token counts: <strong>the occurrences of tokens in each document</strong>. This implementation produces a sparse representation of the counts.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*73FCorAbb0sTI7u0.png" /></figure><pre>from sklearn.feature_extraction.text import CountVectorizer</pre><pre>vectorizer = CountVectorizer(max_df = 0.9,min_df = 10)</pre><pre>X = vectorizer.fit_transform(dataset[&#39;Clean_text&#39;])</pre><p>2. TF-IDF<strong>: </strong>In TF-IDF we<strong> </strong>transform a count matrix to a normalized <strong>tf: term-frequency</strong> or<strong> term-frequency times inverse document-frequency</strong> representation using <strong>TfidfTransformer</strong>. The formula that is used to compute the tf-idf for a <strong>term t</strong> of a <strong>document d</strong> in a document set is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/0*9rDpN5R8aJMR7dqe.png" /></figure><pre>from sklearn.feature_extraction.text import TfidfVectorizer as tf</pre><pre>tf = tf(max_df = 0.9,min_df = 10)</pre><pre>X = tf.fit_transform(dataset[&#39;Clean_text&#39;])</pre><p><strong>Note-</strong></p><p>In <strong>CountVectorizer </strong>we <strong>only count the number of times a word appears in the document </strong>which results in biasing in favour of most frequent words. This ends up in ignoring rare words which could have helped is in processing our data more efficiently.</p><p>To overcome this , we use TfidfVectorizer<strong> .</strong></p><p>In <strong>TfidfVectorizer </strong>we consider <strong>overall document weightage</strong> of a word. It helps us in dealing with most frequent words. Using it we can penalize them. TfidfVectorizer weights the word counts by a measure of how often they appear in the documents.</p><p>If you liked this article, <strong>show your support by clapping</strong> for this article below, <strong>leave a comment.</strong></p><p>You can also follow me on <a href="https://twitter.com/MuduliSumanta">Twitter</a>, <a href="http://sumanta.skm97@gmail.com/"><strong>email me directly</strong> </a>or on <a href="https://www.linkedin.com/in/sumanta-kumar-muduli-08a303198/">LinkedIn</a>. I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b5aafbbe428" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/introduction-to-nlp-2b5aafbbe428">Introduction to 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://medium.com/almabetter/hierarchical-clustering-c40f46c9185e?source=rss-5fe9a4ce63c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c40f46c9185e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[unsupervised-clustering]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <dc:creator><![CDATA[Sumanta]]></dc:creator>
            <pubDate>Sat, 24 Apr 2021 09:54:31 GMT</pubDate>
            <atom:updated>2021-04-24T15:39:52.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2dgMcWklD0wWO1Sq.jpg" /></figure><h4><strong>What is clustering?</strong></h4><p>A <strong><em>cluster</em></strong> is a collection of objects which are “similar” between them and are “dissimilar” to the objects belonging to other clusters. <strong><em>Clustering</em></strong> is a technique used to group similar kind of objects and separate dissimilar kind of objects. It’s a very common technique for statistical data analysis, used in many fields, including pattern recognition, image analysis, information retrieval, bioinformatics, data compression, computer graphics and machine learning. It falls into the realm of unsupervised ML.</p><p><strong>Why we need clustering?</strong></p><p>For examples companies with a strong focus on customers like retail, finance, and marketing are some of the key organizations that benefit from data. To recommend something for customer, company have to be more careful as one misconduct could lead to high financial loss for company. In this case company want to drill down so they can identify the cluster from which the customer belongs to, so that they can predict exact behavior of customer.</p><h3>What is hierarchical clustering</h3><p>The word “ Hierarchy” in the name of algorithm is suggesting something tree like structure. Clustering of data starts to make clusters in tree format.</p><p>Let’s talk about some concepts before going into it’s technicality-</p><p><strong>Proximity matrix-</strong></p><p>Suppose we have a dataset having their id and marks they have obtained. ID is unique to each student, the only feature is marks column. If we want to make a proximity matrix, we have to find the Euclidean distance of each point with all other points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*czSKuYegmLS19JRhKHNnGw.png" /></figure><p>The proximity matrix is-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*UJLJq5BzNlq0lXCeXir9Og.png" /></figure><p>The diagonal elements of this matrix will always be 0 as the distance of a point with itself is always 0. We will use the Euclidean distance formula to calculate the rest of the distances. So, let’s say we want to calculate the distance between point 2 and 3:</p><p>√(28−7)2=√441=21</p><p>Similarly, we will calculate distance between each points and will fill the whole matrix.</p><p>Let’s jump directly into the working of hierarchical clustering algorithm.</p><ol><li>Make proximity matrix out of our data. Here, we have 7 data points(A,B,C,D,E,F,G).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*TuT_-UkpLfl4LURsAgJEKw.png" /></figure><p>2. Identify the shortest distance and make a cluster out of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eM3mwWs5b3bcs8pSKk873Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*XSJWt5S8ibddqZI55Y-oSg.png" /></figure><p>3. we have clustered A,B as one and D,E as another and will treat them as single data point and rewrite proximity matrix. One obvious question will arise that if we treat a cluster as as point then what value of features it will contain. It’s the most important part of Hierarchical clustering. Basically we can use average, minimum, maximum distance between them. As there is no strict rules when what to use, it’s quite challenging. Based on various methods we get various types of clustering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*WtwgIFEhGek4LnAQPl9lJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xX5KVNm0_fuM2Rj3nwdnw.png" /><figcaption>it’s based on various grouping techniques</figcaption></figure><p>4. We will repeat these steps till we reach at one cluster. This is the final dendrogram shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*gG7jvKkSVBmfN1WRn3zxow.png" /></figure><p>5. We will cut our dendrogram to get our final clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-OrqbcysBdIz7MQvikydQ.png" /></figure><p>Cutting of dendrogram is a challenging task. There is no definitive answer since cluster analysis is essentially an exploratory approach, the interpretation of the resulting hierarchical structure is purpose dependent and requires some domain knowledge.</p><p>It could be implemented by some few lines of code.</p><pre># Using the dendogram to find the optimal number of clusters</pre><pre>import scipy.cluster.hierarchy as sch</pre><pre>dendrogram = sch.dendrogram(sch.linkage(X, method = &#39;ward&#39;))</pre><pre>plt.title(&#39;Dendrogram&#39;)</pre><pre>plt.xlabel(&#39;Customers&#39;)</pre><pre>plt.ylabel(&#39;Euclidean Distances&#39;)</pre><pre>plt.show() # find largest vertical distance we can make without crossing any other horizontal line</pre><p><strong>Points to note-</strong></p><p>It struggles when it deal with lots of data(both high dimensional and high number of rows). It takes lots of time to train as it calculates every possible distances. For example we have 1000 rows in our data set then it will calculate distance for 100C2 number of distances.</p><p>If you liked this article, <strong>show your support by clapping</strong> for this article below, <strong>leave a comment.</strong></p><p>You can also follow me on <a href="https://twitter.com/MuduliSumanta">Twitter</a>, <a href="http://sumanta.skm97@gmail.com/"><strong>email me directly</strong> </a>or on <a href="https://www.linkedin.com/in/sumanta-kumar-muduli-08a303198/">LinkedIn</a>. I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c40f46c9185e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/hierarchical-clustering-c40f46c9185e">Hierarchical Clustering</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[K-Means Clustering]]></title>
            <link>https://medium.com/almabetter/k-means-clustering-5bd8eceadd33?source=rss-5fe9a4ce63c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bd8eceadd33</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sumanta]]></dc:creator>
            <pubDate>Sat, 24 Apr 2021 06:19:55 GMT</pubDate>
            <atom:updated>2021-04-24T15:40:32.596Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZefeM3h1YHwZdDfD.jpg" /></figure><p><strong>What is Clustering?</strong></p><p>A <strong><em>cluster</em></strong> is a collection of objects which are “similar” between them and are “dissimilar” to the objects belonging to other clusters. <strong><em>Clustering</em></strong> is a technique used to group similar kind of objects and separate dissimilar kind of objects. It’s a very common technique for statistical data analysis, used in many fields, including pattern recognition, image analysis, information retrieval, bioinformatics, data compression, computer graphics and machine learning. It falls into the realm of unsupervised ML.</p><p>Ex- We all are using various song listening apps. We don’t want to search every time for a song to listen to but want to listen to a similar type of songs based on our interest which we call playlists. We must have seen, these apps shows recommended playlist based on our search.</p><h3>K-Means Clustering</h3><p>Before going into the terminologies of K-Means, we need to understand some concepts beforehand. Let’s talk about those-</p><h4><strong>What metric we are going to use for identifying the similarity and dissimilarity among various data points?</strong></h4><p>We don’t have labelled data(unsupervised learning), how we know which points are similar and dissimilar to each other? In the case of K-means, we use <strong><em>Euclidean Distance(ED) </em></strong>to find out the likeness<strong><em>.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/0*rtWcYe95XanYxnr1.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*dmfH3Q4FMDfUsmYZ" /></figure><h3><strong>Mean of a cluster</strong></h3><p>Suppose we have 2 dimensional(x, y) data cluster having n elements. To find out the mean of the cluster we have to calculate the average of each dimension. The point having the coordinate as the average of each dimension is called the <strong><em>mean</em></strong> of a cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*uHw5vZPf06mxcSd1" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/0*DlrTNjLH0wI1alwk" /><figcaption>fig-1</figcaption></figure><p>Till now we have covered all the important concepts that we need to know beforehand. Let’s discuss k- mean clustering algorithms.</p><h3><strong>How </strong>exactly <strong>K-Means works?</strong></h3><p>K- Mean can’t return how many clusters we have. We have to specify the number of clusters beforehand, we want our algorithms to distinguish.</p><ol><li>We have to initialize the number of means randomly in data points.</li><li>Then we will calculate the distance of each point from each random means. Which data point will belong to which cluster? It will only be decided by the shortest distance from random means.</li><li>After assigning each point to clusters, we will calculate a new mean for each cluster by the above-discussed method.</li><li>After getting the coordinate of new means. we will again find out the distance of each point from new means then will reassign each point to new clusters based on the shortest distance.</li><li>This process will continue.</li><li>This is an iterative algorithm. This procedure will continue still we don’t reach global minima.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*w8PDK_b2StaAxG8x.gif" /></figure><p>K-Means could be implemented by the few lines of code only.</p><pre><strong><br>from</strong> <strong>sklearn.cluster</strong> <strong>import</strong> KMeans<br>kmeans = KMeans(n_clusters=2, random_state=0).fit(X)</pre><p><strong>Important points to focus on-</strong></p><ol><li>Though we are aiming to reach a global minimum, not to a local minimum. Many times we end up with local minima because it’s highly influenced by the random points we are choosing for the initialization of means. To solve this problem we parallelly run K means a multi number of times, the k-means algorithm will be run with different centroid seeds. The final results will be the best output. To implement this we have a parameter called n_init in scikit-learn.</li></ol><pre>kmeans = KMeans(n_clusters=2, random_state=0,n_init=10)</pre><p>2. We can also choose the maximum number of iterations we want to reach at global minima by assigning values to parameter n_iter.</p><pre>kmeans = KMeans(n_clusters=2, random_state=0,n_init=10,<br>max_iter=1000)</pre><p>3. We have to be very careful while choosing the number of clusters. We can best estimate it by various methods.<strong> </strong>The<strong> Elbow method</strong> is very popular for finding it. I will discuss it in another blog.</p><p>If you liked this article, <strong>show your support by clapping</strong> for this article below, <strong>leave a comment.</strong></p><p>You can also follow me on <a href="https://twitter.com/MuduliSumanta">Twitter</a>, <a href="http://sumanta.skm97@gmail.com/"><strong>email me directly</strong> </a>or on <a href="https://www.linkedin.com/in/sumanta-kumar-muduli-08a303198/">LinkedIn</a>. I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bd8eceadd33" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/k-means-clustering-5bd8eceadd33">K-Means Clustering</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[Regularization techniques in Machine Learning]]></title>
            <link>https://sumanta-skm98.medium.com/regularization-techniques-in-machine-learning-a31daf2acc3e?source=rss-5fe9a4ce63c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a31daf2acc3e</guid>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sumanta]]></dc:creator>
            <pubDate>Wed, 07 Apr 2021 09:43:36 GMT</pubDate>
            <atom:updated>2021-04-12T00:47:12.548Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g4ZCJ3-yKRhCYurm.jpg" /></figure><h4><strong>What is regularization?</strong></h4><p>Regularization is a highly used technique in ML that solves the overfitting problem of our model. Ok.., someone may ask that we could also reduce model complexity to solve that problem. Yeah, the question is genuine but, if we reduce model complexity we might end up with underfitting which is not desirable at all. So, we want a more reliable technique that will ensure that we are not losing any data information and at the same time will predict our target variable confidently. That is, where regularization comes into the picture.</p><p>This is a form of regression, that constrains or shrinks the coefficient estimates towards zero. In other words, <strong><em>this technique discourages learning a more complex or flexible model, to avoid the risk of overfitting.</em></strong></p><h4><strong>How does It work?</strong></h4><p>Before going through regularization working, let’s quickly go through how OLS works. We know in OLS, model parameters are found out by taking the optimum value of residual sum squares(RSS) into account. The fitting procedure of OLS involves a loss function, known as the residual sum of squares or RSS. The coefficients are chosen, such that they minimize this loss function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/0*O0-jnVmp1rS0vr7I" /></figure><p>where:</p><ul><li>n is the <strong>total number of observations (data)</strong>.</li><li>yi is the <strong>actual output value of the observation (data)</strong>.</li><li>p is the <strong>total number of features</strong>.</li><li>βj is a <strong>model’s coefficient</strong>.</li><li>xij is the ith<strong> observation, </strong>jth<strong> feature’s value</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*S-JcKW6VB7v2Nt-8.png" /></figure><p>In the case of OLS, we achieve optimum by gradient descent which starts by taking a random starting point (0,0).</p><p><strong><em>Regularized linear regression models are very similar to least squares, except that the coefficients are estimated by minimizing a slightly different objective function. we minimize the sum of RSS and a “penalty term” that penalizes coefficient size</em></strong><em>.</em></p><p><strong><em>Regularization puts a constraints on the optimization algorithm.</em></strong></p><p>There are mainly 3 regularization techniques used across ML, let’s talk about them individually.</p><h4><strong>Lasso Regression:</strong></h4><p>In lasso, the sum of absolute values of parameters multiplied by a shrinkage factor is added to the loss function of OLS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/0*XMdFjhVpGYLEBfXl" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*6yTVHquJZGkdd5PL" /></figure><p>where:<br> λ is a tuning parameter(Shrinkage factor) that seeks to balance between the fit of the model to the data and the magnitude of the model’s coefficients:</p><ul><li>A tiny λ imposes no penalty on the coefficient size and is equivalent to a normal linear regression.</li><li>Increasing λ penalizes the coefficients and thus shrinks them towards zero.</li></ul><p>The above image shows lasso regression, where the <strong><em>RSS is modified by adding the shrinkage quantity.</em></strong> Now, the coefficients are estimated by minimizing this function. Here, <strong><em>λ is the tuning parameter that decides how much we want to penalize the flexibility of our model.</em></strong> The increase in flexibility of a model is represented by the increase in its coefficients, and if we want to minimize the above function, then these coefficients need to be small. This is how the lasso regression technique prevents coefficients from rising too high. Also, notice that we shrink the estimated association of each variable with the response, except the intercept β0, This intercept is a measure of the mean value of the response when xi1 = xi2 = …= xip = 0.</p><p>Let’s understand how coefficients reduce by changing our loss function mathematically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*OWOmdVJ8P3RJgJeWS_g0UA.png" /></figure><p>These elliptical boundaries are drawn for a specific value error function. simply, if we move along those boundaries our value of RSS function won’t change but we will come across various combinations of coefficients.</p><p><strong><em>for the lasso, the equation becomes,|β1|+|β2|≤ s</em></strong>. This implies that <em>lasso coefficients have the smallest RSS(loss function) for all points that lie within the diamond given by |β1|+|β2|≤ s.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*FN1h5_SnX_bsrJcRQjXNJw.png" /></figure><p>Lasso regression just put a constraint.</p><p>As absolute function is not differentiable at 0, so we can’t use gradient descent here but, we use other methods of optimizations like<em> coordinate descent</em> etc.</p><p><strong><em>The lasso constraint has corners at each of the axes, and so the ellipse will often intersect the constraint region at an axis. When this occurs, one of the coeﬃcients will equal zero. </em></strong>We have considered only two parameters in this case, but in the case of multiple parameters, it may reduce multiple parameters to zero. So, it is used for <strong><em>feature selection </em></strong>also.</p><h4>2. <strong>Ridge Regression:</strong></h4><p>In ridge regression, we add a penalty term equals to the sum of squares of coefficients multiplied by a shrinkage factor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*4mrmsqDJrfPVGDwH" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/0*x4sXu2VWV7x59pxJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*1pHwPfuhgTDFH8elIh_B2g.png" /></figure><p><strong><em>Ridge regression is expressed by β¹² + β²² ≤ s</em></strong>. This implies that <em>ridge regression coefficients have the smallest RSS(loss function) for all points that lie within the circle given by β¹² + β²² ≤ s.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Aa9Qur1UvcbL-TR5ttW_w.png" /></figure><p><strong><em>Ridge regression has a circular constraint with no sharp points, this intersection will not generally occur on an axis, and so the ridge regression coeﬃcient estimates will be exclusively non-zero.</em></strong></p><h4>3. Elastic Net Regression:</h4><p>It is a regression that is a combination of both lasso and ridge.</p><p>The constraint zone is the combination of circle and diamond. Apart from the shape, everything is the same.</p><p><strong>Elastic net regression=a * Lasso regression(L1 norm) + b *Ridge regression(L2 norm)</strong></p><p><strong>L1_norm=a/(a + b)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*OAIRgLWB1-FFXlag.png" /></figure><p><strong><em>Behavior of elastic net with the various L1 ratios:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEGOal8mPVc3qbWcHfEfqA.png" /></figure><h3>What does Regularization achieve?</h3><p><em>Regularization, significantly reduces the variance of the model, without a substantial increase in its bias</em>. So the tuning parameter λ, used in the regularization techniques described above, controls the impact on bias and variance. As the value of λ rises, it reduces the value of coefficients and thus reducing the variance. <strong><em>Till a point, this increase in λ is beneficial as it is only reducing the variance(hence avoiding overfitting), without losing any important properties in the data.</em></strong> But after a certain value, the model starts losing important properties, giving rise to bias in the model and thus underfitting. Therefore, the value of λ should be carefully selected.</p><p>A popular library for implementing these algorithms is Scikit-learn. It has a wonderful API that can get your model up and running with <strong>just a few lines of code in python</strong>.</p><p>If you liked this article, <strong>show your support by clapping</strong> for this article below, <strong>leave a comment.</strong></p><p>You can also follow me on <a href="https://twitter.com/MuduliSumanta">Twitter</a>, <a href="http://sumanta.skm97@gmail.com/"><strong>email me directly</strong> </a>or on <a href="https://www.linkedin.com/in/sumanta-kumar-muduli-08a303198/">LinkedIn</a>. I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a31daf2acc3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bias Variance Tradeoff]]></title>
            <link>https://medium.com/almabetter/bias-variance-tradeoff-c8c2a0fb643e?source=rss-5fe9a4ce63c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8c2a0fb643e</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sumanta]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 20:42:28 GMT</pubDate>
            <atom:updated>2021-04-17T11:41:22.797Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey guys, today we are going to talk about a very important concept of ML which is used all across the machine learning realm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*2a_FwnVl_VO2ZqWn.jpg" /></figure><h4><strong>What is Bias?</strong></h4><p>Bias is a measure of error that is calculated between the average prediction and the correct value. It is also known as <strong>Bias Error</strong>. It is the measure of how far predictions are from the original value. A high bias in the model could cause an algorithm to miss the relevant relations between features and the dependent variable(target variable). A high bias means our model is not efficient in predicting our target variable.</p><p>A model having high bias suffers from underfitting.</p><p><strong>What is Variance?</strong></p><p>Variance is the dispersion of our dataset or we can say it measures how spread out our data set is. Variance is the amount that the estimate of the target function will change when it sees new data(which is not seen by the model).</p><p>A model having high variance suffers from overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*r0pPnE_QrXsPNbvDGAqYYA.png" /></figure><h4><strong>Bias And Variance Tradeoff:</strong></h4><p>Before going to bias and variance tradeoff, What is the objective of every ML algorithm? We want to predict something about unseen data(new data) from past pattern of data or the past insights. So before rolling out a model we evaluate our model, how it is going to perform on new unseen data which are called test data.</p><p><strong>Error=Irreducible error+bias²+variance</strong></p><p>Error has three terms. We have already talked about bias and variance, let’s talk about the irreducible error. <strong><em>Irreducible error</em></strong><em> </em>is an error that is random or could say <em>our all features don’t define our target variable completely</em>. Some errors that affect our predictions about the target variable which are random in nature, but that is little. We don’t have any control over irreducible error.</p><p>The only way to minimize error is by reducing <strong><em>Reducible error</em></strong>. Again it has two components.</p><p>Let’s talk about their behavior means how they are increasing or decreasing for model complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QPOQrv6TZm6FVMd1.png" /></figure><p>From the above figure, we can see that bias is decreasing with an increase in model complexity which is obvious because in the underfitting region predicted value and actual value will differ by a large extent.</p><p>Variance is increasing with increasing the model complexity because of overfitting. It will try to catch every data points including noise also, which when tested against test data fails to predict because of the presence of noise and random pattern in the model.</p><p>Test error consists of bias², variance and irreducible error. To minimize error we have to do a tradeoff between bias and variance. For that, we have to find out a proper balance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*W4l_ij18TBwoKrHbAzgZ8Q.png" /></figure><p><strong>Train Error:</strong></p><p>As we will increase the model complexity our training error is going to reduce as we with an increase in complexity, are overtraining our model. Means our model memorize training data set. In simple words our model will overfit our training data, as result, our training error will go on decreasing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WNeOZzDFUMC3N1Mg.png" /></figure><h4><strong>Conclusion-</strong></h4><p>To minimize error in our prediction about unseen data we have to choose an optimum complexity level of our model to properly balance these two terms in the test error that are bias² and variance, which is called <strong><em>bias and variance tradeoff</em></strong><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8c2a0fb643e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/bias-variance-tradeoff-c8c2a0fb643e">Bias Variance Tradeoff</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[Linear Regression]]></title>
            <link>https://medium.com/geekculture/linear-regression-939262ea5b83?source=rss-5fe9a4ce63c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/939262ea5b83</guid>
            <category><![CDATA[linear-regression-python]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sumanta]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 07:31:34 GMT</pubDate>
            <atom:updated>2021-04-10T22:04:37.970Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>What is Regression?</strong></h4><p>Regression is something where we predict the value of some dependent variable based on the independent variable, which is continuous nature.</p><p>Let’s take an example, suppose we want to predict the share price of a company, we know many factors influence share price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*d6i3QROVb8R76ZJstOvpjA.png" /><figcaption>source -mymoneysage</figcaption></figure><p>We want to find a function that could create a relationship between these factors and share price.</p><h4><strong>Linear Regression</strong></h4><p>When it comes to the most simplistic model in Machine Learning, the first thing that comes to mind is linear regression. Though it may seem somewhat pale compared to today’s modern algorithms, linear regression is still a very useful and widely used statistical learning method.</p><p><strong>Mathematically linear regression looks like</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/0*2qTQ_jhd_2r4yjhw" /></figure><p><strong>Where:</strong></p><ul><li>Y is our target variable(dependent variable)</li><li><em>β values are called </em>model coefficients. These values are learning during model training.</li><li><em>β0</em> is the intercept</li><li><em>β1, βn</em> are the coefficients for <em>X1, Xn features respectively.</em></li></ul><h4><strong>Loss Function:</strong></h4><p>When we build our model, we mainly focus on minimizing error from our estimated predictions. That is what we consider a rule for building our model. A cost function is a function that measures the total sum of squared errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/0*PjukdPTPJS9MKXOr" /></figure><h4><strong>Model Training:</strong></h4><p>Model training is a process where we define the relationship between features and target variable by selecting model parameters. Model parameters are the function constants that are <em>β0,β1,β2…βn etc.</em></p><p><strong>How we calculate those parameters?</strong></p><p>In high school, we have learned, how to calculate the optimum value of a function in calculus. Here, we want to find out the optimum value of the loss function and for the optimum value of function, we are interested in finding out function parameters. For that task there’s a mathematical algorithm called<strong> Gradient Descent</strong>, I’m not going through details now but here is an outline of what it does:</p><ul><li>Start with some values of the coefficients/parameters, eg. <em>β0</em>=0, <em>β1</em>=0</li><li>Keep changing <em>B0</em> and <em>B1</em> to reduce the J(<em>B0, B1</em>) until we hopefully end up at a minimum.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eoi0PxhbByMZdXyNx-juWA.png" /><figcaption>representative image of how we reach global minima starting from a random point by using <strong>gradient descent</strong></figcaption></figure><h4><strong>Assumptions of linear regression-</strong></h4><ul><li>There should exist a linear relationship between dependent and independent variables.</li><li>Mean residuals should be zero or close to zero which ensures that the fitted line is our <strong>“<em>best-fit”</em> </strong>line<strong>.</strong></li><li>There should be <strong><em>homoscedasticity or equal variance</em></strong> around our regression line. Heteroscedasticity is just the opposite of homoscedasticity, which shows the uneven distribution of data points across the regression line.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*K6JdRHaDlkmCT_o5.png" /></figure><ul><li>There should not be <strong>multicollinearity</strong> in the regression model. It means no two independent variables should be correlated. In simple words, one independent variable shouldn’t be predicted from other independent variables.<strong><em> VIF</em></strong> is a commonly used tool to detect whether multicollinearity exists in a regression model. It measures how much the variance (or standard error) of the estimated regression coefficient is inflated due to collinearity.</li></ul><p>VIF can be calculated by the formula below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*R8aR5XpqPD0S4UQ5.png" /></figure><p>Where <strong>Ri2 </strong>represents the unadjusted coefficient of determination for regressing the ith independent variable on the remaining ones. The reciprocal of VIF is known as <strong>tolerance</strong>. Either VIF or tolerance can be used to detect multicollinearity, depending on personal preference.</p><h4><strong>Model Evaluation Matrix:</strong></h4><p>1. <strong>Mean Squared Error(MSE): </strong>Mean Square Error is an absolute measure of the goodness for the fit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*CXWdvgutXhBVsUpK.png" /></figure><p>Mean Square Error formula</p><p>MSE is calculated by the sum of the square of prediction error which is real output minus predicted output and then divide by the number of data points. It gives you an absolute number on how much your predicted results deviate from the actual number. You cannot interpret many insights from one single result but it gives you a real number to compare against other model results and help you select the best regression model.</p><p><strong>2.</strong> <strong>Root Mean Square Error(RMSE)</strong> is the square root of MSE. It is used more commonly than MSE because firstly sometimes MSE value can be too big to compare easily. Secondly, MSE is calculated by the square of error, and thus square root brings it back to the same level of prediction error and makes it easier for interpretation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/0*caR9XQDIpzzSlSZW" /></figure><p><strong>3. Mean Absolute Error(MAE):</strong></p><p>Mean Absolute Error(MAE) is similar to Mean Square Error(MSE). However, instead of the sum of the square of error in MSE, MAE is taking the sum of the absolute value of error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*5CckhO_sGjeTFRX4" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*gEuusDkU2KZsTym4.png" /></figure><p>Mean Absolute Error formula</p><p>Compare to MSE or RMSE, MAE is a more direct representation of sum of the error terms. <strong>MSE gives larger penalization to big prediction error by square it while MAE treats all errors the same</strong>.</p><p><strong>4.</strong> <strong>R Square/Adjusted R Square:</strong></p><p>R Square measures how much variability in the dependent variable can be explained by the model. It is the square of the Correlation Coefficient(R) and that is why it is called R Square.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*T55f1MiQVnBD4rAJ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/0*-qPpyGU2Cxe1vrp4.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*6y4VKykwZlkkMOXqCZTK1g.png" /></figure><p>R square formula</p><p>R Square is calculated by the sum of squared of prediction error divided by the total sum of the square which replaces the calculated prediction with mean. R Square value is between 0 to 1 and a bigger value indicates a better fit between prediction and actual value.</p><p>R Square is a good measure to determine how well the model fits the dependent variables. <strong>However, it does not take into consideration of overfitting problem</strong>. If your regression model has many independent variables, because the model is too complicated, it may fit very well to the training data but performs badly for testing data. That is why Adjusted R Square is introduced because it will penalize additional independent variables added to the model and adjust the metric to prevent overfitting issue.</p><p><strong>Range:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/0*dO6LziPh8bG-Z_6J" /></figure><p>It more often takes a value between (0,1).</p><p><strong><em>Interpretation R²:</em></strong> If the R² score is 0.8 that means 80% variance of the target variable could be predicted from the variance of independent variables.</p><p><strong>5. Adjusted R²:</strong></p><p>It is very similar to the R² score but adjusted R² does not suffer from the problem that the score improves on increasing features(independent variables) just in contrast to R².</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*nv5Yx2Fi2tw66ZnRBGy2NQ.png" /></figure><p>Where:</p><p>n=number of observation</p><p>k=number of the independent variables</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=939262ea5b83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/linear-regression-939262ea5b83">Linear Regression</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Machine Learning]]></title>
            <link>https://medium.com/almabetter/introduction-to-machine-learning-d6535b5b058a?source=rss-5fe9a4ce63c1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6535b5b058a</guid>
            <category><![CDATA[machine-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sumanta]]></dc:creator>
            <pubDate>Wed, 31 Mar 2021 13:10:27 GMT</pubDate>
            <atom:updated>2021-04-23T16:37:44.670Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*o2Kf9lMQ-V2W0P8E_NccNA.png" /></figure><h3><strong>What is machine learning?</strong></h3><p>Before discussing machine learning let’s understand how a baby learns? We all have crossed our childhood age. When we came to this universe for the first time we are unconscious then slowly we tried to understand our environment. No doubt we learned everything from our experience. For example, when we saw a bathtub for the first time parents told us it’s a bathtub and used for bathing, at that time our brain captured some features of a bathtub like maybe anything that contains water. The next time when we saw a pond our brain recognized it as a bathtub as it has water, but our parents rectified our mistakes telling us that it’s a pond don’t bath there it’s dangerous in that time our brain created more features to differentiate between a pond and bathtub maybe like the pond is bigger. The next time when we saw a river we thought it’s a pond as it’s bigger than a bathtub but, our parents rectified telling us that it’s a river. Then our brain created more features to differentiate between pond and river maybe like its shape or moving water etc. It’s pretty much clear that human learns from their experiences.</p><p>In simple words, we could say Machine learning is a field of study where we enable machines to learn from experiences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*ln4B-s9f1Qvn1ND9EEeSMA.png" /></figure><h3>Classification of machine learning?</h3><p>Machine learning could be classified into 3 categories.</p><p>1.<strong> Supervised Learning</strong></p><p>2.<strong> Unsupervised Learning</strong></p><p>3. <strong>Reinforcement learning</strong></p><h4>Supervised Learning-</h4><p>The name supervised learning itself suggests machine learns in the presence of a supervisor. In the process, we train the machine with some data that is already labelled correctly. Post this, some new sets of data are given to the machine, expecting it to generate the correct outcome based on its previous analysis of the labelled data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/0*YAPRQilGjcNUXqTN.png" /></figure><p><strong>Steps involved in supervised learning-</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KA-cEO3knsWgsaUsez4eg.png" /></figure><p><strong>Supervised machine learning could be again classified into</strong></p><ol><li><strong><em>Regression </em></strong>— In regression analysis our dependent variable(desired output) could take any continuous value. For example, predicting car price, home rent, weather etc.</li><li><strong><em>Classification</em></strong>-In classification analysis our dependent variable could take only few fixed set of values. Example- Malware detection, spam detection, fraud detection etc.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*RelTwabFELf6kwW7XScPpA.png" /><figcaption>difference between classification and regression</figcaption></figure><h3>Unsupervised learning-</h3><p>Unsupervised learning is the training of a machine using information that is neither classified nor labeled and allowing the algorithm to act on that information without guidance. Here the task of the machine is to group unsorted information according to similarities, patterns, and differences without any prior training of data.</p><p><strong>Clustering</strong>-</p><p>Clustering is a data mining technique which groups unlabeled data based on their similarities or differences. Clustering algorithms are used to process raw, unclassified data objects into groups represented by structures or patterns in the information. Clustering algorithms can be categorized into a few types, specifically exclusive, overlapping, hierarchical, and probabilistic. Example — Document Identification, Customer segmentation, Insurance fraud detection etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cWC788kE_gOakMlg.png" /></figure><h3>Reinforcement learning-</h3><p>Reinforcement learning is an area of Machine Learning. It is about taking suitable action to maximize reward in a particular situation. It is employed by various software and machines to find the best possible behavior or path it should take in a specific situation. Reinforcement learning differs from the supervised learning in a way that in supervised learning the training data has the answer key with it so the model is trained with the correct answer itself whereas in reinforcement learning, there is no answer but the reinforcement agent decides what to do to perform the given task. In the absence of a training dataset, it is bound to learn from its experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dqxeoc0uyh9THEZ0.png" /></figure><h3>How they are different ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*8HbfeyMYpiZ5r8D8hAho2A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6535b5b058a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/almabetter/introduction-to-machine-learning-d6535b5b058a">Introduction to Machine Learning</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>
    </channel>
</rss>