<?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 Aymen Boukhari  on Medium]]></title>
        <description><![CDATA[Stories by Aymen Boukhari  on Medium]]></description>
        <link>https://medium.com/@aymne011?source=rss-c1b8e0a2a743------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*G3MKPk_Mqta4IpbtfW_4_A.jpeg</url>
            <title>Stories by Aymen Boukhari  on Medium</title>
            <link>https://medium.com/@aymne011?source=rss-c1b8e0a2a743------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:55:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aymne011/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[Variational Autoencoders (VAEs)]]></title>
            <link>https://medium.com/@aymne011/variational-autoencoders-vaes-24f5da384a9d?source=rss-c1b8e0a2a743------2</link>
            <guid isPermaLink="false">https://medium.com/p/24f5da384a9d</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[variational-autoencoder]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Aymen Boukhari ]]></dc:creator>
            <pubDate>Tue, 22 Oct 2024 00:17:03 GMT</pubDate>
            <atom:updated>2024-10-22T00:17:03.253Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, VAEs have been considered one of the approaches to <strong>unsupervised learning</strong> (learning from data without labels), showing success in many fields like handwritten digit generation, face generation, physics modeling, and more. In this blog, we will explore the power of VAEs. So, let’s get started — grab a cup of coffee!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N1RTn6Xigaqz17bbd-JMBg.jpeg" /></figure><h4><strong>1 . All About Generative Models:</strong></h4><p>We can formalize generative models as models that attempt to learn a distribution P(X) from a set of samples X, where X is drawn from an unknown distribution Pgt​(X) (ground truth distribution). For example, X could be a set of faces, handwritten digits, etc. One approach to modeling this is using <strong>Variational Autoencoders (VAEs)</strong>, which allow us to formalize the problem as a probabilistic model.</p><h4><strong>2 . What are VAEs:</strong></h4><p>Like all types of <a href="https://en.wikipedia.org/wiki/Autoencoder"><strong>autoencoders</strong></a>, <strong>Variational Autoencoders (VAEs)</strong> are deep learning models that consist of an <strong>encoder</strong> and a <strong>decoder</strong>. The encoder learns important features from the data and maps it to a latent variable Z, which <strong>captures a compressed representation of the input</strong>. The decoder then uses Z to <strong>reconstruct the input data</strong>. During training, the model optimizes both the reconstruction error and the latent space distribution using <strong>backpropagation</strong>. Unlike traditional autoencoders, VAEs introduce a <strong>probabilistic approach</strong> by assuming that the <strong>latent variable Z follows a known distribution (usually Gaussian)</strong>, and the encoder learns the parameters of this distribution (mean and variance) to generate <strong>Z stochastically (</strong>variable is drawn from a probability distribution rather than being determined exactly or deterministically) <strong>.</strong> This allows for better generalization and control over the latent space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*P7aFcjaMGLwzTvjW3sD-5Q.jpeg" /></figure><h4><strong>3 . Latent Variable Models:</strong></h4><p>One of the more complex challenges in generating data is how to train models that can learn the dependencies between the features of our data (e.g., pixels in images). For example, if we want to model the distribution of handwritten digits and generate the number 5, we don’t want the model to generate an image that’s half a 5 and half a 0. This is where the concept of a <strong>latent variable</strong> comes in. Latent variables capture underlying features or structure from our data. For example, in generating handwritten digits, the model might first decide which character to generate (e.g., a 5) before assigning values to any specific pixels. This helps ensure coherence in the generated output by allowing the model to encode high-level decisions before focusing on finer details.</p><p><strong>Latent variable models</strong> take a probabilistic approach to describe the probability distribution of x, P(x), by using the marginal probability P(x,z), where z represents the latent variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*9mw5vThyLGzgGQv0vDAGhw.png" /><figcaption><strong>Equation 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*KdZ27InO-9XCmw8GR6yRMw.png" /><figcaption><strong>Equation 2</strong></figcaption></figure><p>In this formulation, we assume that P(z) is a multivariate normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*1z12BRrN2UtASTFqg9W_BA.png" /><figcaption><strong>Equation 3</strong></figcaption></figure><p>Additionally, the likelihood P(x∣z,θ) is also assumed to be <strong>normally distributed</strong>. Its <strong>mean is a nonlinear function f(z,θ) </strong>, which is learned by a <strong>neural network based on the latent variable </strong>, and its covariance σ2I (introducing some noise around the mean).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*tf3T4d20e2J1fBy_GSYILA.png" /><figcaption><strong>Equation 4</strong></figcaption></figure><p>So, the first formula becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*iwQptoLgGojYGDc87gEhwQ.png" /><figcaption><strong>Equation 5</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*zhgDVNyLMQQZ3vLg6m8VlQ.png" /><figcaption>(source : Understanding Deep Learning book)</figcaption></figure><h4><strong>4 . Training:</strong></h4><p>Like any machine learning model, to train this model, we aim to maximize <strong>Equation 5</strong> (see above), which means maximizing the log probability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*suwQuI6G3C6lJAnyYe8XkA.png" /><figcaption><strong>Equation 6</strong></figcaption></figure><h4><strong>5 . Intractabilities :</strong></h4><p>To compute the integral in <strong>Equation 5</strong>, we encounter a problem: the intractability of the posterior distribution P(z∣x).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*RNzlsM_qblX4WowJl7qwrg.png" /><figcaption><strong>Equation 7</strong></figcaption></figure><p>In <strong>Equation 7</strong>, when we try to calculate P(z∣x), we need to calculate P(x). However, in <strong>Equation 5</strong>, to calculate P(x), we need to compute P(x∣z). This <strong>creates a contradiction</strong>, much like the classic question of “Which came first, the chicken or the egg?”</p><h4><strong>7. Variational Autoencoders: The Solution!</strong></h4><p><strong>VAEs </strong>address this problem by introducing a parametric inference model, commonly known as the encoder or recognition model. Instead of calculating the true posterior Pθ​(z∣x), we approximate it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*zWNLzOGnARbL9Cdub_InBw.png" /><figcaption><strong>Equation 8</strong></figcaption></figure><p>The distribution with parameters ϕ can be parameterized using neural networks, where the outputs are the mean and the variance (see Equation 9).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*u0jzCjJZMpp2jsqNLKAxCw.png" /><figcaption>equation 9</figcaption></figure><h4><strong>8. Evidence Lower Bound (ELBO)</strong></h4><p>The term “evidence” comes from Bayesian statistics, where it refers to the likelihood P(x∣θ). We call it “evidence” because if we choose good parameters and the right model, P(x) will be high, indicating that we are on the right track. In other words, this quantity serves as evidence that we have chosen the right model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*hVz8HV6PkynN9F4w_PLTPA.png" /><figcaption>equation 9</figcaption></figure><p>The derivation of the formula above is straightforward; it simply requires applying <strong>Jensen’s Inequality</strong>.</p><p>If you’re wondering about the gap between the <strong>ELBO</strong> (right term in <strong>Equation 9</strong>) and the <strong>evidence</strong> (left term in <strong>Equation 9</strong>), it is the <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence"><strong>Kullback-Leibler (KL) divergence</strong></a> between P(z∣x;θ) and q(z). (You can prove this!)</p><p>We can also express the <strong>Evidence Lower Bound (ELBO)</strong> as the reconstruction error (generation) minus the distance to the prior (decoding):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*yeC8MpdnVdyGs1SmpiW8oA.png" /><figcaption>equation 10</figcaption></figure><p><strong>Just to avoid confusion, q(z∣x;θ) is Gaussian distributed, with its mean and variance obtained through neural networks.</strong></p><h4>9 . VAE algorithm !</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*suyLawOf2lOeuyrHRlquSQ.png" /><figcaption>(source : Understanding Deep Learning book)</figcaption></figure><p>So far, what we’ve done can be summarized as follows: First, we take our input data and pass it through the encoder (a neural network) to get the mean and variance as outputs. We then construct the distribution q(z∣x,θ) and sample from this distribution to obtain z∗. Next, we pass z∗ to the decoder, which generates the output x∗ Finally, we compute the ELBO (our loss function) and use backpropagation to optimize the model.</p><p><strong>But we have a probelem which is the network involves a sampling step, and it is difficult to differentiate through this stochastic component !!!!</strong></p><h4><strong>10. The Reparameterization Trick is the Solution!!</strong></h4><p>Simply, we draw a sample ϵ from N(ϵ∣0,I) and then use the following relation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*A07yoMPbcJyibciQ7JkV6A.png" /><figcaption>equation 10</figcaption></figure><h4><strong>11 . Some results using VAEs :</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*b0AcG-0OiZfKD3A6NGH-TA.png" /><figcaption>Samples from a VAE trained on MNIST (source : paper )</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*yu9v7VuBfWi7hVAmCiN7RQ.png" /><figcaption>Latent space of MNIST using VAEs</figcaption></figure><p>To code <strong>Variational Autoencoders (VAEs)</strong> from scratch using <strong>PyTorch</strong>, visit <a href="https://github.com/aymen-000/DEEP_LEARNING_ALGORITHMS/tree/main/VAE">my GitHub</a> 🚀💻✨</p><p><strong>Resources:</strong></p><ul><li><strong>Understanding Deep Learning</strong> by Simon J.D. Prince (Book)</li><li><a href="https://mbernste.github.io/posts/elbo/"><strong>The Evidence Lower Bound (ELBO)</strong></a> by Matthew N. Bernstein</li><li><a href="https://arxiv.org/abs/1906.02691"><strong>An Introduction to Variational Autoencoders</strong> </a>(Paper)</li><li><a href="https://arxiv.org/abs/1606.05908"><strong>Tutorial on Variational Autoencoders</strong></a><strong> (paper)</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24f5da384a9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensemble Learning: Boosting, Bagging, Stacking (Gradient boosting)-Part 2]]></title>
            <link>https://medium.com/@aymne011/ensemble-learning-boosting-bagging-stacking-gradient-boosting-part-2-0fcf07fd074e?source=rss-c1b8e0a2a743------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fcf07fd074e</guid>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[gradient-boosting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Aymen Boukhari ]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 01:37:56 GMT</pubDate>
            <atom:updated>2024-08-29T01:42:48.471Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this article, we will continue from where we left off in the <a href="https://medium.com/@aymne011/ensemble-learning-boosting-bagging-stacking-part-1-e97251b16b94">previous one</a> and delve deeper into explaining the Gradient Boosting algorithm.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxKEJWxF6W1MCzy_RmZHug.png" /></figure><h3><strong>2. Gradient Boosting:</strong></h3><p>Gradient Boosting is an algorithm that belongs to the Boosting family of ensemble learning methods (for an explanation of boosting algorithms or ensemble learning, refer to Part 1). It is used for both classification and regression tasks. Like AdaBoost, Gradient Boosting utilizes multiple weak learners to create a powerful model for a given task.</p><h4><strong>2.1. Regression:</strong></h4><p>To explain <strong>Gradient Boosting,</strong> let’s use a regression example (house price prediction). Imagine we have a dataset with four samples (see the figure below), and we want to predict house prices using the Gradient Boosting algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*uSWahtMZS7j7M1Jfc2jwiQ.png" /></figure><h4>2.1.1. Step-by-Step Calculation :</h4><ol><li><strong>Initialize the Model:</strong> In this step, we initialize the base prediction, which is the mean of all the prices in our dataset. (In the math section, we will discuss why we use the mean.) For this example, the <strong>Initial Prediction</strong> is $362,500.</li><li><strong>Calculate the Residuals:</strong> The residuals are the differences between the actual price (true label) and the prediction. This can be calculated as: <strong>Residual=Actual Price−Prediction</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*e_pSlIMwSTWtioFcr31nNg.png" /><figcaption><strong>Calculate the Residuals</strong></figcaption></figure><p><strong>3. Fit a Weak Learner (Decision Tree):</strong> In this step, we use a weak learner, typically a decision tree, to predict the residuals. <strong>The inputs to the decision tree are our features,</strong> such as the number of rooms, space, and number of bedrooms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*hpxei2PkGINTSpiOmlqR5w.png" /><figcaption><strong>Fit a Weak Learner (Decision Tree)</strong></figcaption></figure><p><strong>4.Update the Model :</strong> Add the tree’s predictions to the initial predictions to get updated predictions :</p><p><strong>Updated Prediction=Initial Prediction+α×Tree Prediction</strong></p><p><strong><em>(Note: We use α to control the contribution of the tree’s predictions and to avoid overfitting.)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*cikfSR02fgiMOOI83fEA-w.png" /><figcaption><strong>Update the Model</strong></figcaption></figure><p><strong>5. Repeat:</strong> Now that we have the updated prediction, we use it to calculate <strong>the residuals again and fit a new weak learner</strong>. This process is repeated for <strong>m iterations</strong>, where <strong>m is the number of weak learners we want</strong> to include in the ensemble.</p><h4>2.1.2. Math Behind Gradient Boosting:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*pIkldMWaLOD5gOyvMJHcBw.png" /></figure><p>At first glance, the concept of Gradient Boosting might seem quite complex, but it’s actually quite straightforward once you break it down. Let’s delve deeper into the details to understand how it works.</p><p>If we have training <strong>data S={(x1,y1),(x2,y2),…,(xm,ym)}</strong> and a <strong>differentiable loss function L(y,F(x) </strong>(<strong>since we will need its derivative</strong>), and we want to use <strong>m iterations (weak learners)</strong>, then:</p><p><strong>Step 1:</strong> Initialize the model with a constant value γ, which satisfies the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*iRURMtifFnzfWbhgKQtiuA.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Gradient_boosting">Gradient boosting — Wikipedia</a></figcaption></figure><p>For regression tasks the error L is defined by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*7xOc8OLcdfdjfVumauFkvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*GpQLxhp4372Fun-0M10Sgw.png" /></figure><p>To find the value of γ that minimizes this total loss, we take the derivative of the total loss with respect to γ and set it to zero:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*VtmrxcT4R39JJWQKErSWkg.png" /></figure><p><strong>Step 2 :</strong> After finding the <strong>initial value γ</strong>, we proceed through the following steps for M iterations, where <strong>M is the number </strong>of weak learners:</p><p><strong><em>Step 2–1</em></strong> : Calculate the residuals based on the current model’s predictions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*lzNP9F10sS96lcnFbn9xlA.png" /></figure><p>(with <strong>Fm−1​ representing the previous prediction if m=1 then F0 is γ which is the mean of all the targets yi)</strong></p><p><strong><em>Step 2–2 :</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*jXau3Dr8OFhGjmYTMjYsfQ.png" /></figure><p>After calculating the residuals and building the decision tree, each <strong>terminal node (leaf) in the mth tree may contain several values (samples).</strong> The goal is to find a value <strong>γjm​ for each leaf j that minimizes the loss between the actual target values and the predictions made by the tree.</strong></p><p>To achieve this, we focus on the samples xi​ that end up in leaf j . The idea is to find the optimal <strong>γjm​ that minimizes the loss function for these samples.</strong></p><p><strong>After some mathematical derivation( see the figure below ) , it turns out that the optimal value of γjm</strong> that minimizes this loss is simply the mean of the residuals of all the samples in that leaf j . This means that the best prediction we can make for <strong>all the samples in leaf j is their average.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*VDkfvNpAAOuh9Bf9FufE0g.png" /><figcaption><strong>mathematical derivation</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*_5vuwO0ogCEYLvmu5ffapA.png" /><figcaption><strong>mathematical derivation</strong></figcaption></figure><p><strong><em>Step 2–3 :</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*lsI2gxd1eqmwBbravGZynA.png" /><figcaption><strong>step 2–3</strong></figcaption></figure><p>In this step, we update our model predictions by combining the old predictions with the <strong>new predictions </strong>(<strong>which are the residuals scaled sometimes by alpha which is learning rate between 0 and 1 to reduce overfitting</strong>). Specifically, <strong>we add the old prediction Fm−1(x)</strong></p><h4>2.1.3. Coding :</h4><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>from sklearn.tree import DecisionTreeRegressor<br><br>class GradientBoostingRegressorScratch:<br>    def __init__(self, n_trees=3, lr=0.1, max_depth=3):<br>        self.n_trees = n_trees <br>        self.lr = lr<br>        self.max_depth = max_depth<br>        self.trees = []<br><br>    def fit(self, X, y):<br>        self.f0 = np.mean(y, axis=0) <br>        fm = self.f0<br>        for _ in range(self.n_trees):<br>            tree = DecisionTreeRegressor(max_depth=self.max_depth)<br>            residuals = y - fm<br>            tree.fit(X, residuals)<br>            fm += self.lr * tree.predict(X)<br>            self.trees.append(tree)<br><br>    def predict(self, X):<br>        fm = np.full(X.shape[0], self.f0)<br>        for tree in self.trees:<br>            fm += self.lr * tree.predict(X)<br>        return fm<br></pre><p><strong><em>In the next article, we will complete our exploration of Gradient Boosting by diving into its application for classification tasks. Stay tuned as we uncover how this powerful algorithm can be adapted for classification problems and explore its nuances. Good luck and happy coding! 🚀📈</em></strong></p><h3>Resources</h3><ol><li><a href="https://colab.research.google.com/github/mcb00/blog/blob/master/_notebooks/2020-12-08-gradient-boosting-machine-from-scratch.ipynb#scrollTo=doRznkJprD14">How to Build a Gradient Boosting Machine from Scratch </a>— A comprehensive guide on implementing Gradient Boosting from the ground up.</li><li><a href="https://ieeexplore.ieee.org/document/9893798">A Survey of Ensemble Learning: Concepts, Algorithms, Applications, and Prospects</a> — An in-depth survey covering various aspects of ensemble learning.</li><li><a href="https://en.wikipedia.org/wiki/Gradient_boosting">Gradient boosting</a> — An overview of Gradient Boosting from Wikipedia.</li><li><a href="https://youtu.be/3CC4N4z3GJc?si=dl1bU6Zm0Hj0BmT7">Gradient Boost Part 1 (of 4): Regression Main Ideas</a> — StatQuest with Josh Starmer</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fcf07fd074e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensemble Learning: Boosting, Bagging, Stacking (Part 1)]]></title>
            <link>https://medium.com/@aymne011/ensemble-learning-boosting-bagging-stacking-part-1-e97251b16b94?source=rss-c1b8e0a2a743------2</link>
            <guid isPermaLink="false">https://medium.com/p/e97251b16b94</guid>
            <category><![CDATA[bagging]]></category>
            <category><![CDATA[boosting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ensemble-learning]]></category>
            <category><![CDATA[adaboost]]></category>
            <dc:creator><![CDATA[Aymen Boukhari ]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 19:11:44 GMT</pubDate>
            <atom:updated>2024-08-01T19:11:44.539Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we are going to dive deep into ensemble learning methods, including <strong>boosting</strong> algorithms, <strong>bagging</strong>, and <strong>stacking</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxKEJWxF6W1MCzy_RmZHug.png" /></figure><p>In this part, we are going to see:</p><ol><li>What ensemble learning is</li><li>How to Combine Base Learners?</li><li>Ensemble learning methods (Boosting)</li></ol><h3><strong>1. What is Ensemble Learning?</strong></h3><p>Ensemble learning is a technique used in machine learning that <strong>combines</strong> multiple models to perform a specific task, rather than relying on a single model, like SVM or decision trees. This approach can be divided into two categories: <strong>parallel and sequential ensembles.</strong></p><ul><li><strong>Sequential Ensembles:</strong> In this category, base classifiers are trained <strong>iteratively.</strong> The models at each iteration learn to correct the errors made by the previous model.</li><li><strong>Parallel Ensembles:</strong> These train <strong>different base </strong>classifiers<strong> </strong>independently and then combine their results to obtain a final result, like in Random Forests. Parallel ensembles can <strong>be further divided</strong> into<strong> homogeneous</strong> and <strong>heterogeneous</strong> ensembles:</li><li><strong>Homogeneous Ensembles:</strong> Use the same base classifier, meaning the same <strong>machine learning algorithm</strong> is applied.</li><li><strong>Heterogeneous Ensembles:</strong> Use different <strong>base models.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rIuymVs-MiQUnTcJIUiWQQ.png" /><figcaption>Block diagram of parallel ensemble learning</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzLBYzNlkL4ODP-Rp-w12g.png" /><figcaption>Block diagram of sequential ensemble learning</figcaption></figure><h3><strong>2. How to Combine Base Learners?</strong></h3><p>After training our base classifiers, it’s time to make predictions and combine the results of these classifiers. There are several methods for doing this, but the most common ones are majority voting and weighted majority voting.</p><p><strong>2.1 Majority Voting:</strong></p><p>Majority voting is the simplest and most common method used in ensemble learning. In a classification task, we select the class predicted most often by the base models. In a regression task, we take the average of the predictions from the base models.</p><p>Mathematically, if we assume that we have T classifiers and t=1,…,T and C represents the number of classes we have c=1,…,C then the decision of the prediction of the t-th classifier is d_tc∈{0,1}. The final predicted class after majority voting is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*K9n1txFGTRsm1GeFEzW5Ng.png" /><figcaption>source(paper below)</figcaption></figure><p>However, this method assumes that all base classifiers are equally good, even though individual base models in the ensemble often do not have equal performance. This can sometimes lead to suboptimal results if some models are significantly better than others. so we will use another method called <strong>weighted majority voting</strong></p><h4>2.2 <strong>weighted majority voting :</strong></h4><p>It is similar to the first method, but it adds a weight <strong>wi</strong>​ to every classifier. Generally, these weights are normalized, which means their sum equals one: <strong>∑wi​=1</strong></p><h3><strong>3 . Ensemble learning methods :</strong></h3><h4>3.1 . Boosting :</h4><p>Boosting is a technique used to combine weak learners to create a strong learner with high accuracy. It works by training a weak learner on the input data, computing its predictions, and then identifying the misclassified training samples. The next weak learner is trained on an adjusted training set that includes these misclassified instances from the previous round. This process continues iteratively until a predefined number of weak learners (a hyperparameter) is achieved. The results of each learner are then weighted to produce the final result. Examples of this technique include AdaBoost, Gradient Boosting, XGBoost, and others.</p><p>One issue with this approach is that it forces the algorithm to focus more on noisy data, which can lead to overfitting</p><p><strong>3.1.1 AdaBoost:</strong></p><p>AdaBoost (Adaptive Boosting) is one of the most well-known boosting algorithms. Its process begins with training a base classifier, often a decision stump (a simple, shallow decision tree), on the input data. After each classifier makes predictions, AdaBoost assigns higher weights to the misclassified data points. This adjustment helps the subsequent classifiers focus more on the previously misclassified instances.</p><p>The algorithm iteratively trains a series of classifiers, with each new classifier emphasizing the mistakes made by the previous ones. After training, the final model combines the predictions of all classifiers, weighting them according to their performance. This approach helps in improving the overall accuracy and robustness of the model.</p><p>in mathimathical view if we have m m labelled training instances S = {(x1, y1), . . . ,(xi, yi), . . . ,(xm, ym)} where yi is a label and yi = {-1 , 1} (binary classifiaction) so the weight D1 of the sample xi and the weight update Dt+1 are computed in recursive way as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*zAEpY4oWtjLnKUBTWqj7Xg.png" /><figcaption>source(paper below)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*J6WefFkpH08kqGcG8DyTiQ.png" /><figcaption>source(paper below)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*nfQPq5-cl_u_Dc9-pkFd4w.png" /><figcaption>source(paper below)</figcaption></figure><p>Don’t worry! It’s quite simple. Let’s clarify this formula by examining each step of the AdaBoost algorithm:</p><ol><li>In the first step, we calculate D1​(i) for each sample i. This is simply 1/N​, where N is the number of samples. This means that all samples initially have equal weights. For example, if we have 4 samples, then D1(i)=1/4</li></ol><p>2. Next, we perform a classifier h(xi) (often a decision stump) and use it to predict the label for each sample. We then compare these predicted labels to the true labels.</p><p>After making predictions, we calculate ϵ, which is the sum of the weights of the misclassified samples. This measure tells us how well the classifier performed.</p><p>We then compute αt​, which indicates the importance of the classifier. It is calculated using ϵ and is used to update the weights of the samples. The updated weights D2(i) are adjusted so that misclassified samples get higher weights, making them more influential in the next round of training.</p><p>Here’s a step-by-step breakdown:</p><p><strong>. Train Classifier h(xi)</strong>: Use a decision stump to classify each sample.</p><p><strong>. Compare Predictions</strong>: Check how the predicted labels match the true labels.</p><p><strong>. Calculate ϵ</strong>: Sum the weights of the misclassified samples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*nfQPq5-cl_u_Dc9-pkFd4w.png" /><figcaption>source(paper below)</figcaption></figure><p><strong>. Compute αt​</strong>: Determine the weight of the classifier based on ϵ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*J6WefFkpH08kqGcG8DyTiQ.png" /><figcaption>source(paper below)</figcaption></figure><p><strong>. Update Weights</strong>: Adjust the weights of the samples so that misclassified ones are given more importance for the next iteration.(-1 for 0 labels and 1 for label with 1)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*jln4VHLja-Q_qUBTbtscsw.png" /><figcaption>source(paper below)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*E4lynYY_Hz9zgh4BDY9LlA.png" /></figure><p>After completing the iterations, we can predict the labels as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*9hUGmsT7ITSWKKbAq72gTQ.png" /><figcaption>source(paper below)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*47jw1tzUy7ZawiTRdQGW5g.png" /><figcaption>AdaBoost summary (source : paper below )</figcaption></figure><h3>Resources :</h3><p><a href="https://ieeexplore.ieee.org/document/9893798"><strong>1 . A Survey of Ensemble Learning: Concepts, Algorithms, Applications, and Prospects | IEEE Journals &amp; Magazine | IEEE Xplore</strong></a></p><p><a href="https://www.youtube.com/watch?v=LsK-xG1cLYA"><strong>2 . https://youtu.be/LsK-xG1cLYA?si=W8vdBaSI2T6TE11U</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e97251b16b94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing your own callbacks on TensorFlow]]></title>
            <link>https://medium.com/@aymne011/writing-your-own-callbacks-on-tensorflow-66424e32b1b1?source=rss-c1b8e0a2a743------2</link>
            <guid isPermaLink="false">https://medium.com/p/66424e32b1b1</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[keras]]></category>
            <dc:creator><![CDATA[Aymen Boukhari ]]></dc:creator>
            <pubDate>Mon, 24 Jun 2024 16:05:32 GMT</pubDate>
            <atom:updated>2024-06-24T16:05:32.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AX0iTzSfNlsr25kLsmKxHw.jpeg" /></figure><h4>In this blog, we are going to see:</h4><ol><li>What are <strong>callbacks</strong>?</li><li>Predefined <strong>Callbacks</strong></li><li>Examples of <strong>Keras</strong> callback applications (writing a callback from scratch)</li></ol><h3><strong>1. What are callbacks?</strong></h3><p>Training machine learning models can be a time-consuming process, often taking hours or even days to complete. During this period, you might encounter situations where you wish to:</p><ul><li>Stop training early if the model reaches a satisfactory performance.</li><li>Adjust the learning rate dynamically.</li><li>Save training logs for further analysis.</li><li>Save the best weights of your model at different checkpoints.</li></ul><p>Interrupting the training process to perform these tasks can be challenging. This is where <strong>callbacks</strong> come into play.</p><p><strong>Callbacks</strong> are specialized functions in <strong>Keras </strong>that allow you to control the training process of your model without any interruption. They provide a way to interact with the model during the training phase, enabling you to execute specific code at predefined points throughout the training process.</p><h3><strong>2.Predefined Callbacks</strong></h3><p><strong>Keras</strong> provide to us a set of predifined <strong>callbacks</strong> under <strong>tf.keras.callbacks</strong> module.</p><h4><strong><em>2.1.EarlyStopping :</em></strong></h4><p>The <strong>EarlyStopping</strong> callback monitors a specified metric during training and stops the training process if the monitored metric stops improving. This helps in preventing <strong>overfitting</strong> and saves computational resources.</p><pre>import tensorflow as tf<br>tf.keras.callbacks.EarlyStopping(monitor=&#39;val_loss&#39;, <br>                                min_delta=0.05, <br>                                patience=5, <br>                                verbose=0, <br>                                mode=&#39;auto&#39;, <br>                                baseline=None, <br>                                restore_best_weights=True)</pre><h4>Explanation:</h4><ul><li><strong>monitor=’val_loss’</strong>: This specifies that the validation loss will be monitored.</li><li><strong>min_delta=0.05</strong>: This parameter defines the minimum change in the monitored quantity to qualify as an improvement. If the change is less than 0.05, it is not considered as an improvement.</li><li><strong>patience=5</strong>: The model will continue training for 5 epochs after the last time the validation loss improved. If there is no improvement for 5 consecutive epochs, training stops.</li><li><strong>verbose=0</strong>: This controls the verbosity of the output during training. A value of 0 means no additional logs are generated.</li><li><strong>mode=’auto’</strong>: The mode can be ‘auto’, ‘min’, or ‘max’. In ‘auto’ mode, the direction is inferred from the name of the monitored quantity. For val_loss, it will look for a minimum value.</li><li><strong>baseline=None</strong>: If specified, training will stop if the model doesn’t show improvement over the baseline value.</li><li><strong>restore_best_weights=True</strong>: This ensures that the model weights are restored to the point where the monitored quantity was at its best.</li></ul><h4>Usage:</h4><pre>// here model we assume it is defined<br>model.fit(     <br>    x_train, y_train,<br>    epochs=40,<br>    validation_data=(x_val, y_val),<br>    callbacks=[early_stopping]<br>)</pre><p>With this setup, the training process will stop if the validation loss does not improve by at least 0.05 for 5 consecutive epochs, and the best model weights observed during the training will be restored.</p><h4>2.2.LearningRateScheduler :</h4><p>This callback allow you to update the learning rate during training (make the model learn <strong>fast</strong>) By defining a scheduling function :</p><pre>tf.keras.callbacks.LearningRateScheduler(schedule, verbose=0)</pre><h4>Explanation:</h4><p>.schedule: this is a function that takes the epoch index and current learning rate and returns a new learning rate.</p><h4>Example of schedule function :</h4><pre>def scheduler(epoch, lr):<br>    if epoch &lt; 5:<br>        return lr<br>    else:<br>        return lr * 0.5<br>lr_update = tf.keras.callbacks.LearningRateScheduler(schedule=scheduler)</pre><h4>2.3.ReduceLROnPlateau :</h4><p>This callback is used when you want to change the learning rate when the metrics have stopped improving (The difference between <strong>ReduceLROnPlateau</strong> and <strong>LearningRateScheduler</strong> is that the first updates the learning rate based on a metric (e.g., val_loss), while the second updates the learning rate based on the number of epochs.<strong> </strong>)</p><pre>tf.keras.callbacks.ReduceLROnPlateau(monitor=&#39;val_loss&#39;, <br>                                     factor=0.1, //new_lr = lr*factor<br>                                     patience=10, <br>                                     verbose=0, <br>                                     mode=&#39;auto&#39;,    <br>                                     min_delta=0.0001, <br>                                     cooldown=0, <br>                                     min_lr=0, <br>                                     **kwargs)</pre><h4>Explanation:</h4><p>factor: the factor by which the learning rate should be decreased</p><h4>2.4. CSVLogger :</h4><p>The <strong>CSVLogger</strong> callback allows you to generate a <strong>CSV file</strong> containing model training information for each epoch, such as <strong>epoch number, accuracy</strong>, <strong>validation loss</strong>, <strong>etc</strong>.</p><pre>tf.keras.callbacks.CSVLogger(filename, <br>                             separator=&#39;,&#39;, <br>                             append=False)</pre><p><strong>So These callbacks are the most frequently used, but there are others you can check in the </strong><a href="https://www.tensorflow.org/guide/keras/writing_your_own_callbacks"><strong>TensorFlow docs</strong></a></p><h3>3.Examples of <strong>Kerase</strong> callback applications :</h3><p>Before we start building a callback, we should understand what happens when we call each callback above (so we will understand the backend of our callback):</p><p>All the above callbacks are classes that have methods, and each method is called at a certain time during the training phase (see the code below):</p><pre>class CustomCallback(keras.callbacks.Callback):<br>    def on_train_begin(self, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;Starting training; got log keys: {}&quot;.format(keys))<br><br>    def on_train_end(self, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;Stop training; got log keys: {}&quot;.format(keys))<br><br>    def on_epoch_begin(self, epoch, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;Start epoch {} of training; got log keys: {}&quot;.format(epoch, keys))<br><br>    def on_epoch_end(self, epoch, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;End epoch {} of training; got log keys: {}&quot;.format(epoch, keys))<br><br>    def on_test_begin(self, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;Start testing; got log keys: {}&quot;.format(keys))<br><br>    def on_test_end(self, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;Stop testing; got log keys: {}&quot;.format(keys))<br><br>    def on_predict_begin(self, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;Start predicting; got log keys: {}&quot;.format(keys))<br><br>    def on_predict_end(self, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;Stop predicting; got log keys: {}&quot;.format(keys))<br><br>    def on_train_batch_begin(self, batch, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;...Training: start of batch {}; got log keys: {}&quot;.format(batch, keys))<br><br>    def on_train_batch_end(self, batch, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;...Training: end of batch {}; got log keys: {}&quot;.format(batch, keys))<br><br>    def on_test_batch_begin(self, batch, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;...Evaluating: start of batch {}; got log keys: {}&quot;.format(batch, keys))<br><br>    def on_test_batch_end(self, batch, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;...Evaluating: end of batch {}; got log keys: {}&quot;.format(batch, keys))<br><br>    def on_predict_batch_begin(self, batch, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;...Predicting: start of batch {}; got log keys: {}&quot;.format(batch, keys))<br><br>    def on_predict_batch_end(self, batch, logs=None):<br>        keys = list(logs.keys())<br>        print(&quot;...Predicting: end of batch {}; got log keys: {}&quot;.format(batch, keys))</pre><p>Let’s explain what happens here:</p><ul><li><strong>on_train_begin / </strong><strong>on_train_end:</strong> These methods are called at the very beginning and very end of the training process, respectively. They mark the start and end of the entire training process.</li><li><strong>on_epoch_begin / </strong><strong>on_epoch_end:</strong> These methods are invoked at the start and end of each epoch during training. An epoch is one complete pass through the entire training dataset.</li><li><strong>on_train_batch_begin / </strong><strong>on_train_batch_end:</strong> These methods are called at the start and end of each batch during training. A batch is a subset of the training data, used to update the model&#39;s parameters.</li><li><strong>on_test_begin / </strong><strong>on_test_end:</strong> These methods are called at the beginning and end of the testing phase, which evaluates the model&#39;s performance on the validation/test dataset.</li><li><strong>on_test_batch_begin / </strong><strong>on_test_batch_end:</strong> These methods are called at the start and end of each batch during testing.</li></ul><p>Now that we have briefly explained how callbacks are executed during the training phase, let’s proceed to build a custom callback called <strong>myCallback()</strong></p><pre>import numpy as np<br>import tensorflow as tf<br>import time<br><br>class myCallback(tf.keras.callbacks.Callback):<br>    &quot;&quot;&quot;<br>    Args:<br>    threshold: accuracy threshold for updating learning rate<br>    epochs: total number of epochs<br>    model: the model being trained<br>    factor: factor by which to adjust learning rate<br>    stop_patience: number of epochs to wait after stopping training due to small updates<br>    best_weights: boolean to indicate if we want to restore best weights or not<br>    patience: number of epochs to wait after updating training rate due to small updates<br>    &quot;&quot;&quot;<br>    def __init__(self, threshold, epochs, model, factor, stop_patience=0, best_weights=False, patience=0):<br>        super().__init__()<br>        self.threshold = threshold<br>        self.epochs = epochs<br>        self.model = model<br>        self.factor = factor<br>        self.stop_patience = stop_patience<br>        self.best_weights = best_weights<br>        self.patience = patience<br>        self.count = 0<br>        self.low_loss = np.inf<br>        self.best_weights_values = model.get_weights()<br>        self.initial_weights = self.model.get_weights()<br>        self.high_taccu = 0<br>        self.best_epoch = 0<br>        self.stop_count = 0<br><br>    def on_train_begin(self, logs=None):<br>        print(&#39;Training started. Good luck!&#39;)<br><br>    def on_train_end(self, logs=None):<br>        print(&#39;Training finished.&#39;)<br>        if self.best_weights:<br>            self.model.set_weights(self.best_weights_values)<br><br>    def on_train_batch_end(self, batch, logs=None):<br>        acc = logs.get(&#39;accuracy&#39;)<br>        loss = logs.get(&#39;loss&#39;)<br>        print(&#39;Batch end - accuracy:&#39;, acc, &#39;loss:&#39;, loss)<br><br>    def on_epoch_begin(self, epoch, logs=None):<br>        self.ep_start_time = time.time()<br><br>    def on_epoch_end(self, epoch, logs=None):<br>        ep_end = time.time()<br>        ep_duration = ep_end - self.ep_start_time<br>        loss = logs.get(&#39;loss&#39;)<br>        accu = logs.get(&#39;accuracy&#39;)<br>        val_loss = logs.get(&#39;val_loss&#39;)<br>        val_accu = logs.get(&#39;val_accuracy&#39;)<br>        lr = float(tf.keras.backend.get_value(self.model.optimizer.lr))<br><br>        current_lr = lr<br>        if accu &lt; self.threshold:<br>            monitor = &quot;accuracy&quot;<br>            if accu &gt; self.high_taccu:<br>                self.high_taccu = accu<br>                if self.best_weights:<br>                    self.best_weights_values = self.model.get_weights()<br>                self.count = 0<br>                if val_loss &lt; self.low_loss:<br>                    self.low_loss = val_loss<br>                self.best_epoch = epoch + 1<br>            else:<br>                if self.count &gt; self.patience:<br>                    lr = lr * self.factor<br>                    tf.keras.backend.set_value(self.model.optimizer.lr, lr)<br>                    self.count = 0<br>                    self.stop_count += 1<br>                    if loss &lt; self.low_loss:<br>                        self.low_loss = val_loss<br>                else:<br>                    self.count += 1<br>        else:<br>            monitor = &quot;loss&quot;<br>            if loss &lt; self.low_loss:<br>                self.low_loss = loss<br>                self.count = 0<br>                if self.best_weights:<br>                    self.best_weights_values = self.model.get_weights()<br>                self.stop_count = 0<br>                self.best_epoch = epoch + 1<br>            else:<br>                if self.count &gt; self.patience:<br>                    lr = lr * self.factor<br>                    tf.keras.backend.set_value(self.model.optimizer.lr, lr)<br>                    self.count = 0<br>                    self.stop_count += 1<br>                    if accu &gt; self.high_taccu:<br>                        self.high_taccu = accu<br>                else:<br>                    self.count += 1<br><br>        print(f&#39;{epoch + 1} / {self.epochs}, loss: {loss}, accuracy: {accu}%, val_loss: {val_loss}, val_accuracy: {val_accu}%, current_lr: {current_lr}, duration: {ep_duration} ms&#39;)<br><br>        if self.stop_count &gt; self.stop_patience:<br>            print(f&#39;Training stopped at epoch {epoch + 1}&#39;)<br>            self.model.stop_training = True</pre><pre>callback = myCallback(threshold=0.8, epochs=2, model=model, factor=0.5, stop_patience=3, best_weights=True, patience=2)<br>history = model.fit(train , valid , epochs=2 , callbacks=[callback])</pre><p>So after executing this code, we will get the following results:</p><pre>Training started. Good luck!<br>Batch end - accuracy: 0.75 loss: 0.685<br>Batch end - accuracy: 0.76 loss: 0.683<br>Batch end - accuracy: 0.77 loss: 0.682<br>Batch end - accuracy: 0.75 loss: 0.680<br>...<br>1 / 2, loss: 0.685, accuracy: 75.0%, val_loss: 0.670, val_accuracy: 72.0%, current_lr: 0.001, duration: 2.3 ms<br>Batch end - accuracy: 0.76 loss: 0.670<br>Batch end - accuracy: 0.77 loss: 0.668<br>Batch end - accuracy: 0.78 loss: 0.667<br>...<br>2 / 2, loss: 0.670, accuracy: 80.0%, val_loss: 0.660, val_accuracy: 75.0%, current_lr: 0.001, duration: 2.5 ms<br>Training finished.</pre><h3>References:</h3><ul><li><a href="https://www.tensorflow.org/guide/keras/writing_your_own_callbacks">Writing your own callbacks | TensorFlow Core</a></li><li><a href="https://blog.paperspace.com/tensorflow-callbacks/">A Guide to TensorFlow Callbacks | Paperspace Blog</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66424e32b1b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MobileNetV1: depthwise separable filters :]]></title>
            <link>https://medium.com/@aymne011/mobilenetv1-depthwise-separable-filters-4ab6eeb01c79?source=rss-c1b8e0a2a743------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ab6eeb01c79</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[mobilenet]]></category>
            <dc:creator><![CDATA[Aymen Boukhari ]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 03:20:47 GMT</pubDate>
            <atom:updated>2024-06-11T03:34:39.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>MobileNetV1: <strong>depthwise separable </strong>Convolution :</h3><p><em>Imagine that you want to perform an image classification task, such as plant disease detection, or any other computer vision task on your smartphone or an embedded device. Naturally, you will want an efficient model that offers high accuracy and fast prediction times. Traditional </em><strong><em>Convolutional Neural Networks</em></strong><em> (CNNs), while powerful, are not always the best choice in terms of speed and resource efficiency for these devices. This is where </em><strong><em>MobileNetV1</em></strong><em> comes in. In this article, I’ll explore how </em><strong><em>MobileNetV1</em></strong><em> provides an optimal solution for deploying deep learning models on resource-constrained devices, combining both efficiency and accuracy. So, how does </em><strong><em>MobileNetV1</em></strong><em> really work, and what makes it so effective?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*zBunOS-H-98jA6krBDfF1w.png" /><figcaption>MobileNetV1 Results on Object Detection Tasks<strong> </strong>(source: original paper)</figcaption></figure><h3>What Is Covered in This Article</h3><ol><li>Short Overview of CNNs</li><li>MobileNetV1 Architecture</li><li>Width Multiplier</li><li>Resolution Multiplier</li><li>Results</li></ol><h4><strong>1 - Short Overview of CNNs :</strong></h4><p><strong>CNNs</strong>, or <strong>Convolutional Neural Networks</strong>, are a type of neural network widely used in computer vision tasks such as image classification, object detection, and image segmentation. They have proven their success in these areas.</p><p><strong>CNNs</strong> are derived from the convolution operation, a mathematical process pivotal in computer vision tasks. In this operation, an image with dimensions (w x h x d) (e.g., 256 x 256 x 3 for a typical RGB image) undergoes convolution with a filter or kernel, which is a learnable parameter, with dimensions (wf x hf x d) (e.g., 3 x 3 x 3). This convolution produces an output with dimensions (w — wf) x (h — hf) x d.</p><p>This operation is fundamental to CNNs as it extracts features from the input image by convolving it with these learnable filters. For further insights into CNNs and their applications in computer vision, check out the resources below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*MrGSULUtkXc0Ou07QouV8A.gif" /><figcaption>convolution operation<strong> </strong>(source:<a href="https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/">https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/</a>)</figcaption></figure><p>So if we have <strong>N filter</strong>(kernel) with size <strong>(wf x hf x d ) </strong>and input with size <strong>(w x h x d )</strong> and stride s=1(steps we take during convolution operation ) , then the cost or the number of operation we will have is <strong>(wf x hf x d x w x h x N) for just one </strong>convolutional layer !! <strong>(a lot !!!!)</strong></p><p>Take this rule <strong>Multiplications per image = Kernel width x Kernel height x Number of channels x Number of kernels x input width x input height .</strong></p><h4><strong>2-MobileNetV1 Architecture :</strong></h4><p>Before delving into the entire architecture, let’s first explore the core layers that MobileNet is built upon, namely <strong>depthwise separable filters</strong>.</p><p><strong>2-1-Depthwise Separable Convolution :</strong></p><p>In CNNs, there is a significant computational cost associated with the convolution operation, calculated as (wf×hf×d×w×d×N). To mitigate this cost, <strong>Depthwise Separable Convolution</strong> comes into play.</p><p><strong>Depthwise Separable Convolution </strong>utilizes the same operation we discussed above (convolution) but with fewer computations. To achieve this approach, we divide it to two steps each one has few steps :</p><ol><li><strong>Depthwise convolutions</strong></li><li><strong>Pointwise convolutions</strong></li></ol><p>For <strong>Depthwise convolutions :</strong></p><ul><li>If we have an input with dimensions w×h×d , it separates it into d channels.</li><li>For each channel in d, it performs a convolution operation with a wf×hf filter.</li><li>It stacks each output to produce d channels.</li><li><strong>So in this step we have wf x hf x d x w x h (Kernel width x Kernel height x Number of channels x input width x input height) .</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8JUx0NK4I2j3xHSgO80_g.png" /><figcaption><strong>Depthwise convolutions</strong></figcaption></figure><p>For <strong>Pointwise convolutions :</strong></p><ul><li>Now, after obtaining the output from the Depthwise convolutions in the first step, we perform <strong>1×1×d convolutions</strong> to obtain the final result.</li><li>In this step, we have <strong>d×N×w×h </strong>(<strong>Number of channels x Number of kernels x input width x input height</strong>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*87YY14tmg7ItK3tl-vTqgA.png" /><figcaption><strong>Depthwise and Pointwise convolutions</strong>(source:original paper )</figcaption></figure><p>Finally, the total cost of these operations is:<strong>wf x hf x d x w x h+d x N x w x h</strong></p><p>To get the ratio between <strong>CNN</strong> and <strong>Depthwise Separable Convolution</strong>, assuming a square input ( w=h ) and wf=hf :</p><p><strong>(wf x hf x d x w x h + d x N x w x h)/(wf×hf×d×w×d×N) = 1/N + 1/wf²</strong></p><p>MobileNet utilizes 3 × 3 depthwise separable convolutions, which result in approximately <strong>8 to 9 times fewer</strong> computations than standard convolutions, showcasing remarkable efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*Oc6YXXaNoRwSh1V_p29ydg.png" /><figcaption><strong>Depthwise and Pointwise convolutions (Source : </strong><a href="https://github.com/christianversloot/machine-learning-articles">https://github.com/christianversloot/machine-learning-articles</a>)</figcaption></figure><h4><strong>2–2-Network Structure :</strong></h4><p>MobileNet has <strong>28 layers </strong>, built on <strong>depthwise separable convolutions</strong> as mentioned above except for the first layer which is a full convolution. All layers are followed by a <strong>batchnorm and ReLU</strong> nonlinearity with the exception of the final fully connected layer which has <strong>no nonlinearity</strong> and feeds into a <strong>softmax layer for classification</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*VrAibDMsuO6aOB2fznyt8Q.png" /><figcaption>Network Structure(source:original paper )</figcaption></figure><h4><strong>3 — Width Multiplier :</strong></h4><p>Although this architecture is small and fast, if we aim to enhance its speed further, a new technique called <strong>Width Multiplier</strong> is introduced to <strong>slim</strong> <strong>down the model</strong>. This technique involves <strong>shrinking the channels</strong> of each layer or input of the layer from W×H×D to α×D , where α is a <strong>hyperpa_ _rameter</strong>(In machine learning, hyperparameters are parameters whose values we set, as opposed to learnable parameters) , Here, 0&lt;α≤1. This technique is commonly employed when training the model from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*cq5vl1j0Gg0yroFOtMYuoA.png" /><figcaption>Width Multiplier (source:original paper)</figcaption></figure><h4>4 — Resolution Multiplier:</h4><p>This technique also aims to expedite the model’s training phase. However, instead of solely applying it to the channels, we extend its application to both the input image and the internal representation of every layer (width and height). We refer to this hyperparameter as ρ, where 0&lt;ρ≤1.</p><p>After we apply <strong>width multiplier </strong>and <strong>Resolution Multiplier</strong> we will have a <strong><em>cost</em> </strong>: <strong>wf x hf x (α×d ) x (ρxw) x (ρxh )+ (α×d ) x (αxN) x (ρxw) x (ρxh )</strong></p><h4><strong>5 — Results :</strong></h4><ul><li><strong>Object Detection</strong>: MobileNet trained on COCO datasets for object detection.</li><li><strong>Face Embeddings</strong>: Trained for the face recognition task.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*fo0DvPaulXwJS4USdGizcw.png" /><figcaption><strong>Object Detection(source : original paper )</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*dF5tWqp-pqLC3OyUva_0dw.png" /><figcaption><strong>Face Embeddings </strong>(source: original paper)</figcaption></figure><p><strong>References:</strong></p><ul><li>Howard, A. G., Zhu, M., Chen, B., Kalenichenko, D., Wang, W., Weyand, T., Andreetto, M., &amp; Adam, H. (2017). MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications.</li><li>“An Intuitive Explanation of Convolutional Neural Networks” by Ujjwal Karn. Retrieved from: <a href="https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/">https://ujjwalkarn.me/2016/08/11/intuitive-explanation-convnets/</a></li><li>“Interns Explain CNN ” . Retrieved from : <a href="https://www.datawow.io/blogs/interns-explain-cnn-8a669d053f8b">https://www.datawow.io/blogs/interns-explain-cnn-8a669d053f8b</a></li><li>“understanding-separable-convolutions.md ” Retrieved from :<a href="https://github.com/christianversloot/machine-learning-articles/blob/main/understanding-separable-convolutions.md">machine-learning-articles/understanding-separable-convolutions.md at main · christianversloot/machine-learning-articles (github.com)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ab6eeb01c79" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>