<?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 Mohammed Emad on Medium]]></title>
        <description><![CDATA[Stories by Mohammed Emad on Medium]]></description>
        <link>https://medium.com/@drmohamed4434?source=rss-34ee9692ed5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LC2FdM3mV72f-VBBk0xORQ.jpeg</url>
            <title>Stories by Mohammed Emad on Medium</title>
            <link>https://medium.com/@drmohamed4434?source=rss-34ee9692ed5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:59:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@drmohamed4434/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[Enhance Model performance by using Fastai’s lr.find() and Unfreezing Technique]]></title>
            <link>https://medium.com/@drmohamed4434/enhance-model-performance-by-using-fastais-lr-find-and-unfreezing-technique-6d7c6139f7a3?source=rss-34ee9692ed5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d7c6139f7a3</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Mohammed Emad]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 18:34:50 GMT</pubDate>
            <atom:updated>2024-03-12T18:34:50.208Z</atom:updated>
            <content:encoded><![CDATA[<p>Deep neural networks are trained using the stochastic gradient descent optimization algorithm.</p><p><strong>The learning rate is a hyperparameter that controls how much to change the model in response to estimated error each time the model weights are updated.</strong></p><p>Choosing the optimum learning rate would be like a rocket science, that because <strong>too slow learning rate would lead to slow training, on the other hand too high learning rate will make learning jump over the minimum.</strong></p><h3>In this article we will go through some steps that is provided by fastai can will make the life a lot easier for us when it comes to pick an optimum learning rate and boost our model performance.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GImnDX1Qein5bC3MIrd_Og.jpeg" /></figure><p>Before we start , we must keep in mind that there is no actual learning rate for all datasets, but as we mentioned there is tricky procedure we will try using fastai will allow us to come out with learning rate that is not too slow and consume our training time , and too high to make the loss get worse and wore, so let’s get started !!</p><p><strong>Prepare the Dataset :</strong></p><p>We will be training our model on a marine life images in order to classify sea animals species (Clams’, ‘Corals’, ‘Crabs’, ‘Dolphin’, ‘Eel’, ‘Fish , ..etc) and the model that will train with is <strong>ResNet50.</strong></p><p><strong>Initialize a Path for our dataset and represent data files:</strong></p><pre>path = Path(&#39;/kaggle/input/sea-animals-image-dataste&#39;)<br># show the data files by using :<br>path.ls();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*mTA94rhkrGhDB7WZK1rlHg.png" /></figure><p><strong>Create a DataBlock and DataLoaders :</strong></p><pre>sea_animals = DataBlock(<br>    blocks = (ImageBlock,CategoryBlock),<br>    get_items = get_image_files,<br>    get_y= parent_label,<br>    item_tfms=Resize(460),<br>    batch_tfms=aug_transforms(size=224, min_scale=0.75))<br>#Then create a dataloader and show samples of our data using show_batch():<br>dls = sea_animals.dataloaders(path)<br># check samples of images by using show_batch function<br>dls.train.show_batch(max_n=6, nrows=2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*K8isDvcGbsHQFkEeUQwbQQ.png" /></figure><p><strong>By the next step , we need to train the model for 10 epochs and we can figure out that our metrics is getting down , but our main goal is to make it go down lot deeper :</strong></p><pre>learn = vision_learner(dls, resnet50, metrics=error_rate)<br>learn.fine_tune(3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*OOJX9Co6Lgk92sIj_P1n7Q.png" /></figure><p><strong>Now let’s to Improving our model by finding the best learning rate for this classification task by using fastai’s magic box function lr.find():</strong></p><pre>learn = vision_learner(dls, resnet50, metrics=accuracy)<br>lrs= learn.lr_find(suggest_funcs=(minimum, steep, valley, slide))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*DfTPI0AOYrf1uI_9unDgbQ.png" /></figure><p>This output graph above can be divided into three areas as well as :<strong>Shallow area, Linear area and Divergent area.</strong></p><p><strong>1- Shallow area ==&gt; In this area changing learning rate has minimal effect on loss.</strong></p><p><strong>2- Divergent area ==&gt; In this area learning rate is too high , and it turns out that the loss diverge from the local minimum.</strong></p><h3>3- Linear area ==&gt; It’s our main area in the graph that we want to focus with , where there is steepest drop in loss function. So using learning rate finder function lr.find(), we have freedom to choose any of these points (steep, valley and slide ), that are plotted on the linear area.</h3><p>Now let’s explain the idea behind the learning rate finder , this function is start with very small learning rate and wouldn’t expect it to be too high to handle. We can use that for one mini-batch and notice the value of loss, then duplicate the learning rate and check the loss value again , we will keep trying until the loss gets better.</p><p><strong>Train the model with new suggestive Learning Rate :=</strong></p><p>In this case we select valley point (No matter which point along the linear area).</p><pre>learn = vision_learner(dls, resnet50, metrics=accuracy).to_fp16()<br>learn.fine_tune(11, lrs.valley)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*kwZYFY7iD_py2zC7Avq1Kw.png" /></figure><p>As we can see our new learning rate has progressively improved the model performance and the accuracy jumped around 89.2%. Next , we want to try another technique which may boost the accuracy score by a little bit.</p><h3>Fine tuning (Unfreezing the model):=</h3><p>Basically, Constitutional neural networks consist of many linear layers with non-linear activation functions between each pair followed by one or more final linear layer with an activation function as softmax at the end. The final output layer uses a matrix with enough columns as the same as the number of classes.</p><p><strong>Simply, fine tuning in transfer learning means removing or through out the final layer and replace it with a new layer with correct numbers of outputs for our desired task==&gt;this new linear layer will have random weights , but that does not mean it is entirely random model from scratch.</strong></p><ul><li><strong>The first layers encode very general concepts, such as finding gradients and edges.</strong></li><li><strong>The last layers encode concepts that are very useful.</strong></li></ul><p>The core reason of fine tuning is that we want to train our model in such a way in order to make remember all of these useful ideas from the pretrained model, and use them to solve particular task. In order to accomplish this issue we must tell the optimizer to only update the weights in those randomly added final layers, and don’t change the weights in the rest of the neural network, this process called Freezing the pretrained layers.</p><p>In fastai, when we create a model from a pretrained neural network fastai will automatically freezes all of the pretrained layers for us.</p><pre>learn.unfreeze()<br>lrs = learn.lr_find(suggest_funcs=(minimum, steep, valley, slide))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*fSWd7pojp6I3912Z0f_ZMQ.png" /></figure><pre>learn.fit_one_cycle(10, slice(lrs.minimum, lrs.valley))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*Hx8PVIzmyY5JwY7Hp5Pzcg.png" /></figure><p>Model Interpretation :</p><p>Finally we can check what are the things that are mostly confused our model</p><pre>presize_interp_2 = ClassificationInterpretation.from_learner(learn)<br>presize_interp_2.plot_top_losses(6, nrows=3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*EzAkbr7wNThstYAp0AzSVQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d7c6139f7a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gradient Descent for beginners  : Deep Neural Networks Backbone :]]></title>
            <link>https://medium.com/@drmohamed4434/gradient-descent-for-beginners-deep-neural-networks-backbone-6352e31b5577?source=rss-34ee9692ed5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6352e31b5577</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[fastai]]></category>
            <dc:creator><![CDATA[Mohammed Emad]]></dc:creator>
            <pubDate>Fri, 16 Feb 2024 18:36:17 GMT</pubDate>
            <atom:updated>2024-02-16T18:36:17.503Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Gradient Descent for beginners : Deep Neural Networks Backbone :</strong></h3><p>The basic idea behind building state-of-the-art deep neural net work that can do every thing for us in theory ,is frankly based on a concept of very nice guy called Auther Samuel .He was actually popularized the term of machine learning in the last century and he build a description of how to let artificial neural networks work better. In our days now we call it <strong>Stochastic Gradient Descent</strong> which explained as well as :</p><h3>“ Suppose we arrange for some automatic means of testing the effectiveness of any current weights assignment in terms of actual performance and provide a mechanism for altering the weight assignment so as to maximize the performance. We need not go into details of such a procedure to see that it could be made entirely automatic and to see that a machine so programmed would “learn” from its experience”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eqf1EHRPGFHqEuqnjZHVPA.jpeg" /></figure><h4>For the time being we need to understand the basic concepts of what Auther Samuel meant by his quote, so to do this let’s pick a simple example that we want to measure a speed of a roller coaster as it went over the top of a hump, it would start fast, and then get slower as it went up the hill; it would be slowest at the top, and then it would speed up as it went downhill.</h4><p>We want to build simple machine learning model for scratch that of how the speed changes over time and this model will be initialized on the top of Auther Samuel mindset that we mentioned above.</p><p>Now let’s assume that we want to measure speed manually every second for 20 second , so lets create a variable called time and it will look like this ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMC1KGaVODmFTMXuqaHx1w.png" /></figure><p>By using stochastic gradient descent to find a function that matches the observation at the graph above, let’s say that it would be a quadratic function in form of <strong><em>a*(time**2) + b*time + c</em>.</strong></p><p>Here we have two types of inputs:</p><p>1- The time we are measuring the roller coaster’s speed.</p><p>2- The values that define which quadratic function we are trying to find (Parameters).</p><p>So let’s collect the parameters in one argument and thus separate the input t, (time) and parameters, (params).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*ACvcZNfiEvdFhWNb0F7znQ.png" /></figure><p><strong>Remember </strong>: our main goal is to find the <strong>best quadratic function</strong> that fits the data. Since every quadratic function is fully defined by three parameters as well as <strong>a</strong>, <strong>b</strong> and <strong>c ===&gt; thus to find the best quadratic function we only want to find the best values for a, b and c.</strong></p><blockquote>What do we mean by best values ?? we define this by choosing a loss function , which will return a value based on a predictions and target (actual values), where lower values of the loss function reflecting to better predictions (predictions are so close to targets).</blockquote><p>It’s important that the loss function to return lower values, when predictions are more accurate, as the Stochastic Gradient Descent (SGD) procedure we defined (Auther Samuel’s Description) will minimize this loss.</p><p>For now let’s define our loss function that we will for this example which is mean squared error (mse):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*wlZYSXjfyLukbRFvjeUS8Q.png" /></figure><p>First, we will initialize the parameters to random values, and then we will tell <a href="https://pytorch.org/">Pytorch </a>we want to track their gradient, using <a href="https://pytorch.org/docs/stable/generated/torch.Tensor.requires_grad_.html"><em>requires_grad_()</em></a> method</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G679Wr4LdMMuvh2rscB2pQ.png" /></figure><p>Second, let’s try to calculate the predictions :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ylDluQsCKdWS7FwdNdmbgQ.png" /></figure><p>Let’s plot out those prediction on a scatter plot :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*BadghK_2GpIwhqtH8mupwg.png" /></figure><p>So based on the observations above, it does not looks very close !!!</p><p>The next step is we need to calculate the loss :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*pu8TMg41PkWmxaaVmGjzOw.png" /></figure><p>We are aiming to improve this loss , or by make it going down , so to do that we need to know the gradients.</p><p><strong>Calculating the gradient :</strong></p><p>Here at this step we will calculate the gradients or in the other words we will try how to get <strong>an approximation of how the parameters need to change.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*UpXwpob9b7yV3MYsEPc9CA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*U6uIh3GXmt_SmVeH9CG_Dw.png" /></figure><p><strong>Update the parameters :</strong></p><p>Now we need to update the parameters based on the gradients we just calculated :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*nKpNxAd4z4Q7IMqoiub9Xw.png" /></figure><p>Let’s see if the loss has improved or not ??</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*mBpy28Bz7h00qQON6FOJ0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hUtxCnHRzjF3APiHkAlvbw.png" /></figure><p>We have to repeat this process a few times in order to get better results :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*k4QD8jEybMcdZDA7DXp3qw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYTs5pFIiO31QdtM8ToUSQ.png" /></figure><p>Now as we see the loss is getting down and down as we wanted for each iteration step (epoch).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MpCuMF4Kke_r5nWa7GPs4g.png" /></figure><blockquote>To Sum up with firstly we have to begin with initailizing random weight values , and then by comparing the outputs (predictions) with the actual values (targets), using the loss function which returns a number that we want to make as low as possible by improving our weight automatically by figuring out a mechanism for altering the weight assignment (parameters) as to maximize performance.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6352e31b5577" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Augmentation for vision tasks using Fastai]]></title>
            <link>https://medium.com/@drmohamed4434/data-augmentation-for-vision-tasks-using-fastai-b1fd8c13ff5a?source=rss-34ee9692ed5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1fd8c13ff5a</guid>
            <category><![CDATA[data-sciece]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[deeplearing]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Mohammed Emad]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 10:26:15 GMT</pubDate>
            <atom:updated>2024-02-09T10:26:15.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*bt6gRgpzMTEcsJxMEikpKA.jpeg" /></figure><p>Data augmentation is kind of creating random variations of the input images , such appear different but not change the meaning of the data, there are many examples of data augmentations techniques such as <strong>rotation</strong>, <strong>flipping</strong>, <strong>perspective warping, brightness change</strong> and <strong>contrast</strong> <strong>changes.</strong></p><p>For natural photo images a standard set of augmentations that might work very well are provided by using fastai function which is <a href="https://docs.fast.ai/vision.augment.html"><strong>aug_transform</strong></a>. In the example below I will show you how we can apply these augmentation to an entire batch using the <strong>GPU capabilities</strong>, which will save a lot of time. So to tell fastai that we want to use these transforms on a batch we can use <a href="https://walkwithfastai.com/DBlock_Summary"><strong>batch_tfms</strong></a><strong> parameter :</strong></p><pre>animals = animals.new(item_tfms=Resize(128), batch_tfms=aug_transforms(mult=2))<br>dls = animals.dataloaders(path)<br>dls.train.show_batch(max_n=8, nrows=2,unique=True)<br></pre><p>output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*1fxf52UtvoxfYYm-dw5iCA.png" /></figure><h3>Why Data Augmentation:</h3><p><strong>1-Enhanced model performance: (the number one important requirement :)</strong></p><p>Data augmentation techniques help enrich datasets by creating many variations of existing data. This provides a larger dataset for training and enables a model to encounter more diverse features. The augmented data helps the model better generalize to unseen data and improve its overall performance in real-world environments.</p><p><strong>2-Mitigate overfitting in training data:</strong></p><p>Data augmentation helps prevent overfitting when you’re training ML models. Overfitting is the undesirable ML behavior where a model can accurately provide predictions for training data but it struggles with new data. If a model trains only with a narrow dataset, it can become overfit and can give predictions related to only that specific data type. In contrast, data augmentation provides a much larger and more comprehensive dataset for model training. It makes training sets appear unique to deep neural networks, preventing them from learning to work with only specific characteristics.</p><h3>Thank you!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1fd8c13ff5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>