<?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 Navaneeth Sharma on Medium]]></title>
        <description><![CDATA[Stories by Navaneeth Sharma on Medium]]></description>
        <link>https://medium.com/@navaneethsharma?source=rss-1fb61a861dae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EF1-KnmASQmaih4CMJeFJQ.png</url>
            <title>Stories by Navaneeth Sharma on Medium</title>
            <link>https://medium.com/@navaneethsharma?source=rss-1fb61a861dae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 08:35:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@navaneethsharma/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[Exploring Vector Databases]]></title>
            <link>https://navaneethsharma.medium.com/exploring-vector-databases-451f891b8565?source=rss-1fb61a861dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/451f891b8565</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Navaneeth Sharma]]></dc:creator>
            <pubDate>Thu, 22 May 2025 16:45:01 GMT</pubDate>
            <atom:updated>2025-05-22T16:45:01.756Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_SfyMhDEkFA_IUadKtszQ.jpeg" /></figure><p>Vector database is storage that is useful for storing vectors and embedding specially got popular for LLM embedding storage purposes. Also, for search similar words/sentences or images this is most useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*9z2A05_LXmW1ydAIF1AABA.png" /></figure><p>In first principles, it is basically built by a huge chunk of matrix with n x d, where n is the number of documents/rows and d is the dimension.</p><p>If you know, normally text and image embeddings are typically a square matrix eg: 300x300 .. to store in vec db normally it is flattened to 1D vector of length 1x90000.</p><p>The most common uses cases include the text similar search. for this the search needs be very fast. In relational databases we have concept of indexing, before hand we create a sorted indices to be able to search faster at runtime. Here, similar to indices there are some approaches developed.</p><p>Vector dbs can also apply Sharding, Partitioning and Caching just like relational dbs.</p><p>The Searching in vec dbs is slightly different compared to relational/non relational dbs since the indexing is not straight forward here, so i deep dived into learning few approaches.</p><p>The search operation can be applied via nearest neighbour search as distance b/w 2 vectors conveys that 2 vectors are similar. It can highly classified into either Euclidean distance or angular distance (cosine similarity).</p><p>Brute force would be to compute each and every vector point and nearly the time complexity would be O(n x d). Slightly optimised way is to use K Nearest Neighbours algorithm using KD tree, ball tree, etc. these are to find exact k nearest vectors and can be exhaustive. So, brilliant people came up with Approximate Nearest Neighbour search.</p><p>I have explored bunch of ANNS algorithms as given in the <a href="https://arxiv.org/pdf/2310.11703">paper</a>. Dug deep into the ANNOY (Approximate Nearest Neighbours Oh Yeah) , HNSW (Hierarchical navigable small world), PQ (Product quantization). And the one of the best library <a href="https://github.com/facebookresearch/faiss/wiki/Getting-started">fiass</a> seems to be using <a href="https://github.com/facebookresearch/faiss/wiki">OPQ + HNSW</a></p><p>So, going to document only PQ and HNSW as of now. cool.</p><h3>How does Product Quantization work though ?</h3><p>As simple as it gets,</p><ol><li>have some large chunk of vectors say 100k vectors of dimension 1000,</li><li>Segregate the query embedding vector into m (let say 4) different parts</li><li>for each part calculate the centroid using k means estimator</li><li>use the centroid vector as index (100k x 4) for new search query comparison</li><li>compute the distance table centroid vs query vector for each vector, complexity would be 100k * 4 * 100. (with out PQ it would be 100k * 1000 * 100)</li><li>the bottom k distances would be the indices that are closest to the query</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8X12IsU4BT46NceB9BgZKw.png" /><figcaption>The diagrammatic representation of the algorithm</figcaption></figure><p><a href="https://www.youtube.com/watch?v=PNVJvZEkuXo">this</a> youtube video came in handy to visualize and understand the concepts into much more depth. Also there is code walkthrough to build this searching algo from scratch. To further reduce the time complexity, we can use HNSW (which is baby of NSW and skipped linked list)</p><h3>How does Hierarchical navigable small world work ?</h3><p>Hierarchical navigable small world is a graph based algorithm for NNS, its state of the art approach and can be used to efficiently find the closest vector with O(logn) complexity.</p><p>It uses the navigable small world algo, that has these steps</p><ol><li>Calculate nearest neighbour for each node while adding to the graph and connect it.</li><li>While searching randomly start from the node and navigate to least distance b/w the neighbours until none of its neighbours are closer to query i.e larger distance than current node. bingo you have reached the approximate vector you need</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*GOQ5lw1LuFzr4rgSHiFZEQ.png" /></figure><p>for understanding the skipped linked list <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2c/Skip_list_add_element-en.gif/400px-Skip_list_add_element-en.gif">this</a> gif is better than my words XD. The gif is for inserting element. but for searching the algorithm is same.. instead of inserting at correct place you end up in the correct position where element is if it exist or its nearest ones the answer in case of approximation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*d1SF5E1ImettooIB.gif" /></figure><p>Few points to note is</p><ul><li>higher the level number of connections are minimal.</li><li>The search is really fast but at the cost of the memory of maintaining the connections</li></ul><p>now for HNSW, combine both the algorithms</p><ol><li>Start from choosing a random node from top layer, since it has minimum nodes</li><li>compare the cosine similarity or distance b/w the neighbouring nodes. which ever is the highest (cosine similarity) / lowest (distance) move the pointer to that node</li><li>continue this until no neighbouring node has greater cosine similarity more that what current node and query vector has</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*VuF-FIisWMozAwsG2fWn-A.png" /><figcaption>Image is from the blog <a href="https://towardsdatascience.com/similarity-search-part-4-hierarchical-navigable-small-world-hnsw-2aad4fe87d37">https://towardsdatascience.com/similarity-search-part-4-hierarchical-navigable-small-world-hnsw-2aad4fe87d37</a> . Great explanation from author regarding the HNSW. Go check out for indepth learning of HNSW.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NZkdvWhUl_Q8mHYjLCNsxw.png" /></figure><p>The most optimal way is to combine product optimisation to reduce the search space, and HNSW for the speed. You can see from the below table that memory requirement is significantly reduced introducing the PQ, but slightly increasing the time bcz of extra computation of centroid and query vector distances for various datasets. Here is the link for the amazing <a href="https://weaviate.io/blog/ann-algorithms-hnsw-pq">blog</a> that details about the HNSW PQ experimentation details</p><p>Yo, that’s it. byee…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=451f891b8565" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes on Feature Engineering]]></title>
            <link>https://medium.com/aimonks/notes-on-feature-engineering-5a55485a75e0?source=rss-1fb61a861dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a55485a75e0</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Navaneeth Sharma]]></dc:creator>
            <pubDate>Tue, 26 Sep 2023 15:19:59 GMT</pubDate>
            <atom:updated>2023-10-02T13:49:18.786Z</atom:updated>
            <content:encoded><![CDATA[<h4>Techniques that are worth trying to engineer your data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Imf_mDQ-4yVZkbR9P28_Q.jpeg" /></figure><p>Feature Engineering is like the special sauce in data science. It’s the secret recipe that makes data more useful and powerful. It’s about making data more useful for solving problems. But the way we do it can vary depending on the specific industry or field we’re working in.</p><p>From my experience in data science, I’ve learned that having knowledge about the specific area you’re dealing with is important for effective feature engineering. It’s like knowing the ingredients and flavors in cooking. But don’t worry, there are some techniques and approaches that are useful in many situations.</p><p>In this post, I’ll share some of these techniques with you. Think of this as my personal notes from my data science journey. I’ll explain things assuming you have a basic understanding of numbers and using a computer. So, let’s dive into the world of feature engineering, where we make data work better for us!</p><p>I will be explaining most of the techniques via the ‘taxis’ dataset. This data is about the taxi of NYC provided by Seaborn. So without delay, Let’s import the libraries and load the dataset.</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><pre>df = sns.load_dataset(&#39;taxis&#39;)</pre><p>If you see the data, there are 14 columns that contain different kinds of fields including time, categorical, geo, and numerical. This will help me to explain the techniques in a better way. The `df.head()` will return the below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jpNnwrqDPbIgqLSj1QWxZQ.png" /><figcaption>Taxi Data</figcaption></figure><p>Here, we need to predict the fare price, tip, and total price. We can restrict ourselves to predict fare prices.</p><h3>Math Transformations</h3><p>Math transformations are very useful for both understanding the data and for the models to learn better. In particular, it helps tree-based models as tree-based models don&#39;t learn them directly. I use math transformations as a feature along with group by and other transformations combined as it makes more sense to understand the data better. Here are some of the techniques to list down</p><ul><li>The ratio between different numerical features</li><li>Log Transformations for Skewed Data</li><li>Mean, Median, Mode, Counts, Percentiles, Quantiles. These are most effective when used along with other techniques like Group Transformations</li></ul><p>Let me plot a couple of graphs and demonstrate why the ratio might help us understand the data better also I will use ratio transformation for the below</p><pre>sns.set_style(&#39;darkgrid&#39;)<br>plt.figure(figsize=(16,6))<br><br>plt.subplot(1,2,1)<br>sns.scatterplot(data=df, x=&#39;fare&#39; , y=&#39;distance&#39;)<br>plt.title(&#39;Distance vs fare&#39;)<br><br>plt.subplot(1,2,2)<br>sns.scatterplot(data=df, x=&#39;passengers&#39; , y=&#39;distance&#39;)<br>plt.title(&#39;Distance vs passengers&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IgTIOy8tbbKtSQw5JTnsZg.png" /></figure><pre>df[&#39;fare_per_distance&#39;] = (df.fare / df.distance).replace([np.inf, -np.inf], np.nan)<br>df[&#39;distance_per_passengers&#39;] = (df.distance / df.passengers).replace([np.inf, -np.inf], np.nan)</pre><blockquote>Side Note: The Ratio based features might be important for tree based models as they don&#39;t learn that relationship directly.</blockquote><p>Note, that we cannot use column fare_per_distance directly as we do not know the fare price. So, we need to use historical mean values for certain combinations that can help to predict the fare price. The group transformations will help us here.</p><h3>Group Transformations</h3><p>Group transformation in feature engineering refers to the process of creating new features in a dataset by aggregating or transforming existing features based on groups or categories within the data.</p><p>I have used 3 columns ‘color’,’pickup_borough’, and ‘dropoff_borough’ to get the mean fare price. Also, have pasted the output below. This gives us a good estimate of where the prices are high and low, similarly giving the model an extra derived feature.</p><pre>df[&#39;mean_fare_by_color_pickup_dropoff_borough&#39;] = df.groupby([&#39;color&#39;,&#39;pickup_borough&#39;, &#39;dropoff_borough&#39;])[&#39;fare&#39;].transform(&#39;mean&#39;)<br><br># To Print what we get<br>df.groupby([&#39;color&#39;,&#39;pickup_borough&#39;, &#39;dropoff_borough&#39;])[&#39;fare&#39;].mean()</pre><pre>color   pickup_borough  dropoff_borough<br>green   Bronx           Bronx              14.309667<br>                        Brooklyn           54.062500<br>                        Manhattan          30.879375<br>                        Queens             43.376667<br>        Brooklyn        Bronx              60.280000<br>                        Brooklyn           11.930700<br>                        Manhattan          25.116905<br>                        Queens             36.359545<br>        Manhattan       Bronx              17.093846<br>                        Brooklyn           36.000000<br>                        Manhattan           9.292703<br>                        Queens             26.907143<br>        Queens          Bronx              43.600000<br>                        Brooklyn           34.959000<br>                        Manhattan          30.728462<br>                        Queens              9.731107<br>yellow  Bronx           Bronx              16.833333<br>                        Manhattan          27.597778<br>                        Queens             30.500000<br>        Brooklyn        Bronx              49.500000<br>                        Brooklyn           11.546667<br>                        Manhattan          25.062400<br>                        Queens             26.500000<br>        Manhattan       Bronx              30.433103<br>                        Brooklyn           24.342715<br>                        Manhattan           9.751336<br>                        Queens             34.970064<br>                        Staten Island      44.500000<br>        Queens          Bronx              47.583333<br>                        Brooklyn           37.415000<br>                        Manhattan          37.737374<br>                        Queens             19.972000</pre><p>If you observe carefully, we get to know that for pickup_borough, and dropoff_borough the fare price is much less relatively. This will help the model to understand this pattern better. Also, there might be some hidden patterns like certain pickup_boroug to hdropoff_borough might have very high prices and things like that.</p><p>Here are some more transformations utilizing some more columns</p><pre># These cannot be used directly in prediction as we will not know the fare price before hand. So these must be stored in some way and loaded using the combination.<br># These are just historical values that provides context to the model,<br># also, these transformation help directly to learn the fare price. <br>df[&#39;mean_fare_by_color_pickup_dropoff_borough&#39;] = df.groupby([&#39;color&#39;,&#39;pickup_borough&#39;, &#39;dropoff_borough&#39;])[&#39;fare&#39;].transform(&#39;mean&#39;)<br>df[&#39;first_quantile_fare_by_color_pickup_dropoff_borough&#39;] = df.groupby([&#39;color&#39;,&#39;pickup_borough&#39;, &#39;dropoff_borough&#39;])[&#39;fare&#39;].transform(&#39;quantile&#39;, 0.25)<br>df[&#39;second_quantile_fare_by_color_pickup_dropoff_borough&#39;] = df.groupby([&#39;color&#39;,&#39;pickup_borough&#39;, &#39;dropoff_borough&#39;])[&#39;fare&#39;].transform(&#39;quantile&#39;, 0.5) # this is median<br>df[&#39;third_quantile_fare_by_color_pickup_dropoff_borough&#39;] = df.groupby([&#39;color&#39;,&#39;pickup_borough&#39;, &#39;dropoff_borough&#39;])[&#39;fare&#39;].transform(&#39;quantile&#39;, 0.75)<br><br>df[&#39;count_color_by_color_pickup_borough&#39;] = df.groupby([&#39;pickup_borough&#39;, &#39;color&#39;])[&#39;color&#39;].transform(&#39;count&#39;)<br>df[&#39;count_color_by_color_pickup_dropoff&#39;] = df.groupby([&#39;dropoff_borough&#39;, &#39;color&#39;])[&#39;color&#39;].transform(&#39;count&#39;)<br><br>df[&#39;mean_distance_by_color_pickup_dropoff_borough&#39;] = df.groupby([&#39;color&#39;,&#39;pickup_borough&#39;, &#39;dropoff_borough&#39;])[&#39;distance&#39;].transform(&#39;mean&#39;)</pre><p>The count feature helps the model understand the “how much of them have green color?” kind of questions.</p><p>You can try other combinations and get exciting insights for understanding the data better and introduce new group transformations to handcraft the aggregated features for the model.</p><p>Note, that we can utilize the group transformations with other techniques. We will explore that too next.</p><h3>DateTime Features</h3><p>If your data is time series data as one of the important features, then it makes sense to extract and use the divide and conquer approach to get more insights and to get better results via models.</p><h4><strong>Extracting Components</strong></h4><p><strong>Generic Components:</strong> Timestamps can be broken down into Year, Month, Day, Hour, Minute, and Second. Extract these components from the DateTime to create separate features for each. For example, you can break down a timestamp like “2023–09–17 14:30:00” into Year=2023, Month=9, Day=17, Hour=14, Minute=30, and Second=0. It also depends on the problem, If you have only one month of data then, year and month don’t make sense as both will likely be the same.</p><p><strong>Meta Data Components:</strong></p><ul><li><strong>Week and Day of Year:</strong> Calculate the day of the week (Monday, Tuesday, etc.) and day of the year (e.g., 1 to 365) from the DateTime.</li><li><strong>Is Weekend or Weekday: </strong>Create a binary feature indicating whether a date falls on a weekend (Saturday or Sunday) or a weekday.</li><li><strong>Is Holiday: </strong>Create a binary feature indicating whether a date is a holiday. You can maintain a list of holidays relevant to your dataset.</li><li><strong>Time Since an Event: </strong>Calculate the time elapsed since a specific event or reference point. For instance, you can compute the number of days since the last major holiday.</li></ul><p><strong>Time Differences: </strong>Compute the time difference between two DateTime features. For example, calculate the time between two consecutive events.</p><p><strong>Lag Features:</strong> Create lag features by shifting values from previous time steps. This can be useful for time-series forecasting tasks.</p><p><strong>Rolling Statistics:</strong> Calculate rolling statistics (e.g., rolling mean, rolling standard deviation) over a window of time to capture trends and seasonality. This can be very useful for the model to learn the trends and utilize them to predict the labels accurately (This concept is similar to moving averages).</p><p><strong>Encoding Special Events:</strong> Encode special events or holidays as categorical features. This can be helpful for models to learn the impact of these events. For instance, a launch/rebranding event of a product results in an increase in sales quickly.</p><p><strong>Time-Based Aggregations:</strong> Create features by aggregating data over time intervals (e.g., hourly, daily, weekly, and event-based). For instance, compute the average daily sales.</p><p>Remember that the choice of feature engineering techniques depends on the specific problem and dataset you are working with. It’s essential to understand the domain and the nature of your data to engineer DateTime features effectively.</p><p>Now, let&#39;s apply what we learned to the data we have</p><pre># Time Components<br>df[&#39;pickup_hour&#39;] = df.pickup.dt.hour<br>df[&#39;dropoff_hour&#39;] = df.dropoff.dt.hour<br>df[&#39;pickup_day&#39;] = df.pickup.dt.day<br>df[&#39;dropoff_day&#39;] = df.dropoff.dt.day<br>df[&#39;pickup_weekday&#39;] = df.pickup.dt.weekday<br>df[&#39;dropoff_weekday&#39;] = df.dropoff.dt.weekday<br>df[&quot;pickup_is_weekend&quot;] = df.pickup.dt.dayofweek &gt; 4<br>df[&quot;dropoff_is_weekend&quot;] = df.dropoff.dt.dayofweek &gt; 4<br><br># Time Difference between pick up and drop off<br>df[&quot;time_diff_mins_pickup_dropoff&quot;] = (df.dropoff - df.pickup).dt.total_seconds() / 60</pre><p>Here’s a plot of fare vs. time difference in minutes. You can see that there is a generic trend of increase in fare price as the time difference increases. That trend is captured for the model via this feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0RCyXxL_7k9pBJfJktS5nA.png" /></figure><p>We can utilize the rolling method provided by pandas to get some useful aggregations that can help determine the output.</p><pre># creating a new dataframe<br>df_time_indexed = df.copy(deep=True)<br>df_time_indexed.set_index(&#39;pickup&#39;, inplace=True)<br>df_time_indexed.sort_index(inplace=True)<br><br># replace the hour you want to explore the data for<br>rolling_window_size_hours = 2<br>df_time_indexed.fare.rolling(window=f&#39;{rolling_window_size_hours}H&#39;).mean()</pre><p>The above code will get the mean fare price for the previous 2 hours, this gives a rough estimate of how the price is trending. Note that we can utilize the group by functions and then apply the rolling function to get a better trend of the fare price to make the price suitable for real-time. For instance, consider the below example for utilizing both ‘group by’ and rolling functions where I will group the data by color and calculate the moving/rolling mean for the previous 2 hours.</p><pre>grouped = df_.groupby([&#39;color&#39;])[&#39;fare&#39;]<br><br>rolling_window_size_hours = 2<br>rolling_means = grouped.rolling(window=f&#39;{rolling_window_size_hours}H&#39;).mean().reset_index()<br><br>rolling_means.rename(columns={&#39;fare&#39;: &#39;rolling_mean&#39;}, inplace=True)</pre><p>These are major approaches I have for the Date time as part of feature engineering. Now, let’s dive into the next section.</p><h3>Categorical Encodings</h3><p>Encoding categorical variables can be as easy as converting them into continuous integers for unique values, but there are some techniques that can influence the model&#39;s performance having some extra steps.</p><h4>Target Encoding (Mean Encoding):</h4><p>Mean encoding assigns each category in a categorical feature the mean of the target variable for that category. It can help capture the relationship between the category and the target variable.</p><p>I will take a simple example to explain Target Encoding. This approach is a powerful way to encode rather than a normal label encoder. We get some advantages including</p><ol><li><strong>Preserves Information</strong>: Unlike one-hot encoding, which can lead to a high-dimensional and sparse feature space, target encoding preserves the information present in categorical variables by representing them as continuous values. This can lead to more efficient use of data.</li><li><strong>Handles High Cardinality</strong>: When dealing with categorical variables with a high number of unique categories (high cardinality), target encoding can be especially useful. One-hot encoding of such variables would result in a massive increase in dimensionality, potentially leading to overfitting. Target encoding allows you to encode such variables effectively.</li><li><strong>Captures Relationships:</strong> Target encoding explicitly captures the relationship between the categorical feature and the target variable. By taking the mean of the target variable for each category, it encodes information about how the target variable varies with different categories. This can be particularly helpful when there is a clear correlation between the categorical variable and the target.</li><li><strong>Reduces Noise:</strong> In noisy datasets, target encoding can help reduce the noise associated with individual data points. By aggregating the target variable over categories, the encoding becomes more stable and less sensitive to individual outliers or noisy observations.</li></ol><p>For classification, we can use the target encoding in the below approach</p><pre>import pandas as pd<br><br># Sample data for multi-class classification<br>data = pd.DataFrame({&#39;Category&#39;: [&#39;A&#39;, &#39;B&#39;, &#39;A&#39;, &#39;C&#39;, &#39;B&#39;, &#39;A&#39;],<br>                     &#39;Target&#39;: [&#39;Class1&#39;, &#39;Class2&#39;, &#39;Class1&#39;, &#39;Class3&#39;, &#39;Class2&#39;, &#39;Class1&#39;]})<br><br># Calculate the mean target value for each category<br>category_means = data.groupby(&#39;Category&#39;)[&#39;Target&#39;].value_counts(normalize=True).unstack().fillna(0)<br><br># Encode the &#39;Category&#39; column using the calculated means<br>data[&#39;Category_encoded&#39;] = data[&#39;Category&#39;].map(category_means.mean(axis=1))</pre><p>Here, based on the value counts we try to encode the category. Note, that this code doesn&#39;t handle all the cases like having the same value counts. There are ways to handle it, also ‘sklearn’ provides some methods to find target encoded values. Below is the approach for regression.</p><pre>import pandas as pd<br><br># Sample data for regression<br>data = pd.DataFrame({&#39;Category&#39;: [&#39;A&#39;, &#39;B&#39;, &#39;A&#39;, &#39;C&#39;, &#39;B&#39;, &#39;A&#39;],<br>                     &#39;Target&#39;: [10, 15, 12, 8, 14, 9]})<br><br># Calculate the mean target value for each category<br>category_means = data.groupby(&#39;Category&#39;)[&#39;Target&#39;].mean()<br><br># Encode the &#39;Category&#39; column using the calculated means<br>data[&#39;Category_encoded&#39;] = data[&#39;Category&#39;].map(category_means)</pre><p>I need to also mention that this method would not be useful if the data is Imbalanced, and if not applied correctly it might cause data leakage.</p><h3>Embeddings</h3><p>Text embedding is a crucial step in natural language processing (NLP) and feature engineering. It involves converting textual data into numerical vectors that machine learning algorithms can understand and process. Utilizing the embeddings we can use algorithms like PCA, and t-SNE to visualize how relevant the text is for the use case.</p><p>There are several techniques for text embedding, each with its advantages and use cases. Here are some common techniques:</p><h4>Bag of Words (BoW):</h4><ul><li>BoW represents a text by creating a vocabulary of unique words in the corpus and then counting the frequency of each word in a document.</li><li>It generates a sparse vector where each dimension corresponds to a unique word, and the value represents the word’s frequency.</li><li>BoW doesn’t consider word order or semantics but can capture important information about the presence of words.</li></ul><h4>Term Frequency-Inverse Document Frequency (TF-IDF):</h4><ul><li>TF-IDF is a variation of BoW that considers not only the frequency of words in a document but also their importance in the entire corpus.</li><li>It assigns a weight to each word based on how frequently it appears in a document (TF) and inversely with its occurrence in the entire corpus (IDF).</li><li>TF-IDF helps in identifying the most important words in a document and is commonly used for information retrieval and text classification tasks.</li></ul><h4>Word Embeddings (e.g., Word2Vec, GloVe, FastText):</h4><ul><li>Word embeddings represent words as dense vectors in a continuous vector space.</li><li>These embeddings capture semantic relationships between words and can be pre-trained on large text corpora or trained specifically for the task at hand.</li><li>They are useful for tasks that require an understanding of word semantics, such as sentiment analysis and document clustering.</li></ul><h4>BERT (Bidirectional Encoder Representations from Transformers):</h4><ul><li>BERT is a deep transformer-based model pre-trained on a massive amount of text data.</li><li>It generates contextualized word embeddings by considering the surrounding words in a sentence.</li><li>BERT embeddings are state-of-the-art and have significantly improved performance on various NLP tasks, such as question answering, text classification, and named entity recognition.</li></ul><p>Choosing the right text embedding technique depends on the specific NLP task and the nature of the data. It’s common to experiment with multiple techniques to find the one that works best for a given problem and data. Additionally, fine-tuning embeddings or combining multiple embedding methods can also improve performance in many cases.</p><p>In conclusion, feature engineering is a critical aspect of data science that can greatly impact the performance of machine learning models. Though the techniques explained can extract valuable information from our data, improve model interpretability, and enhance predictive accuracy, it’s important to remember that feature engineering is not a one-size-fits-all process. The choice of techniques should be guided by a deep understanding of the domain and the specific characteristics of the dataset. Experimentation and iteration are key to finding the most effective features for a given problem.</p><p>Ultimately, feature engineering is both an art and a science, requiring creativity, domain expertise, and a solid grasp of data manipulation tools.</p><p>That’s it for this time. See you in the next post :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a55485a75e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aimonks/notes-on-feature-engineering-5a55485a75e0">Notes on Feature Engineering</a> was originally published in <a href="https://medium.com/aimonks">𝐀𝐈 𝐦𝐨𝐧𝐤𝐬.𝐢𝐨</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Technologies I used as a Full Stack Developer in recent time]]></title>
            <link>https://navaneethsharma.medium.com/technologies-i-used-as-a-full-stack-developer-in-recent-time-af85960197a8?source=rss-1fb61a861dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/af85960197a8</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Navaneeth Sharma]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 10:07:03 GMT</pubDate>
            <atom:updated>2023-01-26T10:07:03.695Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Also, the insights I got from using those techs.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RZPzw0uM_60lnMnS" /></figure><p>The world of technology is like a never-ending rollercoaster ride, with new tools and frameworks popping up every other day. As a Full stack developer, it’s my job to keep my finger on the pulse of what’s new and exciting in the tech landscape. In this post, I’ll be taking you on a journey through my tech stack, sharing my experience and insights on the tools and frameworks that have caught my attention and why they have the potential to change the game. From Python and Javascript to HTMX, Alpine JS, and Firebase, let’s dive in and explore what I got for you.</p><h3>Backend Techs</h3><p>Let me start from the backend, I have majorly contributed to python codes for my day job. So, will be a little biased on that. But, I have used javascript for my side projects which I am proud of. So not to worry about that :)</p><h4>1. Django</h4><p>Django is a pretty powerful python framework and has been used by giants like Instagram, Pinterest, etc as their backend. Also, I love to work in python. Majorly my time was spent working on useful functions and creating Django models, views, and testing. The main advantage of using Django is we can integrate ML models easily with python. I also had to implement Pytorch models for internal use (Was hired as an ML Engineer initially, then shifted to Full Stack XD ). I also had to build some applications using Django like google Calendar events manager. Python helped me a lot while building this. The testing of this and logging is easily integrable in Django, So debugging was easier. Also, there is an awesome CMS (Content Management System) Library in python called <a href="https://wagtail.org/">wagtail</a>. It’s very powerful and the learning curve was not that steep if you are used to Django.</p><p>Key takeaways that I learned while developing in Django are</p><ul><li>Unit testing is key to ensuring that your code doesn’t break when updated in the future. Django has a <a href="https://docs.djangoproject.com/en/4.1/topics/testing/overview/">Testcase module</a>. You could utilize that.</li><li>Logging helps a lot in debugging. Use Logging functions as mentioned <a href="https://docs.djangoproject.com/en/4.1/howto/logging/">here</a>.</li><li>Dealing with Views and URLs .py files could be tricky. Be a little cautious while dealing with a lot of view functions and URLs</li><li>Using Django Models is easy. But dealing with tons of migrations might be hard. So, Try to develop the model structure initially with some caution.</li></ul><h4>2. Node.js</h4><p>As of now, I have used node only a handful of times as the backend. So, take my points with pinch of salt. Majory used the Node including Express in my side projects. Only used it when I need to create simple APIs for CRUD operations from the database. But, building that is very easy, and recommend node as a backend if you want to create scalable things with simplicity. Django had tons of files to manage and for a beginner, it could be confusing. Node is always recommended in that sense. Also, Using Express and Node Stack is kinda tradition now.</p><h4>3. Backend as a Service Tools</h4><p>I have used <a href="https://firebase.google.com/">Firebase</a> and <a href="https://appwrite.io/">Appwrite</a> tools as of now. Both tools are good. Appwrite has an upper hand on being open source &amp; its documentation whereas Firebase has a first-mover advantage (Also, can be free for while, Appwrite requires a server). Used it in my personal projects where I needed authentication and simple data storage. Generally, I prefer to use it when I can do almost stuff via frontend.</p><h3>Databases</h3><p>So here are some of the databases I worked on in the recent past.</p><h4>1. Postgres</h4><p>Postgres is a fantastic relational database management system. I’ve had the chance to implement it in multiple projects and it has never failed to impress me. The main advantage of Postgres is its support for advanced data types such as arrays and hstore, which allows for more efficient data storage and querying. I also found the SQL syntax to be quite similar to that of other popular RDBMSs like MySQL, which made it easy to pick up and start working with. One of the key takeaways I learned while working with Postgres is the importance of designing a proper database schema. The more thought you put into designing your tables and relationships, the more efficient your queries will be and the easier it will be to maintain your data in the long run.</p><h4>2. Redis</h4><p>Redis is a powerful in-memory data structure store. I have used it on a few projects where I needed a high-performance data store that could handle large amounts of data. The main advantage of Redis is its ability to handle high-speed data operations, making it perfect for use cases such as real-time analytics and message queues. I found the Redis data structures to be easy to work with and the documentation to be very helpful. One key takeaway I learned while working with Redis is the importance of understanding the trade-offs between data consistency and performance. Redis is often used as a caching layer, so it’s essential to understand how data is stored and how it can be invalidated.</p><h4>3. SQLite</h4><p>SQLite is a lightweight and efficient relational database management system. I have used it on a few projects where I needed a simple and easy-to-use database that could be embedded within an application. The main advantage of SQLite is its small footprint and the ability to work with it without the need for a separate server. It’s perfect for use cases such as small web applications and mobile apps. Also, for testing out your Django models SQlite is best. While it’s ideal for small projects, it may not be suitable for large-scale projects that require high performance and scalability.</p><h3>Frontend Techs</h3><p>As I come from a pythonic background, the Frontend has always been the least priority for me. But since last year my perspective has changed a lot on Frontend. I have Implemented multiple pieces of stuff in different tools. The direction of the full stack seems to change… You need to be good at frontend than backend because there are tools that can replace the backend but till now there are not many tools that can replace frontend. I have worked on both popular and things that are getting popular tools. So, here is my list and insights.</p><h4>1. <a href="https://htmx.org/">HTMX</a></h4><p>HTMX is a new and exciting technology that allows for dynamic updates on the web page without the need for a full page refresh. I have used it at my day job and found it to be a game changer in terms of improving the user experience. The main advantage of HTMX is its ability to handle complex interactions and data updates with minimal effort. I had to build an animation player using HTMX and Django it was pretty cool once it got completed. One key takeaway I learned while working with HTMX is the importance of understanding how it works under the hood. While it can simplify your code, it’s essential to know how it’s handling requests and updates to avoid potential issues.</p><h4>2. <a href="https://alpinejs.dev/">Alpine JS</a></h4><p>Alpine JS is a lightweight JavaScript framework that allows for easy manipulation of the DOM. I have used it on a few <strong>low Frontend required projects</strong> and found it to be a great alternative to larger frameworks like Vue and React. The main advantage of Alpine JS is its simplicity and the ability to get started quickly. You can literally use it by just adding a script tag in your HTML. The Store and Ref in the alpine are game-changing and are powerful for small to medium-sized projects. You can think of it as a modern jquery. I found the documentation to be excellent and the learning curve to be relatively low. Generally, my recommendation is to use alpinejs framework only when you have very limited frontend complexity and you expect basic to medium stuff from the frontend.</p><h4>3. <a href="https://reactjs.org/">React</a></h4><p>React is a popular JavaScript library for building user interfaces. I have used it on a number of projects and found it to be a great tool for building complex and interactive web applications. The main advantage of React is its ability to handle complex state and data updates in a performant manner. Documentation is awesome but has a learning curve relatively steep. Key takeaways that I learned while developing in Django are</p><ol><li>Component-based architecture: React uses a component-based architecture, which allows developers to break down a user interface into smaller, reusable pieces. This makes it easier to build and maintain large and complex applications.</li><li>Virtual DOM: React uses a virtual DOM to optimize updates and reduce the number of actual DOM mutations that need to be made. This allows React to update the page efficiently and avoid unnecessary re-renders of components.</li><li>JSX: React uses JSX. JSX makes it easy to write HTML-like elements in JavaScript, and it’s a powerful tool for building user interfaces.</li><li>React Hoooks: I have found React Hooks to be an incredibly useful tool in my development arsenal. The simplicity of the syntax and ability to manage state and side effects in functional components.</li><li>Structure: Working on large projects in react could lead to tons of components. So be a little cautious and try to keep it minimal and document things properly.</li></ol><h4>4. <a href="https://hyperscript.org/">Hyperscript</a></h4><p>Hyperscript is a lightweight JavaScript library for creating and manipulating the DOM. I have used it on a few projects and found it to be a great alternative to other libraries like jQuery. The main advantage of Hyperscript is its simplicity and the ability to get started quickly. With the combination of HTMX and hyper script along with Django, jinja templates are powerful, you can avoid using the heavy frontend like react, and Vue.</p><h4>5. <a href="https://tailwindui.com/">Tailwind CSS</a></h4><p>Here comes one of my favorite CSS frameworks. Tailwind CSS is a utility-first CSS framework that allows for easy styling of web pages. I have used it on a ton of projects. The main advantage of Tailwind CSS is its ability to handle complex styling with minimal code. I found the documentation to be an excellent resource. And the community is very large. One key takeaway I learned while working with Tailwind CSS is the importance of understanding how it works under the hood. While it can simplify your styling code, it’s essential to know how it’s handling classes and updates to avoid potential issues. Also, Structuring the tailwind is crucial as the project becomes large maintaining your code can be tricky. So keep an eye on the code you write and remove unnecessary CSS (it could be messy if you have a ton of things in one place)</p><h3>Conclusion</h3><p>In conclusion things, I have explored some of the stuff in full stack till now. I haven’t covered the DevOps tools like Docker, Kubernetes, Github actions and workflows, etc. Also, the community loved frontend tech Svelte. I had worked on the ML stuff also, So that could be included as well… But I think this blog is pretty long and will try to cover those in the next blog hopefully.</p><p>Until then, take care and bye :)</p><p><em>Originally published at </em><a href="https://navaneethsharma.hashnode.dev/technologies-i-used-as-a-full-stack-developer-in-recent-time"><em>https://navaneethsharma.hashnode.dev</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af85960197a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers (Quick Revision)]]></title>
            <link>https://navaneethsharma.medium.com/transformers-quick-revision-c00cc6a43938?source=rss-1fb61a861dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/c00cc6a43938</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[attention]]></category>
            <dc:creator><![CDATA[Navaneeth Sharma]]></dc:creator>
            <pubDate>Fri, 22 Jul 2022 17:46:01 GMT</pubDate>
            <atom:updated>2022-07-22T17:47:27.338Z</atom:updated>
            <content:encoded><![CDATA[<p>Self-Attention and Transformers Revision</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BJAzg35kTlMmyrTM.jpg" /><figcaption>Source: Google</figcaption></figure><p>Welcome back! This blog is the part of the Data Science/Machine Learning Series. Today we are going to discuss Self Attention and Transformers of Deep Learning. If you have missed the previous blogs, you can catch up on those <a href="https://navaneethsharma.medium.com/list/data-science-ml-revision-series-c6a6610c13bc">here</a>.</p><h3>The Intuition</h3><p>Transformer is a ground breaking research which changed the trajectory of Deep Learning. This is a revision series, so I assume you have learnt the Transformers previously. So, getting into the basics let’s start with the basic block diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*Dt8ISAQlmD4TbMt8xusXnQ.png" /><figcaption>Transformer Block</figcaption></figure><p>Transformer consists of two blocks,</p><ul><li>Self-Attention Block</li><li>Feed Forward Neural Network Block</li></ul><p>The advanced architectures like BERT, GPT has the transformer as their building blocks. So it is important to know the underlying math and concepts behind transformers. without further due let’s dive in. Transformers have a great advantage because it tries to understand the context of the sentence. This mainly helps to solve the problems such as machine translation, question answer chatbots and many more.</p><h3>Self-Attention</h3><p>If there is a sentence “There was a heavy rain, so dog couldn&#39;t cross the river because it was flooded with water”. Self attention makes model to associate “it” with the right word (here river). To compute the self-attention of the sentence we need to follow few steps. The inputs should be the embedding vector of the tokenized words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*7AIu7oqgJW7fUdXXQ524tg.png" /></figure><p>In Matrix form we can represent this as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*UOdtqQ191h1VpcW7pAG_VQ.png" /><figcaption>Matrix Form for the Self Attention Calculation</figcaption></figure><h4>The Multi-head attention</h4><p>The multi head attention basically adds parallel attention layers. This improves the performance of the network. The major take away of this are -</p><ul><li>It expands the model’s ability to focus on different positions</li><li>It gives attention layer multiple “representation subspaces”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*jNPKjkdvIN5FPy_tyCrnAw.png" /><figcaption>Multi-Head Attention</figcaption></figure><p>To sum up, here is the full computation of multi-head self attention</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*iQ2pVmNqLQhB5lSqMtkqIA.png" /><figcaption>Multi-head self attention</figcaption></figure><p>One of the problem of this model is, it doesn’t consider the position of the word in the sentence. This creates a problem for understanding the sentence correctly. So, we need to add a positional encoding vector. This can be done by adding positional encoding with embedding.</p><p>So, this is it for Self-attention. Let’s move on to the Transformers.</p><h3>Transformers</h3><p>Diagrammatically explaining will give better intuition for the transformers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*QFbGFWhClDy_3yl5ARSdyA.png" /><figcaption>Transformer Block — In detail</figcaption></figure><p>As you can see the embedding vector is added up with the positional encoding vector and gives as inputs for the attention block. Further the outputs are added up with the embedded inputs (skip connection concept) and then the layernorm is performed. Further, the outputs of these are fed to the Feed forward network performing the normalisation along with skip connection. This is the transformer block. The Architectures like Bert and GPT can be created by stacking this further with changes relevant to the problem statement. To learn more about Transformers thouroughly I highly recommend <a href="https://jalammar.github.io/illustrated-transformer/">Jay Alammar’s Blog</a>.</p><p>Cool! That’s it for this blog. See you next time…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c00cc6a43938" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Networks Hyper-parameters (Quick Revision)-2]]></title>
            <link>https://navaneethsharma.medium.com/neural-networks-hyper-parameters-quick-revision-2-9f10c79ae559?source=rss-1fb61a861dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f10c79ae559</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[revision]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Navaneeth Sharma]]></dc:creator>
            <pubDate>Fri, 10 Dec 2021 06:32:36 GMT</pubDate>
            <atom:updated>2021-12-10T06:32:36.228Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Optimization Functions Revision</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AU6O6M6EY0vhSbg0" /><figcaption>Photo by <a href="https://unsplash.com/@pawelskor?utm_source=medium&amp;utm_medium=referral">Paul Skorupskas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome back! This is the #11 blog of the Data Science/Machine Learning Series. In the previous week, we had discussed the Activation Functions. Today we are going to discuss Optimization Functions. If you have missed the previous blogs, you can catch up on those <a href="https://navaneethsharma.medium.com/list/data-science-ml-revision-series-c6a6610c13bc">here</a>.</p><p>Optimization functions are responsible for “learning” in Machine Learning. With the rise of Deep Learning, many optimization functions have emerged for faster and better optimization of weights. The popular optimization algorithms are</p><ul><li>Gradient Descent Algorithm</li><li>Gradient Descent Algorithm with Momentum</li><li>RMS Prop</li><li>Adam Optimization</li></ul><p>So without further due let’s dive in</p><h3>Gradient Descent Algorithm</h3><p>Gradient descent is an algorithm that is used to minimize or maximize a function iteratively. This is an optimization algorithm that iteratively minimizes the loss. The basic algorithm can be given as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*xI_kSXgKVbFbFZWut92K6A.png" /><figcaption>Gradient Descent Algorithm</figcaption></figure><p>Here w, b are the weights and biases. Loss function can be any depending upon the problem statement. The W, b are updated iteratively based on the computation of loss and learning rate alpha value. The alpha will be responsible for how fast the learning can happen. The alpha needs to be chosen appropriately. If alpha is high, the loss may not converge or will not minimize. If alpha is too small, the convergence will happen but, the iterations taken to coverage will be high.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*12uR-AEH1Tz4_D6eIEa0cw.png" /><figcaption>Sample diagram of various alpha values</figcaption></figure><p>The above gradient descent algorithm is also known as <strong>Batch gradient descent</strong> since we are using all the data at once to learn the weights (entire batch). For a smaller size of data, this will work smoothly, but when there is a humongous amount of data (In the range of millions), the computer may not be able to load such a large amount of data at once and the processing cannot be processed.</p><p>Stochastic Gradient Descent(SGD) algorithm is a gradient descent algorithm that takes one sample at a time and trains it. It is also known as online learning since it learns by taking one sample of data at a time.</p><p>The algorithm can be equated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/0*mpemLaDzUbR8WmSL" /><figcaption>SGD Algorithm</figcaption></figure><p>Here i is the ith sample of data. SGD can be used for adaptive learning. For the data that is flowing continuously, the model needs to learn as quickly as possible.</p><p>One of the improvements for SGD is mini-batch Gradient Descent. It is the combination of SGD and Batch gradient descent. Instead of taking entire data or taking single sample data here, the data is in batches. The performance increases drastically for the deep learning models. Mini-batch is fast, and the data can be loaded quickly (as it has small samples of data). Usually, the batch size varies from 32 to 512. The equation of this can be given as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*DbEBTZ749LaTYvcc" /><figcaption>Mini Batch GD</figcaption></figure><p>&lt;i&gt; represent ith batch. The below is the table of compression of these three algorithms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*sSLuReEh51Tug0chkHfSkA.png" /><figcaption>Comparison Table</figcaption></figure><h3>Gradient Descent Algorithm with Momentum</h3><p>The Momentum gives a boost to the gradient descent algorithm to converge faster. The below is the algorithm for gradient descent with momentum</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*FBqmTU18mTMP7qkmrku0DA.png" /><figcaption>Momentum Algorithm</figcaption></figure><p>Here Vdw and Vdb are the variables that are responsible for the actual momentum. Here β<strong> </strong>is the hyperparameter that is used to retain past knowledge, it needs to be chosen for better optimization. Usually, β will be taken as 0.9. and α is the learning rate that needs to experiment based on the models.</p><h3>RMS Prop Optimization</h3><p>RMS Prop stands for Root Mean Square Propagation. Similar to momentum, the RMSprop provides a boost to the gradient descent to converge faster. The algorithm can be given as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*9W8ICWm9NF1Cf9IUeHlQlg.png" /><figcaption>RMS Prop algorithm</figcaption></figure><p>Here β<strong> </strong>plays a similar role, to get the weighted average of the past values. is generally kept as 0.99. Due to the SdW and Sdb, the loss will converge faster. The weights will converge with fewer oscillations (below diagram) compared to the normal gradient descents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wSbK9JJ8PTL8DhIh" /></figure><p>Also, to avoid division by zero or the division by a really small number. The addition of epsilon to the Sdw, Sdb in the denominator is done. The value of epsilon will be in the order of 10-⁸.</p><h3>Adam Optimization</h3><p>Adam Optimization is the combination of both Momentum and RMS prop algorithms. Adam stands for ADAptive Moment Optimization. The Algorithm can be given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*nXAfjuXKTgHs-WPuzseQRw.png" /></figure><p>The term Vdw corresponds to the momentum, and Sdw corresponds to the RMSprop. The Correction terms are used to correct the biases(for intuition, as the number of iteration goes higher the corrected S, V terms are almost equal to the S, V). And here <strong>β1</strong> is generally taken as 0.9 and <strong>β2 </strong>is 0.99</p><p>Cool! We have quickly revised the concepts of almost all important optimization algorithms necessary for deep learning. In the next blog, we will go through another hyper-parameter Regularization for neural networks.</p><p>So stay tuned, See you next time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/345/1*EJIpY9sH2vyTj1cCzqtaqQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f10c79ae559" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Networks Hyper-parameters (Quick Revision)-1]]></title>
            <link>https://navaneethsharma.medium.com/neural-networks-hyper-parameters-quick-revision-1-79fff2c1ee83?source=rss-1fb61a861dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/79fff2c1ee83</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[revision]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Navaneeth Sharma]]></dc:creator>
            <pubDate>Sat, 06 Nov 2021 09:36:52 GMT</pubDate>
            <atom:updated>2021-11-06T09:36:52.576Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Activation Functions Revision</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lPX3XMbndgYqBnjQ" /><figcaption>Photo by <a href="https://unsplash.com/@jjying?utm_source=medium&amp;utm_medium=referral">JJ Ying</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome back! This is the #10 blog of the Data Science/Machine Learning Series. Till now, we have covered Loss Functions, Tree-based Algorithms, Regressions, and Weight Initialization for neural networks. Today we are going to discuss One of the Hyper-parameters<strong> </strong><em>Activation Functions</em>. If you have missed the previous blogs, you can catch up on those <a href="https://navaneethsharma.medium.com/list/data-science-ml-revision-series-c6a6610c13bc">here</a>.</p><p>Neural Network is a vast concept and has many variants in it. As the Algorithms are getting better and better, new concepts emerge every year. Activation Functions are used to extract the data more effectively. It basically transforms the weights of the neurons from one layer to another layer. Pictorially it can be represented as shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*gbQjtUJYRZT4R4uLojqAvA.png" /><figcaption>Neural Net sample diagram</figcaption></figure><p>The Neurons have two-part. <strong>Σ </strong>is called the Activation Function and the other is given in the diagram. Activation functions can be a crucial hyper-parameter while training the Deep Learning Model. Activation functions are usually chosen based on the problem we are solving. There are numerous activation functions to discuss. However, we will revise the most popular and important ones. Those are</p><ul><li>Sigmoid Activation Function</li><li>Tanh Activation Function</li><li>ReLU Activation Function</li><li>Leaky ReLU Activation Function</li><li>Softmax Activation Function</li></ul><p>So, without further delay Let’s dive in.</p><h3>Sigmoid</h3><p>Sigmoid function is given by the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*Tj8nW55hov7N58ZgU0hX7Q.png" /><figcaption>Sigmoid Function</figcaption></figure><p>It is also known as the logistic function. This function will map the input (range from -infinity to +infinity) to 0 to 1. When z=0, the output will be 0.5. If the z is high, the result will tend to reach 1. If out is low, the result will tend to move towards 0. The graph of this function is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*5vPFcckaUeM9d-f8yNadaQ.png" /><figcaption>Sigmoid Graph</figcaption></figure><p>The <strong>sigmoid function can be mainly used for binary classification</strong>, as it gives the output in a probabilistic manner between 0 to 1. One of the disadvantages of the sigmoid function is<strong> whenever the z value is too high or too low, it becomes computationally expensive</strong>(<em>as z approaches high value(+inf), the output remains close to one but never be one. Similarly as z approaches too low value(-inf) the output remains close to zero but never becomes zero</em>)<strong>.</strong> And also, the problem of vanishing gradients in neural networks arises due to small values (&lt;1).</p><h3>Tanh</h3><p>Tanh stands for Tan Hyperbolic. The Function is given by the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*jCRxkD2kyaA80SaN-jWCDA.png" /><figcaption>tanh function</figcaption></figure><p><strong>This function basically maps input ranging from -inf to +inf to -1 to +1. </strong>This function can also be used in binary classification similar to sigmoid. If we need outputs ranging from -1 to +1, we can use the Tanh function. Similar to sigmoid, the disadvantages are vanishing gradient problems and computational cost for large or small values. When z=0, the output will be 0. If the z is high, the result will tend to reach 1. If out is low, the result will move towards -1. The graph for Tanh is given below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*FWmDKbUjwhwIpAcqM_70oQ.png" /><figcaption>tanh</figcaption></figure><h3>ReLU</h3><p>ReLU stands for Rectified Linear Unit. This function can be used at the last layer for regression(non-negative regression) problems. And always using the ReLU activation function for hidden layers is useful. ReLU activation function is given by the simple equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*s__M9XPG1AVpk7C9x3Wxcw.png" /><figcaption>ReLU function equation</figcaption></figure><p>The equation is self-explanatory. If the value is less than zero, then the output will be fixed to zero. Else it will be set to the value at the input. Graphically it can be shown as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*EPZqw1sz8ym675Iv7z45SQ.png" /><figcaption>ReLU in graph</figcaption></figure><p>This function is used widely. As it resolves the issue of the Vanishing gradient problem to some extent compared to sigmoid or tanh. By maintaining the high value, it can resolve the issue. Since it has only a max operator, the computation is simple compared to other functions. (which had an exponential term or a tanh function).</p><h3>Leaky ReLU</h3><p>Leaky Relu is a modification for Relu function. As we have seen, the ReLU function will deactivate the neurons (set to zero if it has negative values). This modification for ReLU solves this problem by allowing some leakage to the negative half. The equation is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*QjMtGtOs4MplmaX6HG8JPw.png" /><figcaption>Sample Leaky ReLU equation</figcaption></figure><p>The graph can clearly explain the concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*fj9InvUKmvSDGpvamXMr8w.png" /><figcaption>Leaky ReLU graph</figcaption></figure><p>This is also a popular activation function for deep neural networks. It combines the advantage of ReLU and also solves the shutting down of neuron problems.</p><h3>Softmax</h3><p>The softmax activation function is mainly used for multi-class classification situations. This is majorly used at the last layer of the neural networks. The equation is given by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*kQLY9S_OLfW0lKTA4zDRhQ.png" /><figcaption>Softmax Function</figcaption></figure><p>The softmax function will return the values between 0 to 1 such that if there are 5 classes, the total sum of values of 5 classes will be 1. Pictorially it can be represented as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*kmT3Mu9ah13CLPmj-sUKGA.png" /><figcaption>Softmax Sample Block diagram</figcaption></figure><h3>Customizing the Activation Function</h3><p>We have seen most of the popular activation functions. There are some more popular functions like Linear, parametric ReLU, etc. A number of activation functions can be derived through ReLU, Sigmoid etc. It can be done via numpy library or keras. You can modify the ReLU function by multiplying a constant value, that is nothing but parametric ReLU. Similarly exponential linear unit can also be created modifying the ReLU. These can be done based on the problem statements you have. If your model are getting vanishing gradient problem you can choose ReLU. If you dont want the neurons to shut, you can either use parametric ReLUor leaky ReLU, or also you can create custom Activation function based on hyper-parameters given in those. I highly recommend you to read <a href="https://medium.com/geekculture/different-activation-functions-for-deep-neural-networks-you-should-know-ea5e86f51e84">this </a>blog to get more insights.</p><p>Awesome! We have revised One of the Hyper-parameters of Neural Networks. In the next blog, we will revise the Optimization Functions used in Deep Learning. Till then take care and See you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79fff2c1ee83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting Techniques-2(Quick Revision)]]></title>
            <link>https://navaneethsharma.medium.com/boosting-techniques-2-quick-revision-a2bdf19219f3?source=rss-1fb61a861dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2bdf19219f3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[boosting]]></category>
            <category><![CDATA[revision]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <dc:creator><![CDATA[Navaneeth Sharma]]></dc:creator>
            <pubDate>Sat, 30 Oct 2021 17:37:27 GMT</pubDate>
            <atom:updated>2021-10-30T17:37:27.498Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Gradient Boosting Decision Trees Revision</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rbc4AvA3vcmiVEH-" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=medium&amp;utm_medium=referral">Annie Spratt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome again! This blog is #9 of the Revision Series. Also, if you want to revise the Machine Learning and Deep Learning Concepts, you can catch up <a href="https://navaneethsharma.medium.com/list/data-science-ml-revision-series-c6a6610c13bc">here</a>). As we have covered Adaboost in the last part, we will go through Gradient Boosted Decision Trees this time.</p><p>Random forests, GBDT based models are the two most widely used Algorithms by data scientists. As I had covered Random Forest in the earlier part, let’s quickly revise What? Why? and When? of GBDT.</p><h3>GBDT Algorithm</h3><blockquote>What?</blockquote><p>Similar to Adaboost, the GBDT learns from its previous mistakes. GBDT uses a single leaf to start instead of a tree or a stump. This leaf represents an initial guess for the weights of all the samples. In the further steps, the Algorithm builds fixed size trees(usually 8–32 leaves) based on previous errors, whereas Adaboost uses just stumps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*x-dN1l-hFc58YMFtJCPkyA.png" /><figcaption>Gradient Boosting Decision Tree Algorithm</figcaption></figure><h4>Algorithm for GBDT-Regression</h4><p><strong>Input: </strong>The input for the algorithm is (xi,yi) i=1,…n. And a Differential loss function is used in the Algorithm</p><p><strong>Step1: </strong>Initialize the model(just a leaf) with a value that has a minimum loss, which is nothing but the average of observed weights.</p><p><strong>Step 2:</strong> Loop through the further steps with M iterations (M is the number of trees to learn ). Calculate the Loss b/w the output y and Model F(x), Next compute the pseudo residuals with gradient (partial derivative) of the Loss. The loss function used here is</p><p>Fit a Regression tree rm (mth tree) which has Jm number of leaves in it. Next, compute the weight as given in the formula taking previous predictions. Finally, update the model with a learning rate nu.</p><p><strong>Step 3: </strong>Return the Final Model</p><h4>Algorithm for GBDT-Classification</h4><p>The changes to be made for classification GBDT are, change the loss function to log loss (logistic loss). And compute gamma by</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*5ZbZ6ImUxwQRWvSYLXrTyA.png" /><figcaption>Gamma Computation Formula for Classification</figcaption></figure><p>where p is sigmoid(x). The Final Output will result in a probability of that class being correct.</p><blockquote>Why?</blockquote><p>GBDT overcome the overfitting in Decision trees and can learn better from Adaboost as Adaboost uses only stump as weak learners. Typically gives good results. Many Data Scientists use GB based models as a baseline to start with.</p><blockquote>When?</blockquote><p>When the data is tabular, GBDT performs well usually. Also, If the data has outliers to some extent, GBDT can handle those whereas Adaboost cannot. So GBDT outperforms the Adaboost in such cases.</p><h4>Advantages</h4><ul><li><strong>GBDT can handle outliers </strong>in the data</li><li>Can solve complex non-linear functions</li><li>Less likely to overfit and underfit</li><li><strong>No Feature Scaling</strong> is required</li></ul><h4>Disadvantages</h4><ul><li><strong>GBDT cannot handle missing values</strong></li><li>Training takes computation resources and time</li></ul><p>Cool! We have revised the GBDT algorithm, and discussed What? When? Why? and its advantages, disadvantages. Next, We will start with Neural Networks (Deep Learning).</p><p>Thank you! and see you in next blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2bdf19219f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting Techniques-1(Quick Revision)]]></title>
            <link>https://navaneethsharma.medium.com/boosting-techniques-1-quick-revision-80a3aefcbf32?source=rss-1fb61a861dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/80a3aefcbf32</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[revision]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[boosting]]></category>
            <dc:creator><![CDATA[Navaneeth Sharma]]></dc:creator>
            <pubDate>Fri, 22 Oct 2021 12:33:31 GMT</pubDate>
            <atom:updated>2021-10-22T12:33:31.913Z</atom:updated>
            <content:encoded><![CDATA[<p><em>AdaBoost Algorithm Revision</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*64rSGcyI5M5Znu_4" /><figcaption>Photo by <a href="https://unsplash.com/@nlswss?utm_source=medium&amp;utm_medium=referral">Niels Weiss</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome to the ML Revision Series. This blog is the #8 part of the Series. In the last blog, we have revised the bagging techniques Random forests, Extra-Tree Classifiers. Today we will Quickly go through one of the Boosting algorithms, Adaboost.</p><h3>AdaBoost Algorithm</h3><blockquote>What?</blockquote><p>Bagging Algorithms like Random Forests combine t1,t2…tk, where ti refers to individual decision trees (i varies from 1 to a given number of trees k). But in Adaboost, the Algorithm uses stumps. A stump refers to a tree with one node and two leaves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*2wOD-Q_77v7hJfbIWEPFTQ.png" /><figcaption>Sample diagram of Stump</figcaption></figure><p>In simple words, a stump is a weak learner that can learn a pattern. The stumps are weighted and combined to create the boosting Algorithm. The weight is generally called the <strong>Amount Of Say (AOS). </strong>The Major Highlights of the Adaboost are</p><ul><li>Combines the weak learners to make classification/Regression, where learners are stumps.</li><li>Some Stumps get more say (weight) in Classification/Regression than others.</li><li>Stump learns from previous mistakes of other stumps and tries to create a model with low error.</li></ul><h4>Algorithm</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5jgfF9tj8Do356tQCxa8xg.png" /><figcaption>AdaBoost Algorithm (Source: Stack Exchange)</figcaption></figure><p><strong>Step 1</strong> is for initializing the weights. The weights are equal to 1/N (Where N is the number of samples in the dataset).</p><p><strong>Step 2</strong> is the crucial step. The Loop is run from 1 to M (M is the number of stumps you want to train). Next, fit a stump classifier to the training data with weights wi. Calculate the Total Error, which is nothing but the sum of weights incorrectly classified samples. Compute alpha (amount of say) by the equation given and adjust the weights wi.</p><p><strong>Step 3</strong> is to calculate the output label.</p><blockquote>Why?</blockquote><p>The Adaboost can learn better from decision trees. It overcomes the High Variance or Overfitting of Decision trees. Also, Algorithm can learn non linear patterns.</p><blockquote>When?</blockquote><p>Adaboost is good for tabular data. So we can try out this with the data we have. Adaboost works fine when there are missing values in data. So this algorithm can be used when there are missing values. If you get to know some advantages, disadvantages you will better understand when to use this Algorithm.</p><h4>Advantages</h4><ul><li><strong>Adaboost can handle missing values</strong> in the data</li><li>Can solve complex non linear functions</li><li>Less likely to overfit and underfit</li><li><strong>No Feature Scaling</strong> is required</li></ul><h4>Disadvantages</h4><ul><li><strong>Adaboost is sensitive to outliers</strong></li><li>Training takes some computation resources and time</li></ul><p>Yo! We have revised the Adaboost algorithm and discussed its advantages, disadvantages, etc. Next, we will go through another Boosting Algorithm GBDT (Gradient Boosting Decision Trees).</p><p>Thank you for your time. Let’s meet soon with another exciting revision material.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80a3aefcbf32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bagging Techniques (Quick Revision)]]></title>
            <link>https://navaneethsharma.medium.com/bagging-techniques-quick-revision-eb2495ac4ea2?source=rss-1fb61a861dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb2495ac4ea2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bagging]]></category>
            <category><![CDATA[revision]]></category>
            <category><![CDATA[random-forest]]></category>
            <dc:creator><![CDATA[Navaneeth Sharma]]></dc:creator>
            <pubDate>Sun, 17 Oct 2021 14:03:16 GMT</pubDate>
            <atom:updated>2021-10-17T18:10:54.362Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Random Forest Algorithm and Feature Extraction via Bagging</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tofHfbfGccmbHmOq" /><figcaption>Photo by <a href="https://unsplash.com/@skamenar?utm_source=medium&amp;utm_medium=referral">Steven Kamenar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome again! Today we will quickly go through a couple of widely used Bagging Techniques. This blog is #7 of the Revision Series. If you want to revise some of the ML concepts quickly, you can check out this <a href="https://navaneethsharma.medium.com/list/data-science-ml-revision-series-c6a6610c13bc">list</a>.</p><p>Random Forest is a popular bagging technique for ML tasks. For Tabular data, It works pretty well, can perform well for both Regression and Classification problems. One more bagging-based Technique used for Feature Selection and to know the Importance of the features is the Extra-Tree Classifier. Let’s dive into What? Why? and When? to use these Techniques.</p><h3>Random Forest</h3><blockquote>What?</blockquote><p>Decision Trees do not perform well for validation data, as it overfits the data a lot. We have discussed this concept in the prevision section of Bagging and Boosting.</p><h4>Algorithm</h4><pre><strong>STEP 1: </strong>Create a Bootstrap Dataset, Bootstrap dataset can be created by selecting n random samples where duplicates are allowed. (Row Sampling)</pre><pre><strong>STEP 2:</strong> Create a Decision Tree Using the Bootstrapped data, but using a random subset of features at each step. Typically √m  Number features are selected. (Column Sampling)</pre><pre><strong>STEP 3:</strong> Go Back to STEP 1 and Repeat</pre><pre><strong>STEP 4: </strong>Aggregate the Results</pre><pre><em>Where </em><strong><em>n</em></strong><em> is the total number of samples or Examples in the Data<br>Where </em><strong><em>m</em></strong><em> is the total number of Features or Variables in Data</em></pre><p>Diagrammatically the Random Forest can be shown as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUCbbn72pyzVP-clepRk4Q.png" /><figcaption>Sample Block Diagram of the Random Forest</figcaption></figure><p>Since the Features are selected at random, there can be a possibility of choosing same features again and again, and some can miss out in training process. This is called <strong>Out of Bag</strong>. Typically one third (⅓) of the data is not being considered for training. So, These samples which are not used in training is used for validation. This is Known as <strong>Out of Bag Score</strong> (OOB_Score). This can be very handy to verify the model performance.</p><blockquote>Why?</blockquote><p>Random Forest overcome the overfitting problem of the Decision Trees. Since the algorithm is Ensemble based model, Typically gives good results. The individual Trees can learn up to some extent, but combining them will enable the model to learn even better.</p><blockquote>When?</blockquote><p>Random Forest is best suited for Tabular data. So, whenever the data is tabular, it is worth trying Random Forest Algorithm. If data contains outliers, a Random forest Algorithm is preferable.</p><h4>Advantages</h4><ul><li>No Feature Scaling is Required</li><li>Decision Trees will highly overfit the data whereas <strong>Random Forest will reduce the high variance (overfitting)</strong></li><li><strong>Robust to outliers</strong> in Data</li><li>Can<strong> handle missing values</strong></li><li>Out Of Bag Score can be used as a verification for the Model Performance</li><li>Works Well on Non Linear Data</li></ul><h4>Disadvantages</h4><ul><li>Random forests tend to be biased while dealing with categorical variables.</li><li>Also, For Multiclass Classification Problems the algorithm tend to be biased for the classes which have more frequency</li><li>The Imbalance Data hurts the Performance</li><li>If the model is large, the computational time will be high.</li></ul><h3>Feature Extraction via Bagging</h3><p>The Decision Tree can be used to score a feature for its importance by computing its Information Gain or Gini Impurity. That is, whether a feature can split the data with higher Information gain or not. Similarly, Random Forest can be used to calculate the Importance score. It uses Proximity Matrix for calculating the similarity. If 2 or more sample end up in a same leaf node, then they are considered to be similar. There is a Special Algorithm can Extra Tree Classifier, which performs well compared to Random Forests. The Major difference between Extra-Tree Classifier and Random Forests lies in its sampling method.</p><p>Algorithmically, the change with the Extra tree classifier is the samples selected are without replacement (duplicates are not allowed). Also this algorithm can be used for Feature Selection or Extraction. It can also give a ranking of the Features that are important for the prediction. The Advantages and Disadvantages are almost similar to Random Forest, except this doesn&#39;t have Out of Bag score and it is an Extremely randomized algorithm, So the learning would be more better than that of RFs.</p><p>Awesome! We have revised the concepts of Random Forests and Extra Tree Classifiers.</p><p>Thank you for your precious time. Let’s revise more concepts in the future. See you next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb2495ac4ea2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bagging & Boosting Ensemble Models(Quick Revision)]]></title>
            <link>https://navaneethsharma.medium.com/bagging-boosting-ensemble-models-quick-revision-cb02c136aaa1?source=rss-1fb61a861dae------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb02c136aaa1</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[boosting]]></category>
            <category><![CDATA[revision]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bagging]]></category>
            <dc:creator><![CDATA[Navaneeth Sharma]]></dc:creator>
            <pubDate>Sat, 16 Oct 2021 14:01:46 GMT</pubDate>
            <atom:updated>2021-10-16T14:01:46.163Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Quickly Going through Bagging and Boosting Techniques used in Tree based Models</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ITYcO4g0EG4neiYp" /><figcaption>Photo by <a href="https://unsplash.com/@gitsela?utm_source=medium&amp;utm_medium=referral">Ergita Sela</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome back to the revision series for ML/Data Science. Today we are going to revise the techniques like Bagging and Boosting for Tree-based algorithms. As this will be a revision series, I assume you have some background on Decision Trees and Machine Learning. So without further delay, let’s dive in.</p><p>Bagging and Boosting are the techniques majorly developed to solve the high variance or Overfitting problem of Decision Trees. These are widely known as Ensemble Models. This can be interpreted as a Model which combines the weak learners (Decision Tree Model) and produces accurate results.</p><h3>Bagging</h3><p>Bagging essentially stands for Bootstrap Aggregation Method. In this method, the Bootstrapped Data are used by the models. Statistically, Bootstrapped data gives an estimate of the whole Data (For more info about Bootstrapping, refer here). Aggregation means aggregating the results by the models. Usually, Decision Trees overfits the data a lot. In Bagging, Essentially “n” decision trees models are trained with bootstrapped data and combined. For Classification Example, the Random Forest Method (which uses Bagging) will aggregate the results by majority vote for prediction of the classes. Higher the number of votes for a particular category that will return as the output. The Sample Block diagram of the Bagging will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*TIeKYF_SiLm7E3c3L_rQVA.png" /><figcaption>Sample Block Diagram of Bagging</figcaption></figure><h4>Advantages</h4><ul><li>Bagging combines the power of many weak learners. Can Solve the Complex Non-Linear Functions</li><li>Decision Trees will highly overfit the data whereas <strong>Bagging will reduce the high variance (overfitting)</strong></li><li><strong>Robust to outliers</strong> in Data</li><li>Can<strong> handle missing values</strong></li><li><strong>No Feature Scaling</strong> is required for the training</li></ul><h4>Disadvantages</h4><ul><li>Sometimes bagging may lead to underfitting or <strong>high bias, If there are many categorical data</strong></li><li><strong>The Learners are isolated </strong>as shown in figure, so it cannot leverage learnings from the past mistakes</li><li><strong>Imbalance Data Effects performance</strong></li><li>Having to train multiple models, Computationally bit Expensive than Decision Trees</li></ul><h3>Boosting</h3><p>Boosting is a powerful technique, which allows weak learners (such as Decision Trees) to learn the patterns more. The Sample block Diagram will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRJcYuOgi9QJedaEHM0lHg.png" /><figcaption>Sample Block Diagram of Boosting</figcaption></figure><p>As the figure shows, the learners will learn from the previous block, This gives an edge over bagging. The learner learns from past mistakes and increases the model performance. The Models like AdaBoost, GBDT, XGBoost, Catboost and many more are tools for Boosted Learning. The learners are usually weak, which means it has only a root, a stump, or a small tree. There will be an error associated with the respective algorithms, which measures the performance of the model. Based on the error, the Learners will learn the feature needed to improve the model performance. For prediction, the data need to go through all the blocks.</p><h4>Advantages</h4><ul><li>Boosting combines the power of many weak learners similar to bagging, but has an edge over bagging since it can learn from past errors</li><li>Can Solve the Complex Non-Linear Functions</li><li>Boosting will <strong>overcome the overfitting problem</strong> of the decision trees</li><li><strong>No Feature Scaling</strong> is required for the training</li></ul><h4>Disadvantages</h4><ul><li>Computationally expensive compared to Decision Trees and Bagging algorithms, This is one of the disadvantages of boosting</li><li>Some algorithms like <strong>AdaBoost are sensitive to outliers</strong></li><li>Some algorithms such as <strong>GBDT, XGBoost cannot handle missing values</strong></li><li><strong>Imbalance Data Effects performance</strong></li></ul><p>Cool! We just revised the Bagging and Boosting Concepts in Machine Learning. Thank you for your time. Let’s discuss the algorithms of those in next sections of Revision Series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb02c136aaa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>