<?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 Reghuram K on Medium]]></title>
        <description><![CDATA[Stories by Reghuram K on Medium]]></description>
        <link>https://medium.com/@reghuramk?source=rss-625634d3ba0f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0lHHaETokVg5FWB9_4GZvg.jpeg</url>
            <title>Stories by Reghuram K on Medium</title>
            <link>https://medium.com/@reghuramk?source=rss-625634d3ba0f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 20:46:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reghuramk/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[This is a new series that explores how data structures and algorithms are applied in real-life…]]></title>
            <link>https://medium.com/@reghuramk/this-is-a-new-series-that-explores-how-data-structures-and-algorithms-are-applied-in-real-life-47c133d18986?source=rss-625634d3ba0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/47c133d18986</guid>
            <dc:creator><![CDATA[Reghuram K]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 20:13:11 GMT</pubDate>
            <atom:updated>2025-07-25T20:13:11.649Z</atom:updated>
            <content:encoded><![CDATA[<h3>How binary search tree optimise query lookup?</h3><p>This is a new series that explores how data structures and algorithms are applied in real-life scenarios. Today, we will explore Binary search trees (BST).</p><p>I came across the following problem of finding the depth of a BST. I wanted to learn about the actual applications of such a problem; turns out there are a lot of ways where finding the maximum depth helps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nQ1r38WAMffxiGTX" /></figure><p>Binary search trees (BSTs) can be used as database index structures to enable fast lookup, insertion, and deletion operations on records based on sorted keys. In such a setup, each node in the tree represents a key (often coupled with a reference to the row or record), allowing the database to efficiently find, insert, or remove values by leveraging the properties of binary search — left subtree for lesser values, right for greater.</p><p>Suppose a small online retailer uses an in-memory BST as an index to store user account IDs for fast lookup. Over time, the database receives records in sorted order — a common real-world scenario when inserting transaction logs or time-series data. If the BST is not managed for balance, new nodes are always added to one side, causing the tree to degenerate into a structure resembling a linked list. The maximum depth approaches the total number of nodes, drastically slowing down searches, inserts, and deletions from logarithmic time (O(log n)) to linear time (O(n)).</p><p>An actual example of database insert scenarios where not monitoring the maximum depth of a binary search tree (BST) leads to problems occurs when inserting sorted or nearly sorted data continuously without rebalancing. This causes the BST to become highly unbalanced, degenerating into a structure akin to a linked list.</p><p>Here is an example of a database query scenario involving insertion into a binary search tree (BST-based in-memory index table) storing user records keyed by user IDs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*85hxrX9p52ZTPzuU" /></figure><p>Because each new key is greater than all existing nodes, each insert adds a new node as the right child of the previous node, causing the tree’s shape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K3AqTD-4cnpf3U1o" /></figure><p>Here, the maximum depth is equal to the number of nodes (6). Searching for any key requires traversing through almost all nodes, resulting in O(n) time complexity rather than the ideal O(log n) for balanced trees. This degrades query, insert, and delete performance severely.</p><p>Consider a lookup query for user ID 5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-nVWUrhxtMnkx5m4" /></figure><p>A query lookup in a binary search tree (BST) works by starting at the root and comparing the search key to the key at the current node. Since a BST maintains the property that all keys in the left subtree are smaller and all keys in the right subtree are larger than the current node, this property guides the search:</p><ul><li>Start at the root node.</li><li>Compare the search key with the current node’s key:</li></ul><p>— If equal, the search is successful, and the node’s data is returned.</p><p>— If smaller, move to the left child subtree.</p><p>— If larger, move to the right child subtree.</p><ul><li>Repeat the process, moving down the tree until the key is found or a leaf (null child) is reached, indicating the key is not in the tree.</li></ul><p>This method efficiently narrows down the search space at each step, reducing the number of nodes checked compared to a linear search.</p><p>The efficiency of this lookup depends heavily on the tree’s maximum depth, or height:</p><ul><li>In a balanced BST, where the tree height is kept close to log2<em>n</em> (with <em>n</em> nodes), each comparison roughly halves the search space, leading to O(logn)<em> </em>time complexity for lookups. This means searches are very fast, even for large datasets.</li><li>In contrast, an unbalanced BST can degenerate into a linked list-like structure if nodes are inserted in sorted order without balancing. Here, the height of the tree approaches <em>n</em>, the number of nodes. This forces the lookup to traverse potentially all nodes sequentially, resulting in worst-case <em>O</em>(<em>n</em>) time complexity.</li></ul><p>This leads to Slower query response times due to deep traversals, increased CPU and memory overhead, potential timeouts or latency issues in real-time systems relying on the BST index, and difficulty in maintaining and updating the tree efficiently.</p><p>Monitoring maximum depth allows detection of this degeneration and prompts rebalancing operations or switching to self-balancing trees (AVL, Red-Black) to restore optimal O(log n) performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SRMpdrfwcQ5LjE8S" /></figure><p>In the balanced tree, the maximum depth is about log₂(7) = 3, while in the unbalanced tree, the depth is 7, drastically increasing search steps.</p><p>This directly impacts database performance when BSTs are used for indexes. Periodic depth checks help decide when to rebalance or rebuild the tree, maintaining efficient insert and lookup operations. By periodically checking the maximum depth of the BST, you detect this degeneration early. When depth crosses a threshold compared to ideal balanced depth (~log₂n), you trigger a rebalancing operation. Rebalancing restructures the BST to keep depth minimal, restoring fast O(log n) search, insert, and delete operations.</p><p>This is one such application where a binary search tree is used; there are other applications as well. In a Compiler Design, an expression tree gives you: Operator precedence, evaluation order and complexity of expressions. In machine the depth denotes the number of decisions in decision trees, and it also helps detect deep trees since a deep tree can overfit. In rendering and Game Engines, a scene graph’s depth can determine rendering order (z-index, lighting cascades).</p><p>So this is what I wanted to share about the binary search trees, let me know if you find any mistakes in this article, will try to correct it. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47c133d18986" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the Model Context Protocol (MCP)?]]></title>
            <link>https://medium.com/@reghuramk/what-is-the-model-context-protocol-mcp-4a388a2ab648?source=rss-625634d3ba0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a388a2ab648</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Reghuram K]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 18:31:44 GMT</pubDate>
            <atom:updated>2025-04-08T18:31:44.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bZQ6t8wqTbC5uvcGaqvsJg.png" /></figure><p>The Model Context Protocol (MCP), developed by Anthropic, is an open standard designed to streamline and standardize the integration between AI models and external systems. It serves as a universal bridge, enabling large language models (LLMs) to interact seamlessly with APIs, databases, and various business applications in a dynamic and structured way.</p><p><strong>MCP is built on a client-server architecture, where</strong>:</p><ul><li>MCP clients (like Claude Desktop) initiate requests and perform tasks,</li><li>MCP servers expose external tools and data sources for the models to use,</li><li>Host applications act as the bridge, facilitating communication between the AI models and connected tools through the MCP framework.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PtVjPcbKDzcQVm8M" /></figure><p>Let’s dive a bit deeper into the technical side.</p><p>At the heart of MCP lies a client-server architecture, where a single host application can interact with multiple servers to access external capabilities.</p><p><strong>MCP is built around three core components:</strong></p><ul><li>Host The host refers to any AI-enabled application — such as Claude Desktop or Cursor — that serves as the environment for AI interactions. It provides access to tools and data and runs the embedded MCP Client.</li><li>MCP Client Operating within the host, the MCP Client acts as the communication bridge, facilitating interaction between the host application and various MCP Servers.</li><li>MCP Server The server component is responsible for exposing specific functionalities or tools. It provides access to external data sources and capabilities, such as</li></ul><p>— Local databases</p><p>— APIs</p><p>— External services</p><p>This modular setup allows AI models to dynamically access tools and data in a standardized, scalable way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6vc_j2X3hAlfMnAZ" /></figure><ul><li>Tools: Enable LLMs to perform actions through your server.</li><li>Resources: Expose data and content from your servers to LLMs.</li><li>Prompts: Create reusable prompt templates and workflows.</li></ul><p>Grasping how client-server communication works is crucial if you’re looking to build your own MCP client-server system.</p><p>So, let’s explore how the client and server interact with each other.</p><p>But first, here’s a visual to set the stage before we walk through it step by step…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lJYFy1SZO6yX2nI3" /></figure><p>First, there is a capability exchange process:</p><ol><li>The client initiates a request to discover the server’s capabilities.</li><li>The server responds with details about its available features.</li></ol><p>For example, a Weather API server might return information on available “tools,” “prompt templates,” and other resources the client can utilize.</p><h3>Why is this setup powerful?</h3><p><strong>Traditional APIs: Rigid and Hardcoded</strong></p><ol><li>Let’s say you build a weather API that initially requires two parameters:</li><li>Users integrate their applications to always send these two parameters. Their code is written assuming that these two parameters are enough.</li><li>Later, you decide to add a third required parameter, like:</li><li>Since this is now required, every client using your API must update their code to include unit.</li></ol><p><strong>MCP’s Dynamic Approach: Flexible and Adaptive</strong></p><ol><li>Instead of hardcoding parameters, MCP allows the dynamic discovery of API capabilities.</li><li>When a client (e.g., an AI app like Claude Desktop) connects to your MCP-powered weather API, it first asks the server:</li><li>The server responds with its current capabilities, like:</li><li>Later, if you add a new parameter (e.g., unit), the server automatically updates its capability response to:</li><li>The next time the client connects, it automatically learns about unit and adjusts its behavior without needing code changes.</li></ol><h3>MCP in action</h3><p>(This entire setup guide is also available in the <a href="https://modelcontextprotocol.io/quickstart/server#claude-for-desktop-integration-issues">MCP</a> Official blog post)</p><p>I built a server that exposes two tools: get-alerts and get-forecast. Then, we’ll connect the server to an MCP host (in this case, Claude for Desktop):</p><p>This setup is available in this <a href="https://github.com/reghuramk/mcp-weather-server">repository.</a> Feel free to clone it. I used Node and TypeScript for this setup. If you want a quickstart on how to set up these two technologies, you can read my earlier blog on <a href="https://medium.com/@reghuramk/bun-v-deno-v-node-f239bd6f09f0">Bun v Node v Deno</a>.</p><p>Once you’ve followed the setup guide above and cloned my repository, you should be able to send prompts via Claude desktop.</p><h3>Test with commands</h3><p>Let’s make sure Claude for Desktop is picking up the two tools we’ve exposed in our weather server. You can do this by looking for the hammer icon:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YTFk4jkNcK3TLk6j" /></figure><p>After clicking on the hammer icon, you should see two tools listed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Mgw0WxRLMqdH3IQv" /></figure><p>If the hammer icon has shown up, you can now test your server by running the following commands in Claude for Desktop:</p><ul><li>What’s the weather like in Sacramento?</li><li>What are the active weather alerts in Texas?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z5JnKSwptBTMj5HY" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eCuy026BAX1EnW7a" /></figure><h3>What’s happening under the hood</h3><p>When you ask a question:</p><ol><li>The client sends your question to Claude</li><li>Claude analyzes the available tools and decides which one(s) to use</li><li>The client executes the chosen tool(s) through the MCP server</li><li>The results are sent back to Claude</li><li>Claude formulates a natural language response</li><li>The response is displayed to you!</li></ol><p>So this is all about the hot and buzzing topic of MCP is all about, Let me know if you find any discrepancies, add your comments, like it, share it. Thanks a lot.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a388a2ab648" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digits Data Classification using different Machine Learning models]]></title>
            <link>https://medium.com/@reghuramk/digits-data-classification-using-different-machine-learning-models-73de5ca9d0bd?source=rss-625634d3ba0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/73de5ca9d0bd</guid>
            <dc:creator><![CDATA[Reghuram K]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 15:02:38 GMT</pubDate>
            <atom:updated>2025-03-26T15:02:38.922Z</atom:updated>
            <content:encoded><![CDATA[<p>For our group project, we were tasked with classifying handwritten digits from the digits dataset in Scikit-learn, where each digit image had to be correctly identified as its corresponding number (0 to 9). We were instructed to use eight classification methods to accomplish this. Below, I will outline the steps we followed to implement and complete the project.</p><pre>1. Decision Tree Classifier<br>2. Linear discriminant analysis (Kaggle,2024) (Ashraf, K. 2024)<br>3. Logistic Regression (Madecraft and Galarnyk M., 2020) (Geron, 2017)<br>4. Gaussian Naive Bayes (Analytics Vidhya, 2025) (Medium,2020)<br>5. Support Vector Machine<br>6. K-nearest neighbors (KNN) (Kaggle,2022) (Singh, B 2022)<br>7. Random Forest (Metric Coders 2024)<br>8. Quadratic Discriminant Analysis (Scikit Learn 2025)</pre><h3>What is a classification in machine learning lingo?</h3><p>Classification is a supervised machine learning technique in which a model is trained to assign the correct label to input data. The model learns from training data, is assessed using test data, and then applied to predict labels for new, unseen data. We used 8 classification methods to classify between the digits dataset included in scikit. We will now see an overview of the dataset.</p><h3>Dataset Overview</h3><p>The digits dataset is a widely used dataset in machine learning for classification tasks. It consists of 8x8 pixel images of handwritten digits (0 to 9), where each image is represented as a 64-dimensional feature vector (8x8 pixels flattened into a single row). The dataset is part of the Scikit-learn library and is often used for benchmarking classification algorithms.</p><ul><li>Number of Samples: 1,797 (total images).</li><li>Number of Features: 64 (each representing a pixel value in the 8x8 image).</li><li>Number of Classes: 10 (digits 0 through 9).</li><li>Target Variable: The label for each image, indicating the digit it represents (0 to 9).</li></ul><p>This dataset is relatively small and well-balanced, making it ideal for experimenting with and comparing different classification methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jM8He18oao7yzsWG" /></figure><h3>Preprocessing</h3><p>Data Splitting: The dataset was split into training and testing sets using an 80–20 split. 80% of the data (1,437 samples) was used to train the models. 20% of the data (360 samples) was reserved for evaluating model performance. The splitting was done using train_test_split from Scikit-learn, with random_state=72 to ensure reproducibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PLKcjpNQyZj3fHsp" /></figure><p>Feature Scaling: The pixel values (features) were scaled using StandardScaler from Scikit-learn. Scaling is essential for algorithms that are sensitive to the magnitude of input features, such as SVM, KNN, and Logistic Regression. We fit the model by Calculating the mean and standard deviation of the training data. We apply the same transformation to both the training and testing data to ensure consistency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z474yjH7NhWu1ULv" /></figure><p>Label Binarization (for ROC-AUC Calculation): For multi-class classification tasks, the target labels were binarized using label_binarize Scikit-learn. This step was necessary to compute the ROC-AUC score for each class in a one-versus-rest manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dpIyueIhNAE8745k" /></figure><p>Handling Class Imbalance: The dataset is well-balanced, so no additional techniques like oversampling or undersampling were required. However, balanced accuracy was used as a metric to ensure fair evaluation across all classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A3vYfYPfLRfKdxvz" /></figure><p>This preprocessing pipeline ensures that the data is clean, normalized, and ready for training and evaluation, allowing for a fair comparison of the classification methods.</p><h3>Classification Methods Overview</h3><p>1. Decision Tree Classifier</p><ul><li>A Decision Tree Classifier is a non-parametric supervised learning algorithm that splits the data into subsets based on feature values, creating a tree-like structure of decisions. It uses criteria like Gini impurity or entropy to determine the best splits.</li></ul><p>2. Linear Discriminant Analysis (LDA)</p><ul><li>LDA is a dimensionality reduction and classification technique that projects data onto a lower-dimensional space while maximizing the separation between classes. It assumes that the data is normally distributed and that classes have identical covariance matrices.</li></ul><p>3. Logistic Regression</p><ul><li>Logistic Regression is a linear model used for binary or multi-class classification. It uses a logistic function to model the probability of a sample belonging to a particular class. For multi-class problems, it uses a one-versus-rest or softmax approach.</li></ul><p>4. Gaussian Naive Bayes</p><ul><li>Gaussian Naive Bayes is a probabilistic classifier based on Bayes’ theorem. It assumes that features are independent and normally distributed. It is computationally efficient and works well with small datasets.</li></ul><p>5. Support Vector Machine (SVM)</p><ul><li>SVM is a powerful classifier that finds the optimal hyperplane to separate classes in the feature space. It can handle linear and non-linear classification using kernel functions like RBF (Radial Basis Function).</li></ul><p>6. K-Nearest Neighbors (KNN)</p><ul><li>KNN is a simple, instance-based learning algorithm that classifies a sample based on the majority class among its k nearest neighbors in the feature space. It is non-parametric and relies on distance metrics like Euclidean or Manhattan.</li></ul><p>7. Random Forest</p><ul><li>Random Forest is an ensemble method that builds multiple decision trees and combines their outputs through majority voting or averaging. It reduces overfitting by introducing randomness in feature selection and bootstrapping.</li></ul><p>8. Quadratic Discriminant Analysis</p><ul><li>QDA is a generalization of LDA that allows each class to have its own covariance matrix. It is useful when the assumption of equal covariance matrices across classes does not hold.</li></ul><h3>Training and predicting with the model</h3><p>Let’s take Decision Tree Classifier for our example. Here, we define the model, fit the model and train the model. We split the dataset into training and testing sets:</p><p>• X_dt_train: Training data (features)</p><p>• X_dt_test: Testing data (features)</p><p>• Y_dt_train: Training labels (target values)</p><p>• Y_dt_test: Testing labels (target values)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iyszHSI5MtL0qIrX" /></figure><h3>Evaluation Metrics</h3><p>To assess the performance of the classification models, several evaluation metrics were used. These metrics provide a comprehensive understanding of how well each model performs in terms of accuracy, robustness, and ability to handle class imbalances. Below is a detailed discussion of the metrics used in this analysis:</p><p>Balanced Accuracy:</p><p>Balanced Accuracy is the average of recall obtained on each class. It is particularly useful for imbalanced datasets, as it gives equal weight to each class, ensuring that minority classes are not overlooked.</p><p>ROC-AUC Score</p><p>The ROC-AUC (Receiver Operating Characteristic — Area Under the Curve) score measures the model’s ability to distinguish between classes. It is calculated by plotting the True Positive Rate (TPR) against the False Positive Rate (FPR) at various threshold settings. For multi-class problems, the One-vs-Rest (OvR) approach is used, where the ROC-AUC score is computed for each class against all other classes and then averaged, which we will look at in a moment when we use it to draw the ROC curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*teIXNrQ5LZtS5Um_" /></figure><p>Confusion Matrix</p><p>A confusion matrix is a table that summarizes the performance of a classification model by showing the counts of True Positives (TP), True Negatives (TN), False Positives (FP), and False Negatives (FN) for each class.</p><ul><li>It provides detailed insights into the model’s performance for each class.</li><li>It helps identify which classes are being misclassified and the nature of the errors (e.g., false positives or false negatives).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2X_sw-OSTvbqwwbi" /></figure><p>Plotting Confusion Matrix for Decision Tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dCULcCLu_C7M6Td4" /></figure><p>Confusion Matrix For Decision Tree</p><h3>Hyperparameter Tuning Using GridSearchCV</h3><p>Hyperparameter tuning is a critical step in optimizing machine learning models. It involves finding the best combination of hyperparameters that maximizes model performance. In this analysis, GridSearchCV from Scikit-learn was used for hyperparameter tuning. Below is an explanation of the process and the rationale behind choosing specific parameters for each method.</p><h3>What is GridSearchCV?</h3><p>GridSearchCV is an exhaustive search method that evaluates all possible combinations of hyperparameters from a predefined grid. It uses cross-validation (CV) to assess the performance of each combination, ensuring robustness and reducing the risk of overfitting. The best combination of hyperparameters is selected based on a specified scoring metric (e.g., balanced accuracy, ROC-AUC).</p><h3>Process of Hyperparameter Tuning</h3><p>A dictionary of hyperparameters and their possible values is created for each model. Example: For a Decision Tree, the grid might include max_depth, min_samples_split, and criterion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pX9zTkMKlX-gsisN" /></figure><p>The model, parameter grid, and scoring metric are passed to GridSearchCV. Cross-validation folds (e.g., cv=5) are specified to evaluate each combination. GridSearchCV fits the model on the training data using all combinations of hyperparameters. It evaluates each combination using cross-validation and the specified scoring metric.</p><p>The combination of hyperparameters with the highest performance (e.g., highest balanced accuracy) is selected. The best model is then retrained on the full training dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AKozAC3bRDcm25cx" /></figure><p>The optimized model is evaluated on the test dataset to assess its generalization performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UYOPEwIDk0WVvjU8" /></figure><p>Now that we have the predictions of the optimised model, we can find the balanced accuracy score and ROC-AUC curve for the hypertuned parameter model and compare it with our default model. We do this with the help of our optimal predicted model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-4PV0bfvD28n8j1V" /></figure><p>We used a simple table to compare the scores of our default and optimised models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C5FLYFJ_QbzpfEDP" /></figure><p>As you can see after the hyper-tuning of our models, there is a slight change in the balanced accuracy score and ROC-AUC scores. There isn’t a significant increase in the difference between default and optimised models since we are dealing with only 10 classes (0–9). As you deal with higher amounts of classes, you will see some significant changes in your balanced accuracy and ROC-AUC scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/0*OiqOsvXZ0837Uq5K" /></figure><p>We also did the same thing for confusion matrices; we ran the confusion matrix again for our optimal model and tried comparing the differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3kE3XytnW_YUPmMK" /></figure><h3>ROC Curve</h3><p>The ROC curve is a graphical representation of the model’s performance across all classification thresholds. It plots the True Positive Rate (TPR) against the False Positive Rate (FPR). It helps visualize the trade-off between sensitivity (TPR) and specificity (1 — FPR). The area under the ROC curve (AUC) provides a single metric to compare models. We tried plotting the ROC curve with the roc_auc_score that we already calculated, but it did not work.</p><p>Why Can’t We Use roc_auc_score Directly for Plotting?</p><p>The function roc_auc_score() calculates the area under the ROC curve (AUC) but does not generate the actual ROC curve itself (i.e., the True Positive Rate (TPR) vs. False Positive Rate (FPR) values needed for plotting).</p><p>What roc_auc_score does:</p><p>It outputs a single number (e.g., 0.85) that represents the area under the curve. It does not give you the full set of FPR and TPR values needed to draw the curve.</p><p>What roc_curve does:</p><p>It returns three arrays: fpr, tpr, and thresholds. These are required to draw the curve itself.</p><p>Since roc_curve() doesn’t support multi-class directly, we need to convert Y_test to a one-hot encoded format and compute ROC curves separately for each class.</p><p>One-hot encoding is a technique used to convert categorical labels into a binary format where each class is represented by a unique vector.</p><p>Let’s say you have three classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/0*jLFTMA5wFi0844bd" /></figure><p>Instead of using single labels (0, 1, or 2), one-hot encoding converts them into binary vectors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/0*i4jxIsQ1djw8hbJx" /></figure><p>Each row represents a single class, and only one value is 1 (hot), while the rest are 0s (cold). Many ML models (like neural networks) don’t understand categorical labels (0, 1, 2). One-hot encoding converts them into numerical, independent representations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/0*7ZglpRsEj9F898uV" /></figure><p>The below ROC curve gives you a glimpse of how all of the classification models performed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*22kaI9NOAf96VB0W" /></figure><h3>Final Thoughts</h3><p>In this analysis, we explored and compared the performance of eight classification methods — Decision Tree, Linear Discriminant Analysis (LDA), Logistic Regression, Gaussian Naive Bayes, Support Vector Machine (SVM), K-Nearest Neighbors (KNN), Random Forest, and Quadratic Discriminant Analysis (QDA) — on the digits dataset. Each model was trained, optimized using GridSearchCV, and evaluated using metrics such as Balanced Accuracy, ROC-AUC Score, and Confusion Matrix.</p><p>Feel free to clone the repo: <a href="https://github.com/reghuramk/ml-group-project">https://github.com/reghuramk/ml-group-project</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73de5ca9d0bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bun v Deno v Node]]></title>
            <link>https://medium.com/@reghuramk/bun-v-deno-v-node-f239bd6f09f0?source=rss-625634d3ba0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f239bd6f09f0</guid>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Reghuram K]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 14:58:26 GMT</pubDate>
            <atom:updated>2025-03-26T14:58:26.733Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfUAylycJNEFox4rUByUHg.png" /></figure><p>I wanted to start a new backend Javascript (well, typescript) project, but I got confused about which libraries to use. Although the ‘Wake up Babe there’s a new JS library/framework’ meme is funny enough, there’s a reason why so many of them exist.</p><p>I don’t want to write about who created Node.js when Deno was released or whether Bun solved all Deno&#39;s problems. This isn’t a review, but a very elementary performance comparison and the overhead it takes for someone to start a simple project in either of these libraries. I’m not making any recommendations, either.</p><p>Before that, I wanted to mention the amount of time it took for me to set up the same snippet of code in all of the three languages, node, bun and deno, respectively.</p><h3>Node JS</h3><p>Let’s talk about Node.js first. Well, for starters, I wanted the project to be written in typescript. If you wonder, well, I’d rather use javascript for a performance comparison, you are free to do so. But I wanted to replicate this in an ideal situation, and ideally, plain Javascript isn’t preferred in any production deployed code.</p><p>Although from Node.js v23.10.0, you can directly compile typescript files on the fly (refer to the image below — <a href="https://nodejs.org/api/typescript.html#modules-typescript">If you want to learn more on this, refer to the official release notes.</a>) without needing to transpile TypeScript to JavaScript using Babel, tsc, tsx, or swc. However, it still cannot type check your Typescript code, this is no good. So that’s why we have to go through the pain of configuring tsconfig.json, installing tsc to typecheck your ts code — while tsc can also transpile your TypeScript code but I chose esbuild because it’s significantly faster — choosing between a plethora of typescript transpilers such as babel, esbuild (I chose this), swc, or tsx (this uses esbuild underneath), choosing between bundlers like esbuild (again esbuild lol) rollup, webpack, parcel, and then writing this simple Express app that listens for a basic request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VEHdyDwXePpOjuMr" /></figure><p>Nodejs transpiles TS files directly</p><p>The combination I used for this Node.js setup is as follows</p><blockquote><em>Typechecking — tsc</em></blockquote><blockquote><em>Transpiling typescript to javascript — esbuild</em></blockquote><blockquote><em>Bundling your code — esbuild</em></blockquote><h3>Bun</h3><p>From the release of Bun 1.2, you can now use bun as a bundler. Yes, you heard it right: In the above Node.js setup, we could have replaced esbuild with bun, and it would have worked as a bundler.</p><p>To spin up a bun project, I made sure I installed bun runtime</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bzXIMq8u4iku9AJp" /></figure><p>bun init — To create a minimal project, no need to choose which transpiler to use; every file in bun is transpiled on the fly by Bun’s fast native transpiler before being executed. But bun doesn’t support typechecking on the fly, we still need to rely on external libraries such as tsc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7sXiyfKjZyfsPqnr" /></figure><p>This is how you start a simple server in Bun. You don’t have to install an express app, bun provides a high-performance HTTP server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VL8O8R45QcMpo_wJ" /></figure><p>The combination I used for this Bun setup is as follows</p><blockquote><em>Typechecking — tsc</em></blockquote><blockquote><em>Transpiling typescript to javascript — Bun’s fast native transpiler</em></blockquote><blockquote><em>Bundling your code — Bun’s fast native bundler</em></blockquote><h3>Deno</h3><p>With Deno, just like Bun, it has a built-in TypeScript compiler that will compile your TypeScript code to JavaScript with no extra configuration needed; we can still type check out of the box. But it doesnt have a bundler out of the box (although in development). So I sought help from <a href="https://www.toddgriffin.me/blog/how-to-bundle-deno-typescript-for-the-browser">here</a>, which also uses esbuild to bundle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*l1I_PpxWa5qZYOfb" /></figure><p>Again, this is how you start a simple server in Deno. You don’t have to install an express app; Deno provides a high-performance HTTP server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dvFTtXuZN755laCb" /></figure><h3>Autocannon</h3><p><a href="https://www.npmjs.com/package/autocannon">Autocannon</a>, an HTTP/1.1 benchmarking tool designed to evaluate the performance of HTTP/1.1 servers by measuring key metrics such as raw throughput and latency.</p><p>I simulated 100 concurrent connections for 10 seconds. This should measure latency, data throughput, and requests handled per sec (req/sec). Let me break down each of these metrics.</p><p><strong>Latency</strong>: Lower latency means faster response times.</p><p><strong>Requests per Second</strong>: This metric indicates how many requests the server can handle per second.</p><p><strong>Throughput</strong>: Throughput measures the amount of data processed per second.</p><p><strong>Node</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7VouJGXQDZjaChwM" /><figcaption>Node Js</figcaption></figure><p>Node.js handled an average of 25,145.46 requests per second with an average latency of 3.3 ms. The maximum latency reached was 223 ms.</p><p><strong>Bun</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*stMV_i30n4xZhEL_" /><figcaption>Bun</figcaption></figure><p>Bun handled an average of 138,455.28 requests per second with an average latency of 0.03 ms. The maximum latency reached was 14 ms.</p><p><strong>Deno</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AkdWoIWgGCxoYqbg" /><figcaption>Deno</figcaption></figure><p>Deno handled an average of 157,352.73 requests per second with an average latency of 0.03 ms. The maximum latency reached was 14 ms.</p><h3>Results</h3><p>It’s clear that Deno was able to handle more requests in a given second; its average latency is the lowest of them all, and also the maximum latency it reached was 14 ms. It also achieved the highest throughput, 263 MB.</p><p>Deno, built with Rust, has outperformed both Node and Bun due to its secure-by-default features, native TypeScript support, and standard library. It uses the V8 engine to run JavaScript, while the Deno runtime provides additional features such as permission control and a built-in standard library for common tasks.</p><p>So, Deno appears to be the fastest runtime; again, this opinion is solely based on the above results. If you think there has been a mistake in how the tests are scored, or if you have a different method of measuring the performance, please do share your thoughts.</p><p>Link to the repository → <a href="https://github.com/reghuramk/js-library-benchmark">https://github.com/reghuramk/js-library-benchmark</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f239bd6f09f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digits Data Classification using different Machine Learning models]]></title>
            <link>https://medium.com/@reghuramk/classification-of-different-machine-learning-models-f7379f7af4d2?source=rss-625634d3ba0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7379f7af4d2</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Reghuram K]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 12:21:54 GMT</pubDate>
            <atom:updated>2025-03-05T12:24:07.520Z</atom:updated>
            <content:encoded><![CDATA[<p>For our group project, we were tasked with classifying handwritten digits from the <strong>digits dataset</strong> in Scikit-learn, where each digit image had to be correctly identified as its corresponding number (0 to 9). We were instructed to use <strong>eight classification methods</strong> to accomplish this. Below, I will outline the steps we followed to implement and complete the project.</p><pre>1. Decision Tree Classifier<br>2. Linear discriminant analysis (Kaggle,2024) (Ashraf, K. 2024)<br>3. Logistic Regression (Madecraft and Galarnyk M., 2020) (Geron, 2017)<br>4. Gaussian Naive Bayes (Analytics Vidhya, 2025) (Medium,2020)<br>5. Support Vector Machine<br>6. K-nearest neighbors (KNN) (Kaggle,2022) (Singh, B 2022)<br>7. Random Forest (Metric Coders 2024)<br>8. Quadratic Discriminant Analysis (Scikit Learn 2025)</pre><h3>What is a classification in machine learning lingo?</h3><p>Classification is a supervised machine learning technique in which a model is trained to assign the correct label to input data. The model learns from training data, is assessed using test data, and then applied to predict labels for new, unseen data. We used 8 classification methods to classify between the digits dataset included in scikit. We will now see an overview of the dataset.</p><h3>Dataset Overview</h3><p>The digits dataset is a widely used dataset in machine learning for classification tasks. It consists of 8x8 pixel images of handwritten digits (0 to 9), where each image is represented as a 64-dimensional feature vector (8x8 pixels flattened into a single row). The dataset is part of the Scikit-learn library and is often used for benchmarking classification algorithms.</p><ul><li>Number of Samples: 1,797 (total images).</li><li>Number of Features: 64 (each representing a pixel value in the 8x8 image).</li><li>Number of Classes: 10 (digits 0 through 9).</li><li>Target Variable: The label for each image, indicating the digit it represents (0 to 9).</li></ul><p>This dataset is relatively small and well-balanced, making it ideal for experimenting with and comparing different classification methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b_YIoLLau1TWAEhz" /></figure><h3>Preprocessing</h3><p>Data Splitting: The dataset was split into training and testing sets using an 80–20 split. 80% of the data (1,437 samples) was used to train the models. 20% of the data (360 samples) was reserved for evaluating model performance. The splitting was done using train_test_split from Scikit-learn, with random_state=72 to ensure reproducibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oXH9O5k3JQ5VuoUv" /></figure><p>Feature Scaling: The pixel values (features) were scaled using StandardScaler from Scikit-learn. Scaling is essential for algorithms that are sensitive to the magnitude of input features, such as SVM, KNN, and Logistic Regression. We fit the model by Calculating the mean and standard deviation of the training data. We apply the same transformation to both the training and testing data to ensure consistency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SB19KqpskyMe5647" /></figure><p>Label Binarization (for ROC-AUC Calculation): For multi-class classification tasks, the target labels were binarized using label_binarize Scikit-learn. This step was necessary to compute the ROC-AUC score for each class in a one-versus-rest manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tVKNhdDT4pNuMUUz" /></figure><p>Handling Class Imbalance: The dataset is well-balanced, so no additional techniques like oversampling or undersampling were required. However, balanced accuracy was used as a metric to ensure fair evaluation across all classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EUXuYI_1Fm9e1uSr" /></figure><p>This preprocessing pipeline ensures that the data is clean, normalized, and ready for training and evaluation, allowing for a fair comparison of the classification methods.</p><h3>Classification Methods Overview</h3><p>1. Decision Tree Classifier</p><ul><li>A Decision Tree Classifier is a non-parametric supervised learning algorithm that splits the data into subsets based on feature values, creating a tree-like structure of decisions. It uses criteria like Gini impurity or entropy to determine the best splits.</li></ul><p>2. Linear Discriminant Analysis (LDA)</p><ul><li>LDA is a dimensionality reduction and classification technique that projects data onto a lower-dimensional space while maximizing the separation between classes. It assumes that the data is normally distributed and that classes have identical covariance matrices.</li></ul><p>3. Logistic Regression</p><ul><li>Logistic Regression is a linear model used for binary or multi-class classification. It uses a logistic function to model the probability of a sample belonging to a particular class. For multi-class problems, it uses a one-versus-rest or softmax approach.</li></ul><p>4. Gaussian Naive Bayes</p><ul><li>Gaussian Naive Bayes is a probabilistic classifier based on Bayes’ theorem. It assumes that features are independent and normally distributed. It is computationally efficient and works well with small datasets.</li></ul><p>5. Support Vector Machine (SVM)</p><ul><li>SVM is a powerful classifier that finds the optimal hyperplane to separate classes in the feature space. It can handle linear and non-linear classification using kernel functions like RBF (Radial Basis Function).</li></ul><p>6. K-Nearest Neighbors (KNN)</p><ul><li>KNN is a simple, instance-based learning algorithm that classifies a sample based on the majority class among its k nearest neighbors in the feature space. It is non-parametric and relies on distance metrics like Euclidean or Manhattan.</li></ul><p>7. Random Forest</p><ul><li>Random Forest is an ensemble method that builds multiple decision trees and combines their outputs through majority voting or averaging. It reduces overfitting by introducing randomness in feature selection and bootstrapping.</li></ul><p>8. Quadratic Discriminant Analysis</p><ul><li>QDA is a generalization of LDA that allows each class to have its own covariance matrix. It is useful when the assumption of equal covariance matrices across classes does not hold.</li></ul><h3>Training and predicting with the model</h3><p>Let’s take Decision Tree Classifier for our example. Here, we define the model, fit the model and train the model. We split the dataset into training and testing sets:</p><p>• X_dt_train: Training data (features)</p><p>• X_dt_test: Testing data (features)</p><p>• Y_dt_train: Training labels (target values)</p><p>• Y_dt_test: Testing labels (target values)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BqW6KFcZ2zBsqcPU" /></figure><h3>Evaluation Metrics</h3><p>To assess the performance of the classification models, several evaluation metrics were used. These metrics provide a comprehensive understanding of how well each model performs in terms of accuracy, robustness, and ability to handle class imbalances. Below is a detailed discussion of the metrics used in this analysis:</p><p>Balanced Accuracy:</p><p>Balanced Accuracy is the average of recall obtained on each class. It is particularly useful for imbalanced datasets, as it gives equal weight to each class, ensuring that minority classes are not overlooked.</p><p>ROC-AUC Score</p><p>The ROC-AUC (Receiver Operating Characteristic — Area Under the Curve) score measures the model’s ability to distinguish between classes. It is calculated by plotting the True Positive Rate (TPR) against the False Positive Rate (FPR) at various threshold settings. For multi-class problems, the One-vs-Rest (OvR) approach is used, where the ROC-AUC score is computed for each class against all other classes and then averaged, which we will look at in a moment when we use it to draw the ROC curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cIgudygAS93W5yNx" /></figure><p>Confusion Matrix</p><p>A confusion matrix is a table that summarizes the performance of a classification model by showing the counts of True Positives (TP), True Negatives (TN), False Positives (FP), and False Negatives (FN) for each class.</p><ul><li>It provides detailed insights into the model’s performance for each class.</li><li>It helps identify which classes are being misclassified and the nature of the errors (e.g., false positives or false negatives).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VzKwdqsfp8GNEmca" /></figure><p>Plotting Confusion Matrix for Decision Tree</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mwr38pVKjg0UiPEK" /></figure><p>Confusion Matrix For Decision Tree</p><h3>Hyperparameter Tuning Using GridSearchCV</h3><p>Hyperparameter tuning is a critical step in optimizing machine learning models. It involves finding the best combination of hyperparameters that maximizes model performance. In this analysis, GridSearchCV from Scikit-learn was used for hyperparameter tuning. Below is an explanation of the process and the rationale behind choosing specific parameters for each method.</p><h3>What is GridSearchCV?</h3><p>GridSearchCV is an exhaustive search method that evaluates all possible combinations of hyperparameters from a predefined grid. It uses cross-validation (CV) to assess the performance of each combination, ensuring robustness and reducing the risk of overfitting. The best combination of hyperparameters is selected based on a specified scoring metric (e.g., balanced accuracy, ROC-AUC).</p><h3>Process of Hyperparameter Tuning</h3><p>A dictionary of hyperparameters and their possible values is created for each model. Example: For a Decision Tree, the grid might include max_depth, min_samples_split, and criterion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fS4woWdQJHoi0R3y" /></figure><p>The model, parameter grid, and scoring metric are passed to GridSearchCV. Cross-validation folds (e.g., cv=5) are specified to evaluate each combination. GridSearchCV fits the model on the training data using all combinations of hyperparameters. It evaluates each combination using cross-validation and the specified scoring metric.</p><p>The combination of hyperparameters with the highest performance (e.g., highest balanced accuracy) is selected. The best model is then retrained on the full training dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RjHGZHGUaZly7Rvw" /></figure><p>The optimized model is evaluated on the test dataset to assess its generalization performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f0AFpgcKSuHvBM5T" /></figure><p>Now that we have the predictions of the optimised model, we can find the balanced accuracy score and ROC-AUC curve for the hypertuned parameter model and compare it with our default model. We do this with the help of our optimal predicted model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AD8IUiO7tsNX0QEP" /></figure><p>We used a simple table to compare the scores of our default and optimised models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a7tcMIssQwxu4erA" /></figure><p>As you can see after the hyper-tuning of our models, there is a slight change in the balanced accuracy score and ROC-AUC scores. There isn’t a significant increase in the difference between default and optimised models since we are dealing with only 10 classes (0–9). As you deal with higher amounts of classes, you will see some significant changes in your balanced accuracy and ROC-AUC scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/0*_3sb_rFro3h_VY_k" /></figure><p>We also did the same thing for confusion matrices; we ran the confusion matrix again for our optimal model and tried comparing the differences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IBOTuiPPqEsWEF6s" /></figure><h3>ROC Curve</h3><p>The ROC curve is a graphical representation of the model’s performance across all classification thresholds. It plots the True Positive Rate (TPR) against the False Positive Rate (FPR). It helps visualize the trade-off between sensitivity (TPR) and specificity (1 — FPR). The area under the ROC curve (AUC) provides a single metric to compare models. We tried plotting the ROC curve with the roc_auc_score that we already calculated, but it did not work.</p><p>Why Can’t We Use roc_auc_score Directly for Plotting?</p><p>The function roc_auc_score() calculates the area under the ROC curve (AUC) but does not generate the actual ROC curve itself (i.e., the True Positive Rate (TPR) vs. False Positive Rate (FPR) values needed for plotting).</p><p>What roc_auc_score does:</p><p>It outputs a single number (e.g., 0.85) that represents the area under the curve. It does not give you the full set of FPR and TPR values needed to draw the curve.</p><p>What roc_curve does:</p><p>It returns three arrays: fpr, tpr, and thresholds. These are required to draw the curve itself.</p><p>Since roc_curve() doesn’t support multi-class directly, we need to convert Y_test to a one-hot encoded format and compute ROC curves separately for each class.</p><p>One-hot encoding is a technique used to convert categorical labels into a binary format where each class is represented by a unique vector.</p><p>Let’s say you have three classes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/0*o-OxP2w7aG3smKCV" /></figure><p>Instead of using single labels (0, 1, or 2), one-hot encoding converts them into binary vectors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/0*0CI8VFMlbs7YgdpD" /></figure><p>Each row represents a single class, and only one value is 1 (hot), while the rest are 0s (cold). Many ML models (like neural networks) don’t understand categorical labels (0, 1, 2). One-hot encoding converts them into numerical, independent representations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/0*uAr5ZZZrOeD8vM7D" /></figure><p>The below ROC curve gives you a glimpse of how all of the classification models performed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6FsCAhfqwO1pc0o0" /></figure><h3>Final Thoughts</h3><p>In this analysis, we explored and compared the performance of eight classification methods — Decision Tree, Linear Discriminant Analysis (LDA), Logistic Regression, Gaussian Naive Bayes, Support Vector Machine (SVM), K-Nearest Neighbors (KNN), Random Forest, and Quadratic Discriminant Analysis (QDA) — on the digits dataset. Each model was trained, optimized using GridSearchCV, and evaluated using metrics such as Balanced Accuracy, ROC-AUC Score, and Confusion Matrix.</p><p>Feel free to clone the repo: <a href="https://github.com/reghuramk/ml-group-project">https://github.com/reghuramk/ml-group-project</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7379f7af4d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-Validation: A Key Technique for Machine Learning]]></title>
            <link>https://medium.com/@reghuramk/cross-validation-a-key-technique-for-machine-learning-b9bc44c615a4?source=rss-625634d3ba0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9bc44c615a4</guid>
            <category><![CDATA[k-cross-validation]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Reghuram K]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 22:19:45 GMT</pubDate>
            <atom:updated>2025-02-23T22:19:45.709Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of machine learning, building a model that performs well on unseen data is the ultimate goal. While the basic train-test split is a crucial first step, it often falls short of providing a truly robust evaluation. This is where the power of cross-validation comes into play. Let’s explore why and how.</p><p><strong>The Limitations of a Simple Train-Test Split</strong></p><p>The train-test split involves dividing your dataset into two portions: one for training the model and the other for evaluating its performance. While this approach is simple and intuitive, it has some significant drawbacks:</p><ul><li>Sensitivity to Data Split: The performance of your model can be heavily influenced by the specific random split of the data. A “lucky” split might lead to overly optimistic results, while an “unlucky” split could paint a pessimistic picture.</li><li>Limited Data Usage: The test set is held back from the training process, meaning a portion of your valuable data isn’t used for model building. This can be especially problematic with smaller datasets.</li><li>Overfitting to the Test Set (Indirectly): If you repeatedly tweak your model based on the test set performance, you are, in effect, leaking information from the test set into your model. This can lead to overfitting to the test set, and your model won’t generalize well to truly new data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkPdunzmrBs2Wf-ifopPWQ.png" /></figure><p>Cross-validation is a technique used in machine learning to evaluate the performance of different models. It involves dividing the data into multiple subsets, training the model on some subsets, and testing it on the remaining subset. This process is repeated multiple times, each subset being used as the test set once.</p><p>The below image trains the data on the first three data blocks and tests the last data block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ni11ihnToh_V342zK4DAzQ.png" /></figure><p>The below image trains the data on the first, second and fourth data blocks, and tests the the third data block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sg8mi4EHxR0iokT0UquncA.png" /></figure><p>This step is repeated until all the blocks are covered, this way, all of the data is trained, and tested. Now, the model should be able to perform well and not underfit or overfit if we provide an unknown sample of data.</p><p>Okay, now you may ask what if I want to divide the data blocks by not but by say seven, you are welcome to do so. There are several cross-validation methods.</p><p><strong>Types of Cross-Validation:</strong></p><ul><li>k-fold Cross-Validation: This is arguably the most popular cross-validation technique. The data is divided into k equal-sized folds (subsets). The model is trained on k-1 folds and tested on the remaining folds. This process is repeated k times, with each fold serving as the test set once. The performance metrics 1 are then averaged across 2 all k folds to provide a final evaluation. A common choice for k is 5 or 10.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6f7nsiRDaltVx7-46H_2Ng.png" /></figure><ul><li>Leave-One-Out Cross-Validation (LOOCV): A special case of k-fold cross-validation where k equals the number of data points. Each data point serves as its own test set. While thorough, LOOCV can be computationally expensive for large datasets.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ab-EHvaXBhQ4-tbIMIb2g.png" /></figure><ul><li>Stratified k-fold Cross-Validation: This is a variation of k-fold where the folds are created in such a way that the proportion of each class in each fold is approximately equal to the proportion in the whole dataset. This is particularly important for imbalanced datasets.</li></ul><p><strong>Benefits of Cross-Validation:</strong></p><ul><li>More Reliable Performance Estimate: By averaging performance across multiple folds, cross-validation provides a more robust and less variable estimate of the model’s performance compared to a single train-test split.</li><li>Better Data Utilization: All data points get a chance to be used for both training and testing, maximizing the use of available data.</li><li>Reduced Overfitting: Cross-validation helps detect overfitting by providing a more realistic evaluation of the model’s ability to generalize.</li><li>Model Selection and Hyperparameter Tuning: Cross-validation can be used to compare different models or to tune the hyperparameters of a single model. By evaluating the performance of different model configurations across the folds, you can select the configuration that generalizes best.</li></ul><p><strong>Using Cross-Validation for Parameter Tuning:</strong></p><p>Cross-validation is invaluable for hyperparameter tuning. You can train and evaluate your model with different hyperparameter values across the cross-validation folds. The hyperparameter combination that yields the best average performance across the folds is likely to generalize best to new, unseen data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9bc44c615a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How DecisionTreeRegressor work?]]></title>
            <link>https://medium.com/@reghuramk/how-decisiontreeregressor-work-92e629ac7848?source=rss-625634d3ba0f------2</link>
            <guid isPermaLink="false">https://medium.com/p/92e629ac7848</guid>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Reghuram K]]></dc:creator>
            <pubDate>Thu, 13 Feb 2025 23:10:16 GMT</pubDate>
            <atom:updated>2025-02-13T23:10:16.212Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>Decision Tree Regressor</strong> is a machine learning model that predicts a <strong>continuous value</strong> (like house prices) by splitting the data into smaller and smaller groups based on certain rules.</p><p>Let’s break it down into simple steps:</p><h3>Data Preparation</h3><p>You provide the input features (X) and target variable (y):</p><ul><li>X: A DataFrame with features like LotArea, YearBuilt, 1stFlrSF, etc.</li><li>y: The target variable (e.g., house prices).</li></ul><p>The DecisionTreeRegressor will use this data to learn a model that predicts the target variable (y) based on the input features (X).</p><p>The DecisionTreeRegressor builds a tree-like structure to make predictions. Here’s what happens behind the scenes:</p><p><strong>Step 1: Start at the Root Node</strong></p><ul><li>The algorithm starts with the entire dataset at the <strong>root node</strong>.</li><li>It considers all features (LotArea, YearBuilt, etc.) and all possible split points for each feature.</li></ul><p><strong>Step 2: Find the Best Split</strong></p><ul><li>The goal is to split the data into two subsets such that the <strong>variance</strong> of the target variable (y) is minimized in each subset.</li><li>For each feature, the algorithm evaluates all possible split points and calculates the <strong>reduction in variance</strong> (or <strong>mean squared error, MSE</strong>) resulting from the split.</li><li>The feature and split point that result in the <strong>maximum reduction in variance</strong> are chosen.</li></ul><p><strong>Step 3: Recursively Split the Data</strong></p><ul><li>The dataset is split into two subsets based on the best feature and split point.</li><li>This process is repeated recursively for each subset until a stopping condition is met (e.g., maximum depth, minimum samples per leaf, or no further reduction in variance).</li></ul><p><strong>Step 4: Create Leaf Nodes</strong></p><ul><li>When the stopping condition is met, the algorithm creates a <strong>leaf node</strong>.</li><li>The predicted value at each leaf node is the <strong>mean</strong> of the target variable (y) for the samples in that node.</li></ul><h3>Code Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P6V0bNkhbOJ9CD6sjPiX0w.png" /></figure><h3>What goes behind the scenes?</h3><p>Imagine you’re trying to predict house prices based on the size of the lot (LotArea). The algorithm looks at all the houses and tries to find the best way to split them into two groups so that the house prices in each group are as <strong>similar as possible</strong>.</p><p>For example:</p><ul><li>It might try splitting the houses into two groups based on whether LotArea is less than or equal to 7,500 sq. ft.</li><li>After the split, it checks how much the <strong>variance</strong> (differences in house prices) is reduced in each group.</li><li>If this split reduces the variance a lot, it’s a good split. If not, it tries other splits (e.g., LotArea &lt;= 5,000 sq. ft. or LotArea &lt;= 10,000 sq. ft.).</li></ul><p>The algorithm picks the split that makes the house prices in each group as <strong>similar as possible</strong>. This is called <strong>minimizing variance</strong>.</p><p>Once the data is split into two groups, the algorithm doesn’t stop there. It <strong>repeats the same process</strong> for each of the two groups to make them even more similar.</p><ol><li><strong>First Split</strong>: The algorithm splits all houses into two groups based on LotArea &lt;= 7,500 sq. ft.</li></ol><ul><li>Group 1: Houses with LotArea &lt;= 7,500 sq. ft.</li><li>Group 2: Houses with LotArea &gt; 7,500 sq. ft.</li></ul><p><strong>2. Second Split</strong>: Now, the algorithm looks at <strong>Group 1</strong> and tries to split it further.</p><ul><li>It might split Group 1 based on YearBuilt &lt;= 1980.</li><li>This creates two new subgroups:</li><li>Subgroup A: Houses with LotArea &lt;= 7,500 sq. ft. <strong>and</strong> YearBuilt &lt;= 1980</li><li>Subgroup B: Houses with LotArea &lt;= 7,500 sq. ft. <strong>and</strong> YearBuilt &gt; 1980</li></ul><p><strong>3. Third Split</strong>: The algorithm also looks at <strong>Group 2</strong> and tries to split it further.</p><ul><li>It might split Group 2 based on 1stFlrSF &lt;= 1,200 sq. ft..</li><li>This creates two new subgroups:</li><li>Subgroup C: Houses with LotArea &gt; 7,500 sq. ft. <strong>and</strong> 1stFlrSF &lt;= 1,200 sq. ft.</li><li>Subgroup D: Houses with LotArea &gt; 7,500 sq. ft. <strong>and</strong> 1stFlrSF &gt; 1,200 sq. ft.</li></ul><p>The algorithm keeps splitting the data into smaller and smaller groups to make the house prices in each group as <strong>similar as possible</strong>. This helps the model make better predictions because:</p><ul><li>Each group becomes more <strong>specific</strong> (e.g., houses with small lots and old construction).</li><li>The predictions for each group become more <strong>accurate</strong>.</li></ul><h3>Example in Action</h3><p>Let’s say you have the following houses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lhX7Obri3bMmRdsA7ozqjQ.png" /></figure><h4>Step 1: First Split</h4><ul><li>The algorithm splits the houses based on LotArea &lt;= 7,500 sq. ft.:</li><li>Group 1: Houses 1 and 2 (LotArea &lt;= 7,500 sq. ft.)</li><li>Group 2: Houses 3 and 4 (LotArea &gt; 7,500 sq. ft.)</li></ul><h4>Step 2: Second Split (Group 1)</h4><ul><li>The algorithm splits Group 1 based on YearBuilt &lt;= 1980:</li><li>Subgroup A: House 1 (YearBuilt &lt;= 1980)</li><li>Subgroup B: House 2 (YearBuilt &gt; 1980)</li></ul><h4>Step 3: Third Split (Group 2)</h4><ul><li>The algorithm splits Group 2 based on 1stFlrSF &lt;= 1,200 sq. ft.:</li><li>Subgroup C: No houses (since both houses in Group 2 have 1stFlrSF &gt; 1,200 sq. ft.)</li><li>Subgroup D: Houses 3 and 4 (1stFlrSF &gt; 1,200 sq. ft.)</li></ul><h3>Key Takeaways</h3><ol><li><strong>Splitting</strong>: The algorithm splits the data into groups based on feature values.</li><li><strong>Goal</strong>: Make the target values in each group as similar as possible.</li><li><strong>Predictions</strong>: New data points are assigned to a group, and the prediction is the average target value for that group.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92e629ac7848" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>