<?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 Harsh S. Ranjane on Medium]]></title>
        <description><![CDATA[Stories by Harsh S. Ranjane on Medium]]></description>
        <link>https://medium.com/@harshsranjane03?source=rss-d918a4bfb487------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kiim1laZ2XLc1hou855jJA.jpeg</url>
            <title>Stories by Harsh S. Ranjane on Medium</title>
            <link>https://medium.com/@harshsranjane03?source=rss-d918a4bfb487------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:03:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshsranjane03/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[Navigating the Complexities of High Dimensional Functions in Machine Learning.]]></title>
            <link>https://medium.com/@harshsranjane03/navigating-the-complexities-of-high-dimensional-functions-in-machine-learning-88bb4de15a94?source=rss-d918a4bfb487------2</link>
            <guid isPermaLink="false">https://medium.com/p/88bb4de15a94</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[local-minima]]></category>
            <category><![CDATA[global-minima]]></category>
            <category><![CDATA[convex-function]]></category>
            <category><![CDATA[high-dimensional-space]]></category>
            <dc:creator><![CDATA[Harsh S. Ranjane]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 10:49:13 GMT</pubDate>
            <atom:updated>2025-01-19T10:49:13.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2BvGXzhB3GA9hL6NB-eyw.jpeg" /></figure><h3>Introduction.</h3><p>Imagine you’re exploring a mountainous terrain, trying to find the lowest valley. Along the way, you might encounter smaller dips that seem like the lowest point, only to realize there’s an even deeper valley ahead. This analogy perfectly captures the essence of the struggle between local and global minima in machine learning.</p><p>In the world of machine learning, optimization lies at the heart of building accurate models. During training, algorithms aim to minimize a loss function, which measures how far the model’s predictions deviate from the actual values. However, the loss landscape is often complex, riddled with multiple peaks and valleys, particularly in deep learning models. This is where the concepts of local minima and global minima come into play.</p><p>Understanding the difference between these two types of minima is crucial. While a local minimum is a point where the loss function is lower than in its immediate neighbourhood, a global minimum represents the absolute lowest point of the function. Getting “stuck” in a local minimum can result in suboptimal model performance, a common challenge in training machine learning models.</p><p>In this article, we’ll dive deep into the fascinating dynamics of local and global minima, explore how the shape of the High Dimensional loss functions impacts training, and discuss techniques to navigate this challenging terrain.</p><h3>What is Optimization and how does it work?</h3><p>Optimization in machine learning is the process of minimizing or maximizing a cost function to improve the model’s performance. The cost function quantifies the error or difference between the predicted output and the actual target values. By optimizing the parameters, the model learns to make better predictions over time.</p><p>In simpler terms, optimization helps in finding the best set of parameters that lead to the most accurate predictions by navigating the loss function’s landscape to find minima (ideally the global minimum).</p><p>Different optimization algorithms include Gradient Descent, Stochastic Gradient Descent, Mini-Batch Gradient Descent, Gradient Descent with Momentum, Adagrad, RMSprop, Ada-delta, LBFGS (Limited-memory Broyden–Fletcher–Goldfarb–Shanno) etc.</p><p>Each algorithm has its strengths and weaknesses, and the choice of the optimization algorithm depends on the problem, data size, and computational resources. Optimization is a critical step in the training process, ensuring models learn effectively and generalize well to unseen data.</p><h3>High-dimensional cost functions.</h3><p>A high-dimensional cost function is a mathematical function that depends on many parameters (weights, biases, etc.). For instance, a neural network with millions of parameters defines a cost function in a space with millions of dimensions. These high-dimensional spaces are far beyond human visualization, making the loss landscape highly complex and challenging to analyse.</p><p>For a simple model, such as linear regression, the cost function can often be visualized as a 2D or 3D curve. However, for complex models, particularly deep learning architectures, the cost function exists in high-dimensional space.</p><p>Key characteristics of high-dimensional cost functions:</p><ul><li>Non-convex nature: They often have multiple local minima, saddle points, and flat regions.</li><li>Complex landscapes: The optimization process involves navigating through this intricate surface to find an optimal solution.</li></ul><h3>How Do We Analyse and Visualize High-Dimensional Cost Functions?</h3><p>Although direct visualization of high-dimensional spaces is impossible, there are techniques to analyse and gain insights into these complex cost functions:</p><p><strong><em>1. Using Contour Plots and Heatmaps:</em></strong></p><p>These are visual representations of a cost function by fixing most parameters and varying only one or two parameters. For models with a small number of parameters, contour plots (2D) or heatmaps (3D) offer insights into the “shape” of the cost function, such as valleys, ridges, and flat areas. In a 2D example, a logistic regression model’s cost function could resemble a convex bowl shape. Contour lines represent areas of constant loss, helping visualize the optimization path taken by algorithms like gradient descent. But the limitation is, as the number of parameters grows, it becomes computationally infeasible to plot these directly due to exponential growth in combinations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*VCxwF3LLWJegt9mQ6ewtFw.jpeg" /></figure><p><strong><em>2. Using Linear Interpolation:</em></strong></p><p>Linear interpolation involves creating a <strong>straight-line path between two points in parameter space</strong> (e.g., initial parameters and trained parameters) and evaluating the cost function along this path. This method helps analyse whether the optimization path crosses valleys (local minima) or flat areas by observing the change in the gradient (if the gradient is zero there is a flat area and if there function is stuck there is a local minima). It can also reveal sharpness or smoothness in transitions. In deep learning, researchers often observe that moving from initial weights to final weights doesn’t necessarily follow a straight descent; instead, optimization might cross multiple small valleys or saddle points. Linear interpolation is <strong>limited to understanding transitions along a straight path</strong> and <strong>doesn’t capture the full complexity of high-dimensional surfaces</strong>.</p><p><strong><em>3. Using tools like PCA (Principal Component Analysis):</em></strong></p><p>PCA is a linear transformation that <strong>projects high-dimensional parameter space</strong> into a smaller number of <strong>orthogonal directions</strong> (principal components), capturing the <strong>most variance</strong> in the data. By plotting the loss function along the principal axes, practitioners can visualize trends in loss variation while ignoring less important dimensions. This approach reveals how much of the loss landscape’s complexity is contained within a few key directions, simplifying analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*njkcdBAyc1_LNLBRyJIrxw.png" /></figure><p><strong><em>4. Using heatmaps from Gradient Norms.</em></strong></p><p>Gradient norms refer to the <strong>magnitude of the gradients at a given point</strong> in parameter space, which represent the <strong>steepness</strong> of the cost function. Heatmaps of gradient norms can be used to identify regions where optimization is faster (steep slopes) or slower (flat areas). For example, in neural networks, flat regions (low gradient norms) can indicate vanishing gradients, especially in deep architectures like RNNs or poorly initialized weights.</p><p>Applications involve:</p><ul><li>Identify bottlenecks in training where gradient updates are small.</li><li>Analyse why certain regions of the loss landscape are harder to optimize.</li><li>Optimize learning rates dynamically by analysing gradient behaviour.</li></ul><p>Heatmaps of gradient norms are often studied to debug optimization algorithms and understand why models may get stuck in flat regions or saddle points. In practice, combining gradient norm analysis with other visualization tools provides a more comprehensive understanding of how optimization progresses.</p><p><strong><em>5. Using Slicing Techniques:</em></strong></p><p>In slicing techniques, a high-dimensional parameter space is reduced by fixing most dimensions and varying only a few parameters to study their <strong>individual or joint influence</strong> on the loss function. This approach simplifies analysis by <strong>fusing only on specific parameter</strong> subsets while ignoring others.</p><p>For neural networks, slicing can reveal how <strong>individual layer weights impact the overall loss</strong>. This helps identify specific layers or weights that may require fine-tuning. In hyperparameter tuning, slicing techniques help visualize how a <strong>single hyperparameter (e.g., learning rate, regularization coefficient) impacts the cost</strong>. By fixing parameters at specific values, practitioners can observe whether small changes in other dimensions significantly alter the cost, aiding in identifying critical regions of parameter space. While effective for targeted analysis, <strong>slicing does not capture interactions among all parameters</strong>, making it a partial view of the overall loss landscape.</p><h3>Convex vs Non-Convex Functions.</h3><h4>1. What are Convex and Non-Convex Functions?</h4><p>In the context of machine learning, convex and non-convex functions are mathematical representations of loss or cost functions that play a critical role in optimization processes. Understanding their nature is essential to designing effective learning algorithms and solving optimization problems.</p><p><strong><em>Convex Functions:</em></strong></p><p>A function f(x) is convex if the line segment connecting any two points on its graph lies above or on the graph. Convex functions are easy to optimize because they have a <strong>single global minimum and no local minima</strong>, making it easier for optimization algorithms to converge to the optimal solution.</p><p><strong>Example</strong>: The Mean Squared Error (MSE) loss function used in linear regression is convex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*ECLZEFudHpqLff2W7cVAwQ.png" /></figure><p><strong><em>Non-Convex Functions:</em></strong></p><p>A function is non-convex if it does not satisfy the above condition. In non-convex functions, the loss surface is more <strong>complex</strong>, containing <strong>multiple local minima</strong>, saddle points, and potentially a global minimum. Non-convex functions are <strong>harder to optimize</strong> since an optimization algorithm can get stuck in a local minimum or saddle point instead of reaching the global minimum.</p><p><strong>Example</strong>: Neural network loss functions, such as cross-entropy for deep networks, are typically non-convex due to the high-dimensional parameter space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*toL0zn6mKPkvLKiNMxFKVA.png" /></figure><h4>2. Characteristics of Convex and Non-Convex Functions.</h4><p><strong><em>Convex Functions:</em></strong></p><p><strong>1. Global Minima</strong>: Convex functions have a single global minimum. Any optimization method that descends along the gradient is guaranteed to find this minimum.</p><p><strong>2.</strong> <strong>First-Order Condition</strong>: For a differentiable convex function, a point <strong>x*</strong> is the global minimum if the gradient <strong>∇f(x*)=0</strong>.</p><p><strong>3.</strong> <strong>Second-Order Condition</strong>: If the second derivative i.e. Hessian matrix in higher dimension, is positive semi-definite (H≥0), the function is convex.</p><p><strong>4.</strong> <strong>Simplified Optimization</strong>: Optimization algorithms converge efficiently without requiring sophisticated techniques.</p><p><strong>5.</strong> <strong>Smoothness</strong>: Convex functions are often smooth, meaning their gradients change gradually.</p><p><strong><em>Non-Convex Functions:</em></strong></p><p><strong>1. Multiple Minima</strong>: Non-convex functions have <strong>numerous local minima</strong> and saddle points, making it difficult to locate the global minimum.</p><p><strong>2. No Guarantee of Global Optimum</strong>: Gradient-based optimization methods might <strong>converge to a local minimum</strong> rather than the global minimum.</p><p><strong>3. Complex Loss Landscape</strong>: The loss surface can have flat regions, steep gradients, and sharp valleys, making optimization challenging.</p><p><strong>4. Second-Order Derivative</strong>: The Hessian matrix can have both positive and negative eigenvalues, indicating a non-convex nature.</p><p><strong>5. Dependence on Initialization</strong>: Optimization heavily depends on the initial parameter values, as poor initialization can lead to convergence at suboptimal points.</p><h3>Local Minima.</h3><p>A local minimum is a point in the parameter space where the value of the loss function f(x) is <strong>lower than at any of the immediately surrounding points</strong> but not necessarily the lowest value in the entire parameter space. In differentiable functions, the following conditions are satisfied:</p><ol><li>First-order condition: The gradient at <strong>x*</strong> is zero:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*df7mZ7BSROkp15RjuUT4KQ.png" /></figure><p>2. Second-order condition: The Hessian matrix (second derivatives) is positive definite:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*d3PMDf9Y8aaZblllc86Xcw.png" /></figure><p>In high-dimensional functions, local minima represent suboptimal solutions that can hinder the optimization process, especially in non-convex loss landscapes.</p><h4>1. What is a Saddle point.</h4><p>A saddle point is a point in the parameter space where the <strong>gradient is zero</strong>, but the function is neither a local minimum nor a local maximum. Instead, it is a critical point where the function curves upward in one direction and downward in another direction. Mathematically, a saddle point satisfies the first order condition but for the second order condition, the <strong>Hessian matrix has both positive and negative eigenvalues.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*Wl_jjocSHk8ToXuxHyaqiA.png" /></figure><p>Saddle points are common in high-dimensional loss surfaces and can <strong>slow down optimization</strong>. Unlike local minima, saddle points do not represent optimal solutions, but optimization algorithms can <strong>stagnate</strong> in their vicinity due to near-zero gradients.</p><h4>2. Techniques to Overcome Local Minima.</h4><p>Efficiently navigating the loss landscape to avoid getting stuck in local minima or saddle points is crucial for training complex machine learning models. Here are key strategies to overcome these challenges:</p><p><strong>i. Learning Rate Tuning:</strong> A high learning rate allows the optimizer to jump over shallow local minima or saddle points, whereas a low learning rate enables fine-tuning when close to the global minimum. Therefore, we should use a learning rate scheduler to dynamically adjust the learning rate during training. Also, we can employ <strong>warm restarts</strong> to escape local minima.</p><p><strong>ii.</strong> <strong>Regularization Techniques:</strong> Regularization discourages overfitting and smoothens the loss landscape, making it easier to avoid sharp local minima.</p><p>· L2 Regularization (Ridge): Adds a penalty proportional to the square of the model weights, making the loss surface smoother.</p><p>· Dropout: Randomly drops neurons during training, which can help the model escape local minima by introducing noise.</p><p>· Weight Decay: Like L2 regularization, prevents weights from becoming too large and dominating optimization.</p><p><strong>iii. Initialization Strategies:</strong> Poor initialization can lead to convergence at suboptimal local minima. Proper initialization improves the chances of reaching better minima. Using techniques like <strong>Xavier Initialization</strong> or <strong>He Initialization</strong> for deep networks, can ensure that weights are initialized proportionally to the size of the layers. Also, for some models, random restarts can be effective.</p><p><strong>iv. Momentum based-optimization:</strong> Momentum-based optimizers add a fraction of the previous gradient to the current gradient, helping the optimizer gain velocity and escape local minima.</p><p>Optimizers with Momentum:</p><ul><li>SGD with Momentum: Adds a momentum term to the gradient.</li><li>Adam: Combines adaptive learning rates with momentum, making it robust against local minima.</li><li>RMSprop: Maintains a running average of squared gradients, preventing oscillations in valleys or sharp regions.</li></ul><h3>Global Minima.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZC9qItK9wI0F6BwSVYMQGg.png" /></figure><p>In machine learning, the global minima of a cost or loss function represent the point in the parameter space where the function achieves its <strong>lowest possible value</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*0jASMuWuXH_TiSD7KaeSLw.png" /></figure><p>This means that for all possible values of <strong>x</strong> in the parameter space, the value of the function at <strong>x*</strong> is less than or equal to the value of the function at any other point.</p><h4>1. Flat Minima vs. Sharp Minima</h4><p><strong><em>Flat Minima:</em></strong><br> Flat minima correspond to regions in the loss landscape where the loss remains <strong>nearly constant</strong> over a wide range of parameter values. These solutions tend to <strong>generalize better</strong> because they are less sensitive to small perturbations in the input data or model weights.</p><p><strong><em>Sharp Minima:</em></strong><br> Sharp minima are <strong>narrow valleys</strong> in the loss landscape where the loss decreases significantly only in a very small region of the parameter space. These solutions are highly sensitive to small changes in parameters, leading to poor generalization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*4fd859sMpg5PUjy0WzRpgw.png" /></figure><p>Flat minima have smaller second-order derivatives (<strong>Hessian matrix eigenvalues close to zero</strong>), indicating a less steep curvature around the minima. Sharp minima exhibit large second-order derivatives, indicating steep curvature. Flat minima are preferred as they lead to better generalization, especially in non-convex functions like those found in deep learning models. Flat minima are <strong>less sensitive to noise</strong> in data or small perturbations in parameters, making the model more stable. Flat minima are particularly important in deep learning, where the complexity of the model can easily lead to overfitting if sharp minima are reached. The choice of optimizer and hyperparameters can influence whether the optimization algorithm converges to flat or sharp minima.</p><h4>2. Does Global Minima Always Guarantee Optimal Performance?</h4><p>While reaching the global minima ensures the best possible value of the loss function on the <strong>training data</strong>, it does not always guarantee optimal performance on unseen <strong>test data</strong>. Here’s why:</p><ol><li><strong>Overfitting</strong>: In high-dimensional models like neural networks, perfectly minimizing the loss on training data (global minima) can lead to overfitting. This happens when the model <strong>captures noise or specific patterns</strong> in the training data that do not generalize to new data.</li><li><strong>Poor Generalization</strong>: A sharp global minimum might fit the training data perfectly but could result in poor generalization to test data due to <strong>sensitivity to small variations</strong> in input.</li><li><strong>Stochasticity in Data and Optimization</strong>: When using stochastic optimization techniques (e.g., SGD), the loss function’s landscape may vary slightly during training, making it challenging to determine if the global minima is reached or if it is even necessary for good performance.</li></ol><p>Thus, the global minima are ideal in theory, but in practice, models are often designed to balance training loss and generalization error.</p><h3>Conclusion.</h3><p>In the intricate terrain of machine learning optimization, understanding the interplay between local and global minima is paramount for building robust and efficient models. High-dimensional loss landscapes, filled with saddle points and flat regions, present significant challenges to optimization. By leveraging tools like learning rate tuning, advanced initialization strategies, and regularization techniques, practitioners can navigate these complexities effectively. While reaching a global minimum may not always guarantee the best generalization, adopting strategies that promote convergence to flat minima often yields more stable and generalizable models. As machine learning evolves, continuous advancements in optimization techniques will remain critical to unlocking the full potential of complex models.</p><p><em>Thank you for reading!</em></p><p><em>If you’d like, </em><a href="http://linkedin.com/in/harsh-ranjane-159365191"><em>add me on Linkedin.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88bb4de15a94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Cost Functions in Machine Learning: A Complete Guide.]]></title>
            <link>https://medium.com/@harshsranjane03/understanding-cost-functions-in-machine-learning-a-complete-guide-3f58b07f0ec5?source=rss-d918a4bfb487------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f58b07f0ec5</guid>
            <category><![CDATA[kl-divergence]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[cost-function]]></category>
            <category><![CDATA[loss-function]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Harsh S. Ranjane]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 20:54:57 GMT</pubDate>
            <atom:updated>2025-01-12T20:54:57.784Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qIWbUmCIv5ZWVdBEo0v4sA.jpeg" /></figure><h3>Introduction.</h3><h4>1. What is a Cost Function.</h4><p>A cost function in machine learning is a mathematical formula that measures the error or difference between the predicted outputs of a model and the actual target values. It serves as an objective metric that quantifies how well or how poorly a model’s predictions align with the true values. The cost function is crucial in optimization as it provides a direction for improving the model’s performance. By minimizing the cost function, machine learning algorithms adjust their parameters (such as weights and biases) during training. Techniques like gradient descent rely on the cost function to compute gradients, enabling the model to iteratively update its parameters and converge toward the optimal solution. In essence, the cost function acts as a guide, helping the model learn patterns from the data and achieve higher predictive accuracy over time.</p><p>It can be mathematically represented as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*gmby02GebaG4kAuUdgVidg.png" /></figure><h4>2. Cost function vs Loss function.</h4><p>Cost function and Loss function are closely related but serve slightly different purposes. Understanding their distinction is essential for grasping how models evaluate and optimize performance. The loss function measures the error for a single data point. It calculates the difference between the predicted value and the actual value for one instance in the dataset. The cost function, on the other hand, aggregates the losses across the entire dataset to provide a single metric. It is essentially the average or sum of the loss values for all data points. The cost function helps evaluate the overall performance of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*XyxbSgjG5oUSQ0BdZ2DHMQ.png" /></figure><p>The loss function is a component of the cost function. For instance, in Mean Squared Error, the loss is computed for individual predictions, and the cost function aggregates these losses over the dataset by taking their mean.</p><h3>Types of Cost Functions.</h3><h4>1. Cost functions for problems involving regression.</h4><p><strong><em>Mean Squared Error.</em></strong></p><p>MSE is one of the most widely used cost functions for regression. It measures the average squared difference between the actual and predicted values. The formula for MSE is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*Dh7lQ0pEgKBzelyBcWXAng.png" /></figure><p>MSE penalizes larger errors more heavily due to squaring the differences, making it sensitive to outliers. It works well when the errors are normally distributed and smaller variations need to be emphasized.</p><p><strong><em>Mean Absolute Error.</em></strong></p><p>MAE calculates the average of the absolute differences between the actual and predicted values. The formula for MAE is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*dxouWqNRjRxguyB98XMpiQ.png" /></figure><p>Unlike MSE, MAE treats all errors equally by not squaring the differences. This makes MAE more robust to outliers, as it does not disproportionately penalize large errors. However, MAE can be less sensitive to smaller errors, making it less suitable when smaller variations are important.</p><p><strong><em>Huber Loss.</em></strong></p><p>Huber Loss is a combination of MSE and MAE, designed to be robust to outliers while still being sensitive to smaller errors. It uses a threshold parameter to determine whether to use a quadratic loss (like MSE) or a linear loss (like MAE). The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*7BdIpKRzhHtlltE1zqcubA.png" /></figure><p>For small errors, it behaves like MSE, and for large errors, it switches to MAE. This balance makes Huber Loss effective in scenarios with outliers while preserving sensitivity to smaller errors.</p><p><strong><em>MSE vs MAE vs Huber Loss.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*1Vokm0DQ-bw2NCMJxVn54w.png" /></figure><h4>2. Cost function for problems involving classification.</h4><p>In classification problems, cost functions evaluate the difference between the predicted class probabilities or labels and the true labels. Choosing the right cost function is crucial for optimizing the performance of the model. Below are three commonly used cost functions in classification:</p><p><strong><em>Cross-Entropy Loss.</em></strong></p><p>Cross-Entropy Loss is one of the most used cost functions for classification problems, particularly in logistic regression and neural networks. It measures the difference between the true label distribution and the predicted probability distribution. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*gbXMYqwJZ8f6wqd0_qqNuw.png" /></figure><p>Cross-Entropy Loss penalizes incorrect predictions with greater intensity as the predicted probability for the correct class deviates from 1. It is widely used in multi-class classification problems, such as image recognition tasks using neural networks. It ensures the model outputs probabilities that align closely with the true class labels.</p><p><strong><em>Hinge Loss.</em></strong></p><p>Hinge Loss is primarily used for training classifiers like Support Vector Machines (SVMs). It focuses on maximizing the margin between classes and is particularly useful for binary classification. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*eKtuMG2MQS36DSv3pISIFg.png" /></figure><p>Hinge Loss encourages correct classification with a margin, meaning the correct class must be confidently predicted beyond a threshold of 1. It is used for binary classification problems and is a key component of SVMs. Hinge Loss is not ideal for probabilistic predictions but works well for margin-based classifiers.</p><p><strong><em>Kullback- Leibler Divergence (KL Divergence).</em></strong></p><p>KL Divergence measures how one probability distribution P i.e. true distribution, differs from a second distribution Q i.e. predicted distribution. It is often used in probabilistic models like Variational Autoencoders (VAEs) or Bayesian networks. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*dwaSwBIZuRbzStvETaBmxQ.png" /></figure><p>KL Divergence is important for tasks where aligning two probability distributions is critical, such as language models or generative models. It is often used in unsupervised learning and probabilistic classification models. Unlike Cross-Entropy Loss, KL Divergence assumes both true and predicted distributions are valid probability distributions.</p><h4>3. Cost functions for complex problems.</h4><p>Regularization is a powerful technique used in machine learning to prevent overfitting, improve generalization, and deal with high-dimensional data. It does so by adding a penalty term to the cost function that discourages overly large model coefficients. Depending on the problem’s complexity and dataset characteristics, three popular regularization techniques are used:</p><p><strong><em>L1 regularization (Lasso).</em></strong></p><p>L1 regularization adds the sum of the absolute values of the model coefficients ∣θi∣ as a penalty term to the cost function. This type of regularization encourages sparsity in the model, effectively driving some coefficients to zero. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*AZa6kbXGCAqNxZTxEVWCDg.png" /></figure><p>The absolute value penalty forces some feature weights to become zero, effectively eliminating them from the model. This makes L1 regularization an excellent tool for feature selection. L1 regularization is particularly useful for high-dimensional datasets where many features may be irrelevant or redundant. By setting some coefficients to zero, it simplifies the model and makes it more interpretable. Commonly used in sparse data scenarios such as text classification or gene selection problems. However, one of the limitations is that if the dataset has correlated features, L1 tends to select one feature arbitrarily and ignore the others, potentially losing useful information.</p><p><strong><em>L2 regularization (Ridge).</em></strong></p><p>L2 regularization adds the sum of the squared values of the model coefficients as a penalty term to the cost function. Unlike L1, it does not force coefficients to zero but shrinks them closer to zero. L2 does not induce sparsity, making it suitable for problems where most features are relevant. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*TYB_XB0ZNN8-d-B6LZEwsQ.png" /></figure><p>The squared penalty discourages large coefficients, ensuring that no single feature dominates the predictions. This helps reduce overfitting and improves the model’s generalization ability. L2 regularization works well in situations where all features are important and need to contribute to the model. It is especially effective for handling multicollinearity (high correlation between features), as it shrinks correlated features together rather than dropping one of them. Commonly used in regression problems and neural networks to ensure stability and robustness.</p><p><strong><em>Elastic Net.</em></strong></p><p>Elastic Net combines both L1 and L2 regularization, making it a hybrid approach that addresses some of the limitations of using L1 or L2 alone. It introduces a mixing parameter α to control the balance between L1 and L2 penalties. The formula is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*_9l4vI1uY0IMpVqAk7d2Vw.png" /></figure><p>Elastic Net combines the strengths of both L1 and L2:</p><ul><li>The L1 term ensures sparsity by setting some coefficients to zero, performing feature selection.</li><li>The L2 term shrinks coefficients, handling multicollinearity effectively.</li></ul><p>Elastic Net is particularly useful for datasets with many correlated features, as it can retain groups of related features rather than arbitrarily selecting one as L1 does. It is often used in high-dimensional datasets with sparse and correlated features, such as genomics or text data. Elastic Net balances the feature selection and smooth coefficient estimation, however, one if the limitation is that it requires careful tuning of two hyperparameters, which can increase computational cost.</p><h3>Cost Function and Optimization.</h3><p>In machine learning, the ultimate goal is to train a model that performs well on unseen data. This is achieved by minimizing the cost function. Optimization algorithms play a critical role in this process. Below, we discuss important aspects related to cost function minimization and optimization.</p><h4>1. How gradient descent minimizes the cost function.</h4><p>Gradient descent is an iterative optimization algorithm used to minimize the cost function. It calculates the gradient i.e. partial derivatives, of the cost function with respect to the model parameters and uses this information to update the parameters in the direction that reduces the error. The model parameters (θ) are updated iteratively using the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*ln3bLpTXcxkUTVFdW_Qu1w.png" /></figure><p>At each iteration, gradient descent computes the slope of the cost function surface (gradient) at the current point. The parameters are updated by taking a small step in the direction opposite to the gradient (downhill), as this reduces the cost function. This process continues until the algorithm converges to a minimum value of the cost function.</p><h4>2. Role of Learning rate in Cost Minimization.</h4><p>The learning rate (η) is a hyperparameter that controls the size of the step taken during each update of the model parameters. It determines how quickly or slowly the optimization algorithm converges to the minimum of the cost function.</p><p><strong><em>Small Learning Rate:</em></strong></p><ul><li>Takes small steps toward the minimum.</li><li>Leads to slow convergence, requiring many iterations.</li><li>Reduces the risk of overshooting but can get stuck in local minima or take a long time to converge.</li></ul><p><strong><em>Large Learning Rate:</em></strong></p><ul><li>Takes large steps toward the minimum.</li><li>Speeds up convergence but risks overshooting the minimum or diverging if the steps are too large.</li></ul><h3>Conclusion.</h3><p>Cost functions are at the core of machine learning, serving as the compass that guides models toward better predictions. By defining the error between predicted and actual values, they provide a clear metric for optimization algorithms to minimize. From basic problems like regression and classification to complex tasks requiring regularization and probabilistic modelling, choosing the right cost function ensures effective learning and generalization.</p><p>Optimization techniques such as gradient descent, influenced by learning rate adjustments, allow for efficient minimization of cost functions. Understanding and leveraging cost functions effectively equips practitioners to build models that not only fit their training data but also generalize well to unseen data, enabling success in diverse real-world applications.</p><p><em>Thank you for reading!</em></p><p><em>If you’d like, </em><a href="http://linkedin.com/in/harsh-ranjane-159365191"><em>add me on Linkedin.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f58b07f0ec5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Metrics in Machine Learning.]]></title>
            <link>https://medium.com/@harshsranjane03/performance-metrics-in-machine-learning-30207cde8e96?source=rss-d918a4bfb487------2</link>
            <guid isPermaLink="false">https://medium.com/p/30207cde8e96</guid>
            <category><![CDATA[mean-absolute-error]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[performance-evaluation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mean-squared-error]]></category>
            <dc:creator><![CDATA[Harsh S. Ranjane]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 18:27:02 GMT</pubDate>
            <atom:updated>2025-01-12T20:46:40.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lio-xYAS41Dc-N7KlqObow.jpeg" /><figcaption>Image created using DALL.E</figcaption></figure><h3>Introduction.</h3><p>Machine learning, at its core, is the process of enabling machines to learn patterns and make predictions or decisions based on data. This transformative technology has led to the development of numerous algorithms, ranging from neural networks and convolutional neural networks (CNNs) to decision trees and ensemble models. Given the diverse nature of these algorithms, it becomes essential to evaluate their performance effectively for a given problem statement. Without a clear understanding of how well a model performs, it is impossible to determine whether it is suitable for real-world applications.</p><p>Another critical aspect of machine learning involves tuning hyperparameters to optimize model performance. To do so, we need standard evaluation metrics that provide clear insights into how adjustments impact the model’s output. However, performance evaluation is not a one-size-fits-all approach. Different problem statements require unique metrics to measure success accurately. For example, metrics like accuracy, precision, recall, F1 score, and mean squared error are just a few among many, each suited to specific types of tasks. Choosing the right metric is crucial to ensure that the model performs optimally and aligns with the objectives of the task at hand.</p><h3>Generalization in Machine Learning.</h3><h4><strong>A. What is Generalization?</strong></h4><p>Generalization in machine learning refers to a model’s ability to perform well on unseen data, meaning data that was not part of the training process. It is a measure of how effectively a trained model can adapt to new, similar data points without overfitting to the specifics of the training dataset. Here, we assume that the training and the test datasets follow a same probability distribution. Generalization is critical because the ultimate goal of a machine learning model is not just to perform well on the training set but to deliver reliable predictions on real-world data.</p><p>To calculate generalization, we typically evaluate the model’s performance on a separate test dataset or validation dataset. Metrics such as accuracy, precision, recall, F1 score, mean squared error, or others, depending on the task, are used to quantify how well the model generalizes. A smaller gap between training and test performance is a strong indicator of good generalization, whereas a significant difference often points to overfitting or underfitting.</p><h4>B. What is the use of Generalization?</h4><p>The primary purpose of generalization is to ensure that machine learning models remain robust and effective when exposed to new and unseen data. This capability is vital in practical applications, as models are typically deployed in dynamic environments where data distributions may vary. For example, in predictive maintenance, customer behaviour analysis, or medical diagnostics, models must handle data variations while maintaining reliable performance.</p><p>Generalization also helps in making informed decisions during the model selection and tuning process. By evaluating generalization performance, practitioners can identify whether the model complexity is appropriate and adjust hyperparameters to avoid overfitting or underfitting, ultimately leading to a more reliable and scalable solution.</p><h4>C. Relation to Bias and Variance.</h4><p>Generalization is closely linked to the bias-variance trade-off, a fundamental concept in machine learning. Generalization error can be measured as the prediction error (calculated from Training set) over an independent test set or validation set with similar probability distribution.</p><blockquote>Generalization error = Irreducible error + Bias2 + Variance.</blockquote><p>1. Here the irreducible error is unavoidable and cannot be reduced since it is subject to noise in the data, which can be probable over unseen data.</p><p>2. The squared bias term shows the models capability to approximate the real world. High bias means higher assumptions which leads to underfitting.</p><p>3. The variance shows the sensitivity of the model to small fluctuations in the training data. High variance can result in overfitting, where the model learns noise and specifics of the training data rather than the general patterns.</p><p>Achieving good generalization requires balancing bias and variance. A model with low bias and low variance generalizes well, striking the optimal balance between underfitting and overfitting. Techniques such as cross-validation, regularization, and careful hyperparameter tuning are often employed to achieve this balance and improve generalization performance.</p><h3>Validation and Cross-Validation.</h3><h4>A. Validation.</h4><p>Validation in machine learning refers to the process of evaluating a model’s performance on a dataset that is separate from the training data but not entirely unseen. It serves as a checkpoint to ensure that the model is learning appropriately and is capable of generalizing to new data. The most common practice is to split the dataset into training and validation sets, where the training set is used to train the model and the validation set is used to tune hyperparameters, assess performance, and prevent overfitting.</p><h4>B. Cross Validation.</h4><p>Cross Validation or K-fold cross-validation is a more robust and systematic approach to model validation. In this method, the dataset is divided into k equally sized folds. The model is trained on k-1 folds and validated on the remaining fold. This process is repeated k times, with each fold serving as the validation set exactly once. After completing the k iterations, the performance metrics are averaged to provide a more reliable estimate of the model’s generalization ability.</p><p>For example, in 5-fold cross-validation, the dataset is split into 5 parts. The model is trained on 4 parts and tested on the remaining part, rotating the validation fold each time. This ensures that every data point is used for both training and validation, reducing bias in the evaluation and giving a more comprehensive assessment of the model’s performance.</p><h4>C. How do I know which type of validation to use?</h4><p>The choice between standard validation and k-fold cross-validation depends on the size of the dataset and the specific requirements of the task.</p><ul><li><em>Standard Validation:</em> When the dataset is large, a simple train-validation-test split is often sufficient. The model has enough data to learn from, and a single validation set provides a good estimate of its performance. This method is computationally less expensive and works well when computational resources or time are limited.</li><li><em>K-Fold Cross-Validation:</em> For smaller datasets, k-fold cross-validation is preferred as it ensures that every data point is used for both training and validation. This reduces the chances of a biased evaluation caused by an unlucky train-validation split. While it is computationally more intensive, it provides a more reliable estimate of model performance, especially when data is limited or imbalanced.</li></ul><p>K-fold cross-validation is often the default choice for robust model evaluation, but standard validation is a simpler and faster alternative for larger datasets or when computational efficiency is a priority.</p><h3>Metrics for Performance Evaluation.</h3><p>Evaluating the performance of a machine learning model is a crucial step in ensuring its reliability and effectiveness. Different types of problems, such as regression and classification, require specific metrics to measure how well a model performs. For regression tasks, metrics like Mean Squared Error (MSE), Mean Absolute Error (MAE), and R-squared are commonly used to quantify the difference between predicted and actual values. For classification tasks, metrics such as Accuracy, Precision, Recall, F1 Score, and Area Under the Receiver Operating Characteristic Curve (AUC-ROC) provide insights into the model’s ability to distinguish between classes. Choosing the right metric is essential as it directly impacts the interpretation of results and the success of the machine learning solution in solving real-world problems.</p><h4>A. Metrics for Regression.</h4><p><strong>1. Mean Square Error (MSE).</strong></p><p>Mean Squared Error (MSE) is a commonly used metric to evaluate the performance of regression models. It measures the average of the squared differences between the predicted values and the actual target values. The formula for MSE is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*Dh7lQ0pEgKBzelyBcWXAng.png" /></figure><p>MSE penalizes larger errors more heavily than smaller ones due to the squaring of the differences, making it sensitive to outliers.</p><p><strong>1.1 Significance of MSE.</strong></p><p><em>i. Mathematical Convenience:</em> The differentiable nature of MSE makes it a preferred choice for optimization in gradient-based learning algorithms. Its squared term ensures that errors are amplified, leading to smoother gradients, which helps in faster convergence during the training of machine learning models like linear regression and neural networks.</p><p><em>ii. Emphasis on Large Errors:</em> MSE’s sensitivity to large errors is both a strength and a limitation. In applications where large deviations are costly (e.g., financial forecasting or medical diagnostics), MSE serves as an excellent metric since it penalizes these deviations heavily, making the model focus on minimizing them.</p><p><strong>1.2 When should we use MSE as a Performance Metric?</strong></p><p>The decision of using any performance metric in machine learning highly depends on the nature of the problem statement, probability distribution of the underlying dataset and the complexity of the dataset.</p><p>MSE can we used when:</p><p><em>i. Dealing with larger errors:</em> MSE is ideal in the scenarios where the machine learning model is prone to larger, undesirable prediction errors.</p><p><em>ii. Avoiding Outliers:</em> If the dataset is more prone to outliers or noisy measurements, MSE may overemphasize the influence of these anomalies.</p><p><strong>2. Mean Absolute Error.</strong></p><p>Mean Absolute Error (MAE) is a metric used to evaluate the performance of regression models by measuring the average magnitude of errors between predicted values and actual target values. Unlike Mean Squared Error (MSE), MAE calculates the absolute differences without squaring them, which gives equal weight to all errors regardless of their magnitude. The formula for MAE is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*dxouWqNRjRxguyB98XMpiQ.png" /></figure><p>MAE provides a straightforward interpretation as it represents the average error in the same unit as the target variable, making it highly intuitive and easy to understand.</p><p><strong>2.1 Significance of Mean Absolute Error.</strong></p><p><em>i. Robust to Outliers :</em> Unlike MSE, which squares the errors, MAE treats all errors equally. This makes it more robust to outliers, as large errors do not disproportionately impact the overall metric.</p><p><em>ii. Interpretability :</em> Since MAE is calculated in the same unit as the target variable, it provides a direct and interpretable measure of the average prediction error. For example, if the MAE for a housing price prediction model is 5,000, it means the model’s predictions are off by $5,000 on average.</p><p><strong>2.2 When should we use MAE as a Performance Metric?</strong></p><p><em>i. Presence of Outliers:</em> MAE is the preferred choice when the dataset contains outliers or noisy data, as it minimizes the impact of extreme values compared to MSE. For example, in applications like social science data or customer ratings, where outliers are common, MAE provides a more reliable evaluation.</p><p><em>ii. Interpretability Matters:</em> In cases where interpretability in the same unit as the target variable is critical, such as predicting temperatures, sales, or distances, MAE is a better fit.</p><p><strong>3. Coefficient of Determination — R2 (R — Squared).</strong></p><p>The Coefficient of Determination measures the proportion of variance in the dependent variable that is predictable from the independent variable. Essentially, it indicates how well the model explains the variability of the target variable. The formula for R2 is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*tJctjlbnHukXAzIkJUPDuw.png" /></figure><p>R — Squared ranges from 0 to 1, where:</p><ul><li>R — Squared = 1 Perfect prediction (the model explains all variability in the data).</li><li>R — Squared = 0: The model fails to explain any variability, equivalent to using the mean of y (target variable) as the predictor.</li><li>Negative R — Squared : Indicates that the model performs worse than a simple horizontal line (mean value) as a predictor.</li></ul><p><strong>3.1 Significance of Coefficient of Determination.</strong></p><p><em>i. Explains Variance :</em> R — Squared provides a clear measure of how much of the variability in the target variable is explained by the model. For example, an R2 of 0.85 means 85% of the variance in the data is explained by the model, which is useful for understanding the model’s effectiveness.</p><p><em>ii. Model Comparison :</em> It is a standard metric to compare the performance of multiple models trained on the same dataset. Higher R — Squared values indicate better performance.</p><p><em>iii. Global Fit :</em> Unlike MAE or MSE, which measure error magnitude, R — Squared provides a holistic view of how well the model fits the entire dataset.</p><p><em>iv. Diagnostic Tool :</em> A low R — Squared can highlight potential issues such as poor feature selection, missing variables, or inherent randomness in the target variable.</p><p><strong>3.2 When should we use R2 as a Performance Metric?</strong></p><p><em>i. Linear Models :</em> R — Squared is particularly useful in evaluating the performance of linear regression models, where the relationship between variables is linear.</p><p><em>ii. Feature Engineering :</em> It helps determine whether adding new features improves model performance, as a significant increase in R — Squared suggests better explanatory power.</p><p><em>iii. Use with Caution in Non-Linear Models :</em> For non-linear models, R — Squared can be misleading as it assumes linearity in variance explanation. Metrics like adjusted R — Squared, RMSE, or MAE may be more appropriate in such cases.</p><h4>B. Metrics for Classification.</h4><p><strong>1. Accuracy.</strong></p><p>Accuracy is one of the most commonly used metrics in classification tasks. It measures the proportion of correctly classified instances out of the total number of instances. In simpler terms, accuracy tells us how often the model is correct in its predictions.</p><p>The formula for accuracy is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*TVqSjRR7MRrmIZFIPOgJTA.png" /></figure><p>Accuracy is useful when the dataset has a balanced distribution of classes and when the cost of false positives and false negatives is similar.</p><p><strong>2. Misclassification Rate.</strong></p><p>The misclassification rate, also known as the error rate, measures the proportion of incorrect predictions made by the model out of the total number of predictions. It provides an inverse measure of accuracy, indicating how often the model gets it wrong.</p><p>The formula for the misclassification rate is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*7uLxopyTUOnwjpw3-1cDPQ.png" /></figure><p>The misclassification rate is useful in understanding the error proportion and is particularly important in scenarios where even small error rates can have significant consequences, such as fraud detection or medical diagnosis.</p><p><strong>3. Precision.</strong></p><p>Precision is used when particularly when dealing with imbalanced datasets. It measures the proportion of correctly predicted positive instances (true positives) out of all instances predicted as positive by the model. In simpler terms, precision answers the question: “Of all the instances the model predicted as positive, how many are actually positive?”</p><p>The formula for precision is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*zSB_OFq4_ZWsFPddrKJYng.png" /></figure><p>Precision is particularly important in scenarios where the cost of false positives is high. For example, in spam detection, a high precision ensures that only actual spam emails are classified as spam, minimizing the risk of misclassifying important emails as spam.</p><p><strong>4. Recall.</strong></p><p>Recall, also known as Sensitivity or True Positive Rate, measures the proportion of actual positive instances that the model correctly identifies. In other words, it answers the question: “Of all the positive instances in the dataset, how many did the model correctly predict as positive?”</p><p>The formula for recall is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*dSj3ZwVW31tN1RZyenqdmA.png" /></figure><p>Recall is critical in applications where missing a positive instance (false negative) can have severe consequences. For example, in medical diagnosis, a high recall ensures that most patients with a condition are correctly identified, minimizing the risk of missing potential cases.</p><p><strong>5. F1 Score.</strong></p><p>F1 Score is the harmonic mean of Precision and Recall, balancing the trade-off between the two. The F1 Score is particularly useful when we want to consider both false positives and false negatives equally in our evaluation.</p><p>The formula for the F1 Score is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*ZQXSC_C5wffrfKVWLL4P-A.png" /></figure><h3>Conclusion.</h3><p>Performance metrics serve as the backbone of machine learning model evaluation, guiding practitioners in selecting, fine-tuning, and deploying robust models tailored to specific tasks. From understanding generalization and the bias-variance trade-off to applying metrics like accuracy, precision, recall, and MSE, each metric offers unique insights into model behaviour and suitability. By carefully aligning metric choices with problem objectives, we can ensure that machine learning models not only excel in development but also deliver meaningful impact in real-world applications. Whether tackling classification or regression problems, the right performance metrics are instrumental in achieving reliable and interpretable solutions, paving the way for advancements in the field.</p><p><em>Thank you for reading!</em></p><p><em>If you’d like, </em><a href="http://linkedin.com/in/harsh-ranjane-159365191"><em>add me on Linkedin.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30207cde8e96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximum Likelihood Estimation: Here’s what you need to know.]]></title>
            <link>https://medium.com/@harshsranjane03/maximum-likelihood-estimation-heres-what-you-need-to-know-6121a25de194?source=rss-d918a4bfb487------2</link>
            <guid isPermaLink="false">https://medium.com/p/6121a25de194</guid>
            <category><![CDATA[maximum-likelihood]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[likelihood-estimation]]></category>
            <category><![CDATA[probability-distributions]]></category>
            <category><![CDATA[log-likelihood]]></category>
            <dc:creator><![CDATA[Harsh S. Ranjane]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 19:09:33 GMT</pubDate>
            <atom:updated>2025-01-02T19:09:33.710Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XQxMP_bxu7YFqVAvuRvdg.jpeg" /><figcaption>Image generated using DALL.E</figcaption></figure><p>In the realm of statistics and machine learning, understanding the relationship between data, models, and their underlying distributions is pivotal. Maximum Likelihood Estimation (MLE) is a foundational concept that play a central role in this endeavour. This concept, while rooted in probability theory, have widespread applications across diverse fields such as data science, natural language processing, computer vision, and econometrics.</p><p>Maximum Likelihood Estimation (MLE) provides a powerful framework for estimating the parameters of a <strong>probabilistic model</strong> by finding the values that <strong>maximize the likelihood</strong> of observing the given data. It forms the backbone of many machine learning algorithms, offering a systematic and interpretable approach to parameter estimation.</p><p>This article delves into the concepts of MLE, exploring their mathematical foundations, practical significance, and the intrinsic connection between them. By understanding these tools, you’ll gain deeper insights into the <strong>statistical mechanics of model fitting</strong> and the trade-offs inherent in approximating complex probability distributions.</p><h3>Maximum Likelihood Estimator.</h3><p>Maximum Likelihood Estimation (MLE) is a method used to <strong>estimate the parameters of a probabilistic machine learning model</strong>. It identifies the parameter values that make the observed data most likely under the given model based upon the probability distribution of the underlying dataset.</p><p>In simple terms:</p><ol><li><strong>Likelihood Function</strong>: This function measures how <strong>plausible</strong> is the value of the parameter, which is estimated, given the <strong>probability distribution of the underlying data</strong>. This probability can only be formulated using <strong>Bayes Theorem</strong> and not entirely based on nature of parameters itself.</li><li><strong>Maximum Likelihood</strong>: Find the parameter values that maximize this likelihood. This is done by finding the <strong>critical points</strong> for the function by <strong>equating its derivative to 0</strong>. The critical point is where the slope of the function is 0.</li></ol><h3>Where is MLE required?</h3><p><strong>A. You are Building a Probabilistic Model.</strong></p><ul><li>If your model predicts probabilities (e.g., logistic regression, Gaussian Naive Bayes, or Hidden Markov Models), MLE is commonly used to estimate parameters.</li><li>For example, in logistic regression, you use MLE to estimate weights by maximizing the likelihood of the observed binary outcomes.</li></ul><p><strong>B. The Problem Requires Estimating Model Parameters.</strong></p><ul><li>Any time you need to estimate parameters like mean, variance, coefficients, or transition probabilities from data, MLE can be applied.</li><li>Example: Fitting a Gaussian Mixture Model (GMM) to cluster data.</li></ul><p><strong>C. Your Problem Involves Statistical Distributions.</strong></p><ul><li>If your data fits a known distribution (normal, Bernoulli, Poisson, etc.), use MLE to estimate parameters.</li><li>Example: Modelling arrival times in a queue with a Poisson distribution.</li></ul><p><strong>D. Custom Loss Function.</strong></p><ul><li>If the built-in libraries don’t provide the functionality you need, you might need to write the MLE logic manually to define a custom loss function.</li><li>Example: Custom neural networks requiring specific probability distributions for outputs.</li></ul><h3>How does it work?</h3><p><strong>A. Defining the Likelihood Function.</strong></p><p>Suppose we have a dataset <strong>D = {x₁, x₂, …, xₙ}</strong> consisting of n independent and identically distributed observations drawn from a probability distribution with an unknown parameter θ (e.g., mean, variance).</p><p>The <strong>likelihood function</strong> is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*4F1LVwDmgwLGQm8faP1eIA.png" /></figure><p>This formula says the likelihood L(θ∣D) is the product of probabilities of observing each data point xi given the parameter θ.</p><p><strong>B. Adding Natural Logarithm to the function.</strong></p><p>To simplify calculations, we use the natural logarithm of the likelihood function, called the log-likelihood. The likelihood function is often a product of probabilities, which can be cumbersome to differentiate. It also preserves the location of the maximum (since the log function is monotonic). The log of a product becomes the sum of logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*SBZ_-2lqy0D7z9XbWVAQjA.png" /></figure><p><strong>C. Maximizing the Log-likelihood function.</strong></p><p>Since we are maximizing the likelihood of the function, we are looking for the peak of the function. At this peak the function stops increasing and initiates to decrease, i.e. mathematically the slope of the function at that point is 0. The slop of the function is given by its derivative; thus, we equate the derivative of the function to 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*6nJrrPzlXNJb4s_SJivT4Q.png" /></figure><h3>Example Application — House Price Prediction.</h3><p><strong>Problem:</strong></p><p>A real estate agent collects historical data on house prices in a neighbourhood. The prices are assumed to follow a normal distribution, but the <strong>mean (μ)</strong> and <strong>variance (σ2)</strong> are unknown. The agent uses MLE to estimate these parameters.</p><p><strong>Solution:</strong></p><p><strong>1. Collecting Dataset:</strong> Suppose the agent has the following house prices (in $1000s): [250,300,275,325,290]. Let’s assume that these datapoints follow a <strong>Normal Distribution</strong> and we are supposed to estimate the mean (μ) and variance (σ2) for this dataset.</p><p><strong>2. Probability Density Function:</strong> The PDF for a normal distribution is given by the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*G-Av0oNOdVRzSSJ9Ezh-FQ.png" /></figure><p><strong>3. Formulating the likelihood function:</strong> For the above normal distribution, the likelihood function will be formulated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*BvQoS3SGj_cRlqR4DA4gQQ.png" /></figure><p><strong>4. Calculating the Log-likelihood:</strong> We take the natural log for the above equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*icm2gqIthUsKxAUZoAN-2Q.png" /></figure><p><strong>5. Maximizing and calculating for mean:</strong> We differentiate the above equation with respect to μ, to calculate the value of the mean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*_CpBlP0zQtehNAg4z8JILw.png" /></figure><p><strong>6. Maximizing and calculating for variance:</strong> We differentiate the above equation with respect to σ2, to calculate the value of the variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*qpebz5W3ZS347Tj23cbUmQ.png" /></figure><p><strong>7. Substituting the values to find the mean (μ):</strong> We use the above equation for the mean and substitute the values and calculate the actual mean for the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*PP6IqjroJfqo1Mlfu5JBsA.png" /></figure><p>The estimated mean house price is $288,000.</p><p><strong>8. Substituting the values to find the variance (σ2):</strong> We use the above equation for the mean and substitute the values and calculate the actual mean for the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*uNnub3kuiTjawtv4-p1GLw.png" /></figure><p>Thus, using MLE, the agent estimates that house prices in the neighbourhood are normally distributed with a <strong>mean of $288,000</strong> and a <strong>standard deviation of $25,000</strong>. This information can be used to make predictions about future house prices.</p><h3>Conclusion</h3><p>In conclusion, Maximum Likelihood Estimation (MLE) stands as a cornerstone of statistical modelling and machine learning, offering a robust methodology for parameter estimation. By maximizing the likelihood of observed data, MLE enables precise and interpretable outcomes, which are vital for building effective probabilistic models. Its versatility extends across various domains, from regression analysis and clustering to more intricate models like <strong>Gaussian Mixture Models</strong> and custom <strong>neural networks</strong>. The integration of tools like the log-likelihood function further simplifies computational complexities, ensuring MLE’s practicality in real-world scenarios.</p><p>As illustrated through the example of house price prediction, MLE not only estimates parameters like mean and variance but also delivers actionable insights that can guide decision-making. This approach highlights the balance between mathematical rigor and application-driven results. Ultimately, a strong grasp of MLE equips practitioners with the ability to bridge theoretical understanding and practical implementation, fostering innovation and accuracy in data-driven fields.</p><p><em>Thank you for reading!</em></p><p><em>If you’d like, </em><a href="http://linkedin.com/in/harsh-ranjane-159365191"><em>add me on Linkedin.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6121a25de194" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning: Let’s dive into its fundamentals.]]></title>
            <link>https://medium.com/@harshsranjane03/machine-learning-lets-dive-into-its-fundamentals-f886f2ef62c1?source=rss-d918a4bfb487------2</link>
            <guid isPermaLink="false">https://medium.com/p/f886f2ef62c1</guid>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[bias-in-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Harsh S. Ranjane]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 20:05:42 GMT</pubDate>
            <atom:updated>2024-12-23T20:05:42.398Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXzIlyYsaCQg5w8hyfKeUg.jpeg" /></figure><p>So, we basically know that Machine Learning is just about making a “Machine” to “Learn”. But this an abstract statement and there is a lot more depth while we design and build a machine Learning algorithm. In this article, lets dive into the fundamentals of Machine Learning and see as to what type of learning algorithms do exist and what are the concepts involved while designing an algorithm.</p><h3>1. Definition.</h3><p>One of the most quoted definitions of Machine Learning is given by Tom M. Mitchell in his book “Machine Learning” (1997):</p><blockquote>“A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E.”</blockquote><p>In the above definition, 3 essential components of machine learning are mentioned. Let’s break them down into simpler bits using an example. Consider a spam filter which classifies an e-mail as a spam or not. In this case, the Task T is to identify where the incoming mail is spam or not. Now, to accomplish this Task T, the algorithm analyses the data and further calculates the probability of it being a spam mail based on presence of certain words or phrases. This artificial cognition is referred to as Experience E. And the ability to learn Experience E while performing Task T is evaluated using Performance Measure P.</p><p>Some of the common tasks (T) performed using Machine Learning involves classification, regression, clustering etc. and many more. For the evaluation of these algorithms there exists performance measure (P), which quantifies the ability of an algorithm to perform the task. Different task related metrics involved for performance measurement are Accuracy, Precision, Mean Squared Error (MSE), P-norm etc. Machine Learning algorithms currently can only experience the world using the provided datasets. These datasets are subdivided into training and test sets. Using these datasets, the algorithms are supposed to learn different patterns, representations and semantics.</p><h3>2. Types of Learnings.</h3><p>The way of experiencing a dataset is connected to the type of learning. Different types of machine learning algorithms exist depending upon the type of data available like if the data contains labels for each sample or depending upon the complexity of the problem or the goal we are trying to achieve. Each type of learning is designed to handle specific type of data and tasks more effectively. Some of them are listed below:</p><h4>A. Supervised Learning.</h4><p>Consider a dataset representing input features 𝒙i ∈ ℝ and target value as 𝒚i indexed by i. Thus, dataset is represented as,</p><p><em>D = { { 𝒙1, y1 } , { 𝒙i, yi } }</em></p><p>The dataset contains pairs containing input and its labels. The algorithm learns the relationship between the input and its labels and predicts the labels or outputs on unseen inputs. In simpler terms, this algorithm learns from the labelled data i.e. the data where the input and the desired output are known. The goal is to predict the output for the new, unseen input data.</p><p>If we consider an algorithm predicting house prices, the input data consists of features such as the size of the house, location, and number of rooms, while the output is the house price. In supervised learning, the training dataset includes both input features and corresponding labels (house prices). Using this labelled data, along with the number of samples and other parameters, the model learns to predict house prices accurately for unseen data.</p><h4>B. Weakly-supervised Learning.</h4><p>Weakly supervised learning is used when label values (𝑦ᵢ) for the training set are unavailable or unreliable due to the complexity of annotation. This approach involves learning from imperfect, noisy, or incomplete labels, which provide partial supervision.</p><p>Three types of weak supervision are common:</p><p><strong>i. Incomplete supervision:</strong> Only a subset of the data is labelled, while the rest remains unlabelled.</p><p><strong>ii. Inexact supervision:</strong> Labels are present but are not precise.</p><p><strong>iii. Inaccurate supervision:</strong> Labels may contain errors or noise.</p><p>This method is particularly useful when obtaining clean, high-quality labelled data is challenging or costly. Techniques like label noise reduction or generating pseudo-labels for incomplete or inexact data can help address these challenges.</p><p>For example, in image-based object detection, training samples may include object category annotations but lack details like object location or scale within the image. Similarly, in medical imaging, this approach helps handle inconsistencies in annotations provided by radiologists.</p><h4>C. Semi-supervised Learning.</h4><p>Semi-supervised learning combines elements of supervised and unsupervised learning by utilizing a small amount of labelled data alongside a larger pool of unlabelled data. The labelled data guides the learning process, while the unlabelled data helps the model understand the underlying data distribution, ultimately improving its performance.</p><p>Common techniques to use this type of learning involves:</p><p><strong>i. Self-Training:</strong></p><ul><li>A supervised model is trained on labelled data.</li><li>The model predicts pseudo-labels for unlabelled data, which are added to the training set.</li></ul><p><strong>ii. Generative Models:</strong></p><ul><li>Use probabilistic models (e.g., Variational Autoencoders, GANs) to infer the structure of unlabelled data.</li></ul><p><strong>iii. Consistency Regularization:</strong></p><ul><li>The model is encouraged to produce similar outputs for slightly perturbed versions of the same input (e.g., augmentations of images).</li></ul><p>This training approach is widely used in Natural Language Processing tasks, such as training chatbots or building sentiment analysis models, where a small amount of annotated text is combined with a large corpus of unlabelled text. Similarly, in Image Recognition, object detection models are trained using a limited set of labelled data alongside a large collection of unlabelled data, enabling the model to learn effectively despite minimal supervision.</p><h4>D. Self-supervised Learning.</h4><p>Self-supervised learning is a form of unsupervised learning where the system generates pseudo-labels from the input data itself eliminating the need for manually labelling the data, to create a supervised learning problem. The Key Idea is that the model learns by solving a pretext task (Auxiliary tasks), that guides the model to learn useful representations, which helps it to understand the structure of the data without human-labelled annotations. Once the model learns good representations, it can be fine-tuned for downstream tasks like classification or object detection.</p><p>Based on the types of the pretext tasks, supervised learning can be broadly classified into following categories:</p><p><strong>i. Contrastive Learning.</strong></p><p>The concept behind contrastive learning is to learn representations by comparing the data samples and identifying which ones are similar or dissimilar. Model is trained to bring similar representations (Positive pairs) closer and to push dissimilar representations(Negative pairs) farther apart in the embedding space.</p><p>One is the key examples of this type learning is SimCLR (Simple Contrastive Learning of Representations) which is developed by researchers at Google. This framework is used for learning visual representations by performing data augmentation on raw images and creating two different views on each image. Augmented views of the same image are considered as positive pairs, while views of different images are considered as negative pairs.</p><p><strong>ii. Generative Methods.</strong></p><p>Generative methods in self-supervised learning focus on training models to reconstruct or predict parts of the input data. These methods are designed to help models understand and learn the underlying structure or patterns within data by solving tasks related to the generation of data itself. The learned representations are then transferable to downstream tasks, such as classification, regression, or detection.</p><p>Generative methods use reconstruction-based objectives where the model predicts the input data or parts of it. This forces the model to learn meaningful patterns, such as co-relations between features, Global structure of the data, and local relationships within the data. Generative methods involve tasks like Autoencoding, Masked Prediction, Denoising, Generative Adversarial Networks (GANs) etc. This reconstructed signal forces the model to learn rich and generalized representations. It also helps the model to perform well in cross-domain applications involving Images, Videos, Audios and various other data types.</p><h4>E. Unsupervised Learning.</h4><p>Unsupervised learning is a branch of machine learning where the model is trained on data without explicit labels. Unlike supervised learning, which relies on labelled datasets to map input features to output labels, unsupervised learning focuses on discovering hidden patterns, structures, or relationships within the data. It is especially useful when labelled data is scarce or unavailable, allowing the model to extract meaningful insights autonomously.</p><p>At its core, unsupervised learning works by finding similarities or differences between data points, enabling tasks such as clustering, dimensionality reduction, anomaly detection, and generative modelling. For example, in clustering, the model groups similar data points together based on shared characteristics. This can be useful in customer segmentation, where businesses group customers by purchasing behaviour or preferences. Dimensionality reduction is another application, which condenses high-dimensional data into a smaller set of meaningful features, often used for data visualization or pre-processing for downstream tasks.</p><p>Some of the key algorithms used in unsupervised learning include:</p><p><strong>i. K-means Clustering </strong>— which partitions data into distinct groups.</p><p><strong>ii.</strong> <strong>Hierarchical clustering</strong> — which creates nested clusters.</p><p><strong>iii.</strong> <strong>Autoencoders </strong>— Type of Neural Network, which play a crucial role in learning compressed representations of input data while reserving its key features.</p><h3>3. Parameters and Hyperparameters.</h3><p>In Machine Learning, a model is defined or represented using its model parameters. While training a model, one must choose optimal hyperparameters that will help the learning algorithm to learn optimal parameters which eventually maps a relationship between input features and the ground truth.</p><blockquote>“Ground truth refers to data that is known to be accurate and is used to train and test AI model outputs. In Machine Learning it is commonly referred to describe the ideal expected result, serving as a benchmark for evaluating the performance of models or algorithms.”</blockquote><h4>A. Parameters.</h4><p>Parameters are the internal variables of a model that are learned from the training data. They determine how the model processes the input data to produce the output data. Parameters are core components of a machine learning model which are formulated and updated during the training process to minimize the loss function.</p><blockquote>“A loss function is a mathematical function that measures the difference or error between the predicted output of a model and the actual target values. It quantifies how well or poorly the model is performing, guiding the learning process to minimize this error.”</blockquote><h4>How are the Parameters calculated and updated during the training process?</h4><p>The calculation and updating of parameters occur iteratively during the training process using the below processes:</p><p><strong>i. Initialization:</strong></p><p>Parameters are typically initialized to small values of zeros before the training process. This provides a starting point to the optimization process before convergence.</p><p><strong>ii. Forward propagation.</strong></p><p>The model computes the predictions using the provided input features. An activation or hypothesis function is formulated during this process which determines the predictions.</p><p><strong>iii. Loss Calculation.</strong></p><p>The loss function after the forward propagation quantifies the error i.e. difference between the input features and the predictions</p><p><strong>iv. Backward Propagation.</strong></p><p>The gradient of the loss function with respect to each parameter is calculated using the chain rule of the calculus. This determines how each parameter affects the loss.</p><p><strong>v. Iterations.</strong></p><p>This process is repeated for multiple epochs (iterations over the dataset) until the model converges, i.e. the loss stops decreasing significantly.</p><p>Well-optimized parameters allow the model to generalize to unseen data. Overfitting or underfitting is a sign of poorly chosen or inadequately trained parameters. The values of the parameters directly influence the accuracy of the model. Properly tuned parameters minimize the error and improve the model’s reliability. The number of parameters reflects the complexity of the model. More parameters can capture complex relationships but might lead to overfitting. Fewer parameters may lead to underfitting if the model is too simple.</p><h4>B. Hyper-parameters.</h4><p>Hyperparameters are configuration settings in machine learning model that are set before the training process begins. Hyperparameters are external to the model and control the training process and the structure of the model.</p><blockquote>“Hyperparameter is a parameter which parametrizes the choice of parameters.”</blockquote><p>Hyperparameter tuning involves finding the optimal values of the hyperparameters to achieve the best performance for a model. The process is iterative and can be done manually or using automated techniques. Some of the techniques are mentioned below:</p><p><strong>i. Grid Search.</strong></p><p>This method systematically searches through a pre-defined set of hyperparameter combinations. This method is exhaustive and is computationally expensive for a larger parameter space.</p><p><strong>ii. Random Search.</strong></p><p>This method randomly samples combinations for hyperparameters from the search space and is often more efficient than Grid search for larger parameter space.</p><p><strong>iii. Bayesian Optimization.</strong></p><p>This method uses probabilistic models like Gaussian Processes which uses probabilistic calculations to model the object function of tuning the hyperparameter. It iteratively selects hyperparameter values that are likely to improve performance based on prior evaluation.</p><p>Let’s consider a neural network as example. The hyperparameters in that case would be:</p><p><strong>i. Learning rate:</strong> This controls the rate as to how much a model should update in response to estimated error each time the model weights are updated. A high learning rate leads to unstable training or divergence because overshoots to the optimal point on the other side, low-rate results into slower convergence, potentially causing the model to get stuck in a local minimum.</p><p><strong>ii. Number of Epochs:</strong> This is the number of times the algorithm will iterate over the dataset to reduce the loss function. If the number of epochs is low it may result in underfitting and if the number is high model is vulnerable to overfitting.</p><p><strong>iii. Batch Size:</strong> This is the number of training samples utilized in one iteration. A smaller batch size may provide frequent updates but may add noise to training and leads to slower training. While a larger batch size results in faster computations but may lead to poor generalization.</p><p><strong>iv. Network Architecture:</strong> This is the number of hidden layers and neurons in each layer. A shallow architecture with a smaller number of layers may lack the capacity to capture complex patterns which may lead to underfitting while a deep architecture is more prone to overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*DL66WuKoy-x_jJkRG5jNSQ.jpeg" /></figure><h3>4. Bias and Variance.</h3><p>Bias, variance, and model complexity are critical concepts in machine learning that influence model performance. Bias refers to errors due to overly simplistic assumptions, leading to underfitting, where the model fails to capture the underlying patterns in the data. Variance represents sensitivity to small fluctuations in the training data, causing overfitting, where the model captures noise instead of general trends. Model complexity balances bias and variance; simple models tend to have high bias but low variance, while complex models exhibit low bias but high variance. Striking the right balance between these factors is essential for achieving optimal performance and generalization on unseen data.</p><blockquote>“Bias and Variance are interdependent factor which can be difficult to visualize but relatively easier to mitigate if we strike a perfect tuning”</blockquote><h4>A. Bias.</h4><p>Bias originates from the assumption made by the machine learning algorithm about the data’s structure to simply the learning and decision-making process. These assumptions are inherent to the model and can influence the training process significantly. Bias is a systematic and intentional or non-intentional deviation from the actual values which prevents the system from learning actual values (i.e. Overfitting) from the input data.</p><p>Bias usually has an algorithm-dependent nature i.e. for example considering a linear regression model, the model will evidently have a high bias, as it assumes a linear relationship between the input features and the output. Also, Decision trees are usually bound to have a low bias, since it needs more precise spilt functions at every step and eventually tries to fit in more complex patterns. Bias can also be intentional, for example, regularization techniques like L1 and L2, which are commonly used in regression and neural networks, introduce bias deliberately to avoid overfitting.</p><h4>How does Bias affect a Machine Learning Algorithm?</h4><p><strong>i. Bias can determine the complexity of functions a model can learn:</strong></p><ul><li>For example, a linear classifier in SVM will evidently mis-classify non-linear patterns, no matter how much huge data is available.</li><li>The kernel tricks in SVM can help to reduce the bias by mapping the input data to higher dimensions and capture non-linear complex relationships.</li></ul><p><strong>ii. Training Data size.</strong></p><p>Smaller dataset usually leads to algorithmic bias, as the model assumes patterns from limited data and generalizes poorly. Higher complexity algorithms like neural networks which are known to extract complex patterns effectively may perform poorly in such scenarios.</p><p><strong>iii. Machine Learning Pipelines.</strong></p><p>In end-to-end pipelines, which involves sequential steps like pre-processing, feature extraction, model training, bias from earlier stages propagates and often amplifies.</p><h4>B. Variance.</h4><p>Variance in machine learning measures the variability of a model’s predictions due to changes in the training data. It reflects how much the model depends on the specific data it was trained on. If a model is highly sensitive to training data changes, it has high variance. If it is less sensitive, it has low variance.</p><p>Variance arises from the model’s complexity and its attempt to fit the training data. Complex models (e.g., high-degree polynomial regression, deep neural networks) tend to have high variance as they attempt to capture every subtle detail of the data, including noise.</p><blockquote>“Variance is not only about sensitivity to data but also the model’s susceptibility to algorithmic instability.”</blockquote><h4>How Does Variance Affect a Machine Learning Algorithm?</h4><p>Variance plays a critical role in determining how well a machine learning model generalizes to unseen data. Its effects include:</p><p><strong>i. High Variance:</strong></p><ul><li>A model with high variance performs exceptionally well on the training data but poorly on the test data.</li><li>It captures not only the underlying patterns but also the noise in the training data, leading to poor generalization.</li></ul><p>Example: A decision tree grown to its maximum depth can overfit the training data.</p><p><strong>ii. Low Variance:</strong></p><ul><li>A model with very low variance may be too simple to capture the complexity of the data.</li><li>This often results from using overly restrictive models or not providing enough flexibility for the model to learn the underlying patterns.</li></ul><p>Example: Linear regression on a dataset with a non-linear relationship.</p><h4>What is the significance of Variance in a Machine Learning Algorithm?</h4><p><strong>i. Variance Reduction Techniques:</strong></p><ul><li>Regularization: Techniques like L1 and L2 regularization add penalties to the loss function to reduce the model’s complexity, thereby controlling variance.</li><li>Bagging: Bootstrap aggregating reduces variance by averaging predictions from multiple models trained on different subsets of the data.</li><li>Pruning in Decision Trees: Removing unnecessary branches helps avoid overfitting, thus reducing variance.</li></ul><p><strong>ii. Variance in Model Diagnostics:</strong></p><ul><li>Variance is crucial when performing cross-validation. A large variance in cross-validation scores across different folds suggests overfitting.</li><li>While cross-validation typically involves dividing the dataset into k folds, repeated k-fold cross-validation (repeating the process with different random splits) provides a better estimate of variance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMEY-Hv8wRVSWafID7U88w.png" /></figure><h4>C. Bias-Variance Trade-off.</h4><p>The Bias-Variance Trade-off is a fundamental concept in machine learning that explains the balance between two types of errors a model can make: bias and variance. This trade-off is important because it helps us find the sweet spot where the model performs well on both training and unseen (test) data. If the model has high bias, it will underfit, meaning it performs poorly because it doesn’t capture the true patterns in the data. If the model has high variance, it will overfit, meaning it performs well on the training data but poorly on test data because it learned noise instead of patterns. The goal is to build a model that has just the right balance of bias and variance, minimizing total error and ensuring good generalization to new data.</p><h3>5. Conclusion.</h3><p>Machine learning is a multifaceted discipline that bridges data, algorithms, and computational power to enable systems to perform tasks with increasing efficiency over time. By understanding its fundamental components, one can appreciate the diversity of approaches available for tackling a wide array of problems. The roles of parameters and hyperparameters further underscore the need for precise tuning and optimization to achieve reliable and efficient models. Moreover, the interplay between bias, variance, and model complexity highlights the fine balance required to ensure robust generalization to unseen data. Ultimately, machine learning empowers us to uncover patterns and insights from data, driving innovation and transformation across industries and shaping the future of technology.</p><p><em>Thank you for reading!</em></p><p><em>If you’d like, </em><a href="http://linkedin.com/in/harsh-ranjane-159365191"><em>add me on Linkedin.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f886f2ef62c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence, Machine Learning and Deep Learning: A comprehensive look.]]></title>
            <link>https://medium.com/@harshsranjane03/artificial-intelligence-machine-learning-and-deep-learning-a-comprehensive-look-227fb979284e?source=rss-d918a4bfb487------2</link>
            <guid isPermaLink="false">https://medium.com/p/227fb979284e</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Harsh S. Ranjane]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 18:47:35 GMT</pubDate>
            <atom:updated>2024-12-23T18:56:27.318Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdSvKhTJTbhu9LgmI70SYA.jpeg" /></figure><h3>1. What is Artificial Intelligence, do we really need it?</h3><p>Artificial Intelligence (AI) is the <strong>ability</strong> of a computer or machine to perform tasks that usually require human intelligence and interference. This includes things like learning from experiences, understanding language, solving problems, and making decisions. In simple terms, AI is when machines are designed to think, learn, and act like humans in certain ways, without needing constant human input.</p><p>Do we always need it? No really, we do not need Artificial Intelligence integrated into <strong>every</strong> daily application of ours. AI systems can be <strong>resource-intensive</strong>, <strong>requiring significant computational power</strong>, which can strain the system. Additionally, training AI models is often <strong>complex</strong>, <strong>time-consuming</strong>, and <strong>expensive</strong>. For some applications, simpler solutions may be more efficient and effective, as not every task requires the sophistication of AI.</p><blockquote>“AI isn’t a tool — it’s an Agent”</blockquote><p>Overusing AI can also lead to unnecessary dependencies, making systems more prone to errors and harder to maintain. Furthermore, integrating AI where it isn’t essential can raise ethical concerns, such as <strong>data privacy risks</strong> or <strong>bias in decision-making</strong>. It’s important to carefully evaluate whether AI genuinely adds value to an application or if traditional methods are more practical and sustainable.</p><p>The <strong>Black box</strong> Large Language AI models that we use in our day-to-day life like Chat-GPT, Gemini, Co-pilot etc. also have a significant environmental impact. A recent study by University of California revealed the significant water footprint of Chat-GPT 3 for training purposes which was approximately <strong>700000 litres</strong>. Additionally, detailed calculations revealed that per every query on Chat-GPT, <strong>4.2 grams</strong> of <strong>CO2</strong> is emitted. This is a substantial amount considering its billions of users.</p><p>AI systems are unnecessary in situations where operations can be performed <strong>empirically</strong>, and an <strong>analytical solution</strong> to the problem already exists. If a function can directly and accurately solve the problem, developing an AI system to approximate the same function using various input parameters is redundant and inefficient.</p><p>Moreover, relying on AI in such cases not only wastes resources but also introduces potential errors during training and prediction. <strong>Analytical solutions</strong> are often more reliable, interpretable, and easier to implement. Therefore, it’s more practical to prioritize straightforward mathematical or logical methods when they are sufficient to solve a problem.</p><blockquote>Occam’s Razor is the principle that states: “The simplest explanation, with the fewest assumptions, is usually the best.”</blockquote><p>For example, for basic mathematical functions like Addition, subtraction, Integration etc. we do not need to build an AI model, a simple calculator can do the work. Point being, according to <strong>Occam’s Razor</strong>, there’s no need to complicate the solution (by developing and training an AI model) when a simpler, more direct approach works efficiently and effectively. Over-engineering in such scenarios violates the principle of simplicity and can lead to wasted resources without providing additional value.</p><h3>2. So, where should we exactly use Artificial Intelligence?</h3><p>AI models should be used strategically in areas where they provide clear and measurable benefits, addressing problems that traditional methods cannot solve efficiently or consume a significant time and effort. Their strength lies in handling complex tasks like <strong>pattern recognition</strong>, <strong>data analysis</strong>, and <strong>decision-making at scale</strong>, making them invaluable in sectors such as <strong>healthcare</strong>, <strong>finance</strong>, <strong>education</strong>, etc. For instance, in healthcare, AI can be used for early disease detection, personalized treatment recommendations, and drug discovery. In finance, AI excels at fraud detection, credit risk assessment, and algorithmic trading. Similarly, AI-powered tools in education provide personalized learning experiences, automated grading, and adaptive content delivery, while in transportation, AI optimizes traffic flow, enables autonomous vehicles, and improves logistics.</p><p>To use AI effectively, organizations and individuals must first <strong>assess</strong> whether it is genuinely necessary for a specific application. <strong>Ethical considerations</strong> should also play a critical role in determining the use of AI. Developers and organizations must ensure the responsible handling of data, addressing concerns like <strong>privacy</strong>, <strong>bias</strong>, and <strong>fairness</strong>.</p><p>AI works best when it <strong>complements human expertise</strong> rather than replaces it. Integrating AI systems should aim to augment human capabilities, enabling better decision-making and improving overall efficiency. The focus should be on applications where AI delivers meaningful value — simplifying processes, enhancing accuracy, and solving complex challenges. By carefully evaluating the need, ensuring ethical implementation, and balancing automation with human oversight, AI can be a powerful tool that drives innovation while remaining practical and sustainable.</p><h3>3. What are these concepts: Machine Learning and Deep Learning.</h3><h4><strong>3.1 Machine Learning.</strong></h4><p>The name itself explains the concept, making the ‘<strong>Machine</strong>’ ‘<strong>Learn</strong>’. Machine Learning is the way of teaching machines to learn using data to make <strong>decision</strong> or <strong>predictions</strong>, without explicitly programming it for every individual task. Machine Learning is a <strong>subset</strong> of Artificial Intelligence, where AI refers to broader concept about development of systems that stimulate <strong>human intelligence</strong>. Machine Learning is way to develop such tools which stimulate human intelligence.</p><p>Data is analysed for <strong>learning patterns</strong>, <strong>semantics</strong> and <strong>representations</strong> and these help in formulating predictions. It is an effective method since large amounts of data can quickly be analysed, it updates to new information and this can be used to solve complex problems, which can be difficult to be solved by traditional programming.</p><p>For example, a <strong>spam filter</strong> in your email uses machine learning to recognize and block spam messages by analysing patterns like <strong>keywords</strong> or <strong>sender behaviour</strong>. Another example is a <strong>recommendation system</strong>, like Netflix suggesting movies based on what you’ve watched and liked before. These systems learn from data and continuously improve, making our lives easier and more efficient.</p><h4>So how does it Machine Learning work?</h4><p>For prediction of the <strong>ground truth</strong>, different algorithms are used based on the <strong>interpretability</strong> of the problem, <strong>nature</strong> of the input data whether complex or simple patterns are to be analysed, or <strong>scalability</strong> of the system where computational efficiency is the concern. Some of these algorithms are listed below:</p><p><strong>A. Linear Regression.</strong></p><p><strong>When to use it</strong>:</p><ul><li>If your goal is to predict a <strong>numerical value</strong> based on input features.</li><li>When the relationship between your features and the target variable is <strong>linear </strong>or approximately linear.</li><li>If you need a simple, interpretable model that explains how different features contribute to predictions.</li></ul><p><strong>Example</strong>:</p><ul><li>Predicting house prices based on size, location, and number of bedrooms.</li></ul><p><strong>B. K-Nearest Neighbours (KNN).</strong></p><p><strong>When to use it</strong>:</p><ul><li>When you need a simple, intuitive algorithm for <strong>classification</strong> or <strong>regression</strong>.</li><li>When your data is small and not too high-dimensional (because KNN can be computationally expensive for large datasets).</li></ul><p><strong>Example</strong>:</p><ul><li>Classifying whether a plant is a type of flower or weed based on features like petal size and colour.</li></ul><p><strong>C. Logistic Regression.</strong></p><p><strong>When to use it</strong>:</p><ul><li>For binary classification problems (e.g., yes/no).</li><li>When the relationship between the features and the target variable can be modelled using a logistic (S-shaped) curve.</li></ul><p><strong>Example</strong>:</p><ul><li>Predicting whether an email is spam or not.</li></ul><h4>3.2 Deep Learning</h4><p>Deep Learning is a specialised type of Machine learning that uses structures called as <strong>neutral networks</strong>, which is inspired by how human brain works, to learn and make decisions. Deep learning is inspired by <strong>Cognitive Neuroscience</strong> (a.k.a Neuropsychology) as it explains complex cognitive processes of the human brain. The neural networks consist of different layers characterized by <strong>weights</strong> and interconnected <strong>nodes </strong>(just like neurons) which process information in a hierarchical way i.e. starting with learning of simple absolute patterns and gradually diving deep into complex patterns.</p><p>Deep learning is an effective and efficient way for working with <strong>large amounts of data</strong>, such as images and videos, or even text, because it can automatically identify important features in an effective manner relative to other machine learning algorithms.</p><p>For example, deep learning powers <strong>facial recognition systems</strong> by analysing key facial features, and it’s used in self-driving cars to detect pedestrians, traffic signs, and lanes. It’s also behind <strong>virtual assistants</strong> like Alexa or Google Assistant, enabling them to understand and respond to voice commands accurately.</p><h4>How does Deep learning work?</h4><p>Deep learning works by using neural networks with <strong>multiple layers</strong> to process data and automatically learn patterns from it. Each layer extracts <strong>features</strong>, starting with simple ones (e.g., edges) and progressing to more complex representations (e.g., faces or objects). You should use deep learning when you have large amounts of labelled data, complex tasks like image recognition or natural language understanding, and access to significant computational resources. It is ideal for scenarios where traditional machine learning fails to capture <strong>intricate patterns</strong> in data. Deep learning is most effective when feature extraction and decision-making need to happen automatically. Below are some of the commonly used deep learning algorithms:</p><p><strong>A. Convolutional Neural Networks:</strong></p><p>CNNs are designed to process and analyse visual data, such as images or videos. They work by breaking an image into small parts (like patches or filters) and scanning for patterns such as edges, shapes, or textures. These patterns are then combined to recognize the bigger picture, like identifying a cat in an image. CNNs are great for tasks like image classification, object detection, and facial recognition because they focus on important features in the data and ignore irrelevant details.</p><p><strong>B. Recurrent Neural Networks:</strong></p><p>RNNs are used for analysing <strong>sequential data</strong>, like time series, speech, or text, where the order of the data matters. They work by remembering information from previous steps while processing new data. For example, when predicting the next word in a sentence (“I am going to the ___”), an RNN remembers the context of earlier words to guess the next word correctly (e.g., “store” or “park”). This memory-like behaviour makes RNNs effective for <strong>language translation</strong>, <strong>speech recognition</strong>, and <strong>stock price prediction</strong>.</p><p><strong>C. Generative Adversarial Networks:</strong></p><p>GANs consist of two parts: a <strong>generator</strong> and a <strong>discriminator</strong>. The generator creates fake data (like realistic-looking images), and the discriminator tries to distinguish between the real and fake data. Both parts compete with each other, and over time, the generator becomes so good that the fake data looks almost real. GANs are widely used for creating <strong>realistic images</strong>, <strong>enhancing photo</strong> quality, and even <strong>generating deepfake videos</strong>.</p><h3>Conclusion</h3><p>Artificial Intelligence, Machine Learning, and Deep Learning are transformative technologies that have reshaped how we approach complex problems and interact with the world. While AI enables machines to replicate human-like intelligence, Machine Learning and Deep Learning provide the <strong>means</strong> to process and analyse data in innovative ways, driving advancements across diverse fields like healthcare, finance, education, and transportation. However, <strong>AI is not a universal solution</strong>. Its integration must be thoughtful and strategic, ensuring it <strong>adds real value</strong> while addressing challenges such as resource consumption, ethical concerns, and environmental impact. Simpler, traditional approaches should not be overlooked when they are sufficient for solving problems efficiently.</p><p>In conclusion, the key to harnessing AI lies in balancing its immense potential with responsible and practical application. By using AI to <strong>complement human expertise</strong>, we can solve complex challenges, improve efficiency, and create impactful innovations. At the same time, prioritizing ethical considerations, sustainability, and simplicity ensures that AI remains a tool for progress without unnecessary complications or negative consequences. With the right approach, AI has the power to <strong>revolutionize industries</strong> while maintaining a strong foundation of practicality and responsibility.</p><p><em>Thank you for reading!</em></p><p><em>If you’d like, </em><a href="http://linkedin.com/in/harsh-ranjane-159365191"><em>add me on Linkedin.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=227fb979284e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>