<?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 Mohit Gupta on Medium]]></title>
        <description><![CDATA[Stories by Mohit Gupta on Medium]]></description>
        <link>https://medium.com/@mgupta70?source=rss-c42ce3a0024------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JjO1-Yypf1lNVSa7PQlskw.jpeg</url>
            <title>Stories by Mohit Gupta on Medium</title>
            <link>https://medium.com/@mgupta70?source=rss-c42ce3a0024------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:57:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mgupta70/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[Optimizers in Deep Learning— A concise summary]]></title>
            <link>https://medium.com/@mgupta70/optimizers-in-deep-learning-a-concise-summary-cdaf5aa70430?source=rss-c42ce3a0024------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdaf5aa70430</guid>
            <dc:creator><![CDATA[Mohit Gupta]]></dc:creator>
            <pubDate>Tue, 07 May 2024 05:30:26 GMT</pubDate>
            <atom:updated>2024-06-25T19:45:31.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*5z2XON1-KM5AAVwfnmjToQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*GSc39mXutU8Y_bURG90Kyg.png" /></figure><p><strong>1. Batch Gradient Descent (BGD)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*5prAyePBNOcUxLMpR5-YSg.png" /></figure><p>++ updates are stable &amp; loss does not fluctuate much<br> — whole dataset is required to perform 1 update<br> — very slow<br> — intractable for datasets that don’t fit into memory<br> — does not allow ‘online’ (on-the-fly) update of the model<br> — can potentially stuck into local minima<br> — does not guarantee convergence</p><p><strong>2. Stochastic Gradient Descent (SGD)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*TkFzN-6hpA0SrbTwLYfrTQ.png" /></figure><p>++ faster than BGD<br>++ can be used for learning/ training model ‘online’<br>++ gradient updates have high fluctuations which help it in getting out of local minima. So, there are less chances that it sinks into a local minima as compared to BGD<br> — it has frequent updates with high variance. This means objective function fluctuates heavily.<br> — difficult to converge to exact global minima because of the abovementioned fluctuations. But there is a way to solve this — keep reducing the learning rate as training progresses</p><p><strong>3. Mini-Batch Gradient Descent</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*nZ6LKsd3i_8_YzjEhwsu4Q.png" /></figure><p>++ reduces variances of parameters updates<br>++ Thus, more stable convergence as compared to SGD (less fluctuations &amp; overshooting)<br>++ takes advantage of matrix calculation parallelism offered by GPUs for faster computations</p><p><strong>Question-1</strong>: <strong>What is a common challenge to BGD, SGD and MiniBatch GD?</strong><br><strong>Answer</strong>: The learning rate (<em>lr</em>) is kept the same for all the parameters. Learning rate is responsible in deciding the magnitude of parameter update. Some parameters may require smaller update and some may require higher updates. Keeping lr as same for all parameters result in suboptimal convergence for model training. Thus, differential learning rates are desired.</p><p><strong>4. Gradient Descent with Momentum</strong></p><p>It adds a fraction of update vector of past time step to current update vector. This fraction is denoted by \gamma and is usually kept 0.9</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxaqzjonPfmJY3tw8RiCWw.png" /></figure><p><em>++ Momentum term</em> increases for parameters whose past and new gradients point in the same direction and reduces the updates for parameters whose gradients change directions. This results effectively in differential learning rates and leads to faster and better convergence</p><p><strong>5. Nesterov Accelerated Gradient (NAG)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWARvZ4NvqMfkIg1zFsYRg.png" /></figure><p>Instead of using gradients at current position of parameter in <em>Momentum </em>method above, Nesterov suggested updating parameters by estimating the future position of the parameter. This solves the problem of ‘overshooting’ found in the pure <em>Momentum </em>method.</p><p>++ NAG prevents us from going too fast<br>++ NAG was widely used in RNNs to boost their performance</p><p><strong>6. Adagrad</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4uWUyyFq254dqeTTg0yk2w.png" /></figure><p>Adopts lr performing smaller updates for parameters with frequently occurring features and larger updates for parameters associated with infrequent features.</p><p>[Parameters that are associated with features occurring frequently in the training data tend to have more “stable gradients” — meaning their gradients have small fluctuations or variance over time. These stable gradients indicate that the parameter is already close to an optimal solution or that the features associated with it are well-represented in the training data. In adaptive learning rate algorithms, these parameters will receive smaller updates because their gradients are less likely to fluctuate significantly from one iteration to another. Invert this explanation for parameters with infrequent features or sparse features.]</p><p>++ Adagrad suits datasets having sparse features<br>++ Adagrad uses differential learning rate for every parameter \theta_i @ every time step <em>t<br> — </em>Accumulation of square gradients =&gt; denominator keeps increasing =&gt; lr reduces/shrinks a lot =&gt; lr becomes infinitesimally small =&gt; learning stops<br> — aka lr reduces monotonically and ultimately the learning stops. {<strong>Good news</strong>: To solve this problem see RMSprop and Adadelta. Main concept: Replace the sum of squared gradients with running averages. This prevents the denominator becoming too large}</p><p><strong>7. RMSprop</strong></p><p>Developed to resolve the problem of infinitesimally small lr in Adagrad.<br>Replaced the sum of gradient squares with running average of past squared gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*lXDd74_xLsoUcu5yM5ppGw.png" /></figure><p><strong>Question-2</strong>: <strong>What is a common challenge to BGD, SGD, MiniBatch GD, Adagrad &amp; RMSprop?</strong><br><strong>Answer</strong>: Units of update don’t match. The unit of update should be the same as parameter units but for all these optimization algorithms, the update units are actually dimensionless. (Verify this yourself) {Adadelta solve this}</p><p><strong>8. Adadelta</strong></p><p>A brief overview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qJNS7bGzkRwetK_0yXk3w.png" /></figure><p><strong>Adadelta </strong>starts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZ1WoFBZKKCdghmfvOoPCQ.png" /></figure><p>++ Similar to RMSprop, Adadelta solves the problem of monotonically reducing lr by storing sum of gradients as decaying average. Running average E[g²]_t @ timestep t depends only on previous average and current gradient</p><p>++ Adadelta has correct unit of update. It does so by also taking the decaying average over past squared parameters (theta<em>_t</em>) in numerator in addition to taking running average of past squared gradients [<em>g2_t</em>]in denominator.</p><p><strong>9. Adaptive Moment Estimation (Adam)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfSXtv4enko7Mb80_EC-ZQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdaf5aa70430" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multimodal learning: Using Text Embeddings to Fine-tune CNNs]]></title>
            <link>https://medium.com/@mgupta70/multimodal-learning-using-text-embeddings-to-fine-tune-cnns-40bdc32ec409?source=rss-c42ce3a0024------2</link>
            <guid isPermaLink="false">https://medium.com/p/40bdc32ec409</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[multimodal-learning]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[vision-language-model]]></category>
            <dc:creator><![CDATA[Mohit Gupta]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 07:01:52 GMT</pubDate>
            <atom:updated>2024-02-13T07:24:09.681Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9zGD8POY7nhr6xHUV5T_g.png" /><figcaption>Figure 1: t-SNE plots of Visual Features for MNIST digits 4 &amp; 9 Fine-tuned with ResNet18 using a) only Images and b) Text and Images</figcaption></figure><p>In this blog post, we’ll explore how multimodal learning can enhance the feature learning process of a CNN for image classification tasks. <em>Figure 1a</em> depicts the t-SNE representation of fine-tuned ResNet18 image features for MNIST digits 4 and 9. In <em>Figure 1b</em>, we illustrate the impact on feature representation when incorporating textual cues alongside images during the fine-tuning of ResNet18. It is evident that the<strong> inclusion of text cues not only leads to denser clustering of data points belonging to the same class but also increases the inter-cluster distance</strong>. This suggests that our CNN is now acquiring more robust feature representations.</p><p><strong>How was this done? </strong>This approach was implemented by leveraging a multimodal learning technique, wherein ResNet18 was trained not only to learn features from the images themselves but also to incorporate information about what those images represent through text semantics. The rationale behind this method lies in addressing the challenge of misclassification errors that can arise due to visually similar-looking classes in computer vision tasks. By integrating text embeddings as auxiliary signals during the training process, the vision model is encouraged to generate more discriminative embeddings. This multimodal approach effectively enhances the model’s ability to distinguish between visually similar classes and ultimately improves its performance in image classification tasks.</p><p><em>Figure 2</em> presents a conceptual overview of the entire process. The top part of the process involves standard procedures, where ResNet18 is fine-tuned using cross-entropy loss (also known as misclassification loss), denoted as <strong>Lclf </strong>in the diagram. However, the bottom part of the diagram introduces complexity, yet it is also intriguing. Here, text embeddings are extracted from a description of the image using the pretrained CLIP Text Encoder. This text embedding serves as an ‘<em>anchor</em>’ for the vision embeddings of ResNet18, and deviations from this anchor are calculated using Mean Squared Error loss, referred to as <strong>LMMSE </strong>(Multimodal Mean Squared Error Loss) in the diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAgix9KYE9Cyx3GO15IRXQ.png" /><figcaption>Figure 2 Overview of the proposed framework</figcaption></figure><p>Therefore, the final loss is calculated as the sum of Lclf and g*LMMSE, where g determines the weighting assigned to the text embeddings. Determining an appropriate range for g often involves some experimentation, such as trial and error, particularly for custom datasets.</p><p>The ResNet architecture can be readily adapted to extract both the output activations and vision embeddings. Below is the code for customizing ResNet:</p><pre>class CustomResNet18(nn.Module):<br>    def __init__(self, num_classes=1):<br>        super(CustomResNet18, self).__init__()<br>  <br>        resnet18 = torchvision.models.resnet18(pretrained=True)<br>        self.features = nn.Sequential(*list(resnet18.children())[:-2]) <br>        self.classification_layer = nn.Linear(resnet18.fc.in_features, num_classes)<br>        <br>    def forward(self, x):<br>        features = self.features(x)<br>        features = nn.functional.adaptive_avg_pool2d(features, (1, 1))<br>        features = torch.flatten(features, 1)<br>        classification_output = self.classification_layer(features)<br>        <br>        return classification_output, features</pre><p>It was an interesting project for me. I have a hypothesis that multimodal learning could be even more advantageous in scenarios with small datasets, such as few-shot classification. If, after reading this blog, you delve into this area, I would be eager to hear about your findings or even collaborate on projects with shared interests.</p><p>Feel free to comment if you have any questions or if something is unclear. I will clarify any doubts or provide further information as needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40bdc32ec409" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision Blogs — Improving the accuracy of your Image classifier]]></title>
            <link>https://medium.com/@mgupta70/computer-vision-blogs-improving-the-accuracy-of-your-image-classifier-4ce8545e3f97?source=rss-c42ce3a0024------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ce8545e3f97</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[augmentation]]></category>
            <category><![CDATA[progressive-resizing]]></category>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Mohit Gupta]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 00:52:33 GMT</pubDate>
            <atom:updated>2023-08-28T04:14:57.835Z</atom:updated>
            <content:encoded><![CDATA[<h3>Computer Vision Blogs — Improving the accuracy of an Image Classifier</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*vfo2k9Z7uc8gmDpJGLUEIw.jpeg" /><figcaption>Fig-1. Visualizing activations of an image classifier trained to classify if the image has a Bicyclist</figcaption></figure><p>While image classification might appear to be one of the simplest tasks in computer vision, you might have encountered instances where achieving the desired accuracy on your dataset proves to be challenging. What strategies can you explore to enhance this accuracy? <br>In this blog post, we will delve into several such methods. I will also present the experimental results obtained by applying these methods to a dataset. So, let’s get started!</p><p>Our capacity for improvement lies within the ‘elements’ under our control. In the case of an image classification model (or any neural network), these elements are: <br>1. Data<br>2. Neural Network<br>3. Loss function <br>4. Optimizer</p><p>Hence, our improvements will come from modifications of these four aspects. Let’s take one aspect at a time and list out some of the most common strategies:</p><h3><strong>1. Data-related improvements</strong></h3><p><strong>A. Increase Image Size:</strong> Increasing the image size is one of the simplest and most logical steps to take. When larger images are used as input, the neural network receives more information, resulting in higher performance (mostly). <em>[We will see an example at the end]</em></p><p><strong>B. Normalization</strong> — meaning your data should have mean=0 and std=1. Why? Because normalization helps in better convergence when you train the model. <em>[We will see an example at the end]</em></p><p><strong>C. Augmentations </strong>— making multiple slightly different copies of the train images using random cropping, color jitter, horizontal flipping, shear, etc. For ex: as shown in Fig-2 below, we created multiple versions of an image using slight rotation, center cropping, and changing brightness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osP28li2lKN8hhhR8bjifg.png" /><figcaption>Fig-2. Showing four augmented versions of the left-most image</figcaption></figure><p>But, you have to be cautious when using these augmentations. The choice of augmentations should be closely linked with the dataset. For example, as shown below in Fig-3, doing the same augmentations as shown above on a vegetation dataset onto another dataset containing bicyclist images can work against you. It is because we want to build an image classifier that can classify whether an image has a bicyclist or not. Now, the original image had a bicyclist but in 2 out of 3 augmented images, the bicyclist gets cropped out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fj56XKgTLxQj4imaqwj_mg.png" /><figcaption>Fig-3. An example where augmentations lead to poor results because the Bicyclist (originally present) gets cropped out in augmented versions</figcaption></figure><p>Hence, it is the best practice to visualize some of them and verify if it is working for your dataset or not. If you train a model unaware of what is going into it, you will probably see poor-quality results.<br>The good news is that it is very easy to control these augmentations. You can make them either extreme or mild. <em>[We will see an example at the end]</em><br><strong>D. Progressive Resizing </strong>— This involves training a model using a small size of input images for an initial few epochs, and then progressively increasing the size of the image. Why do you think this technique works? Answer — Since the initial layers of an NN learn basic features like edges, vertices, etc.. Hence, this technique is particularly useful when we do not have pre-trained weights. In this case, by using small images, we can quickly learn those initial layers and then use large images to get higher discriminative power. <br>This progressive resizing can be done in 2 or 3 stages or as many as you want ultimately reaching the original resolution of images. You have to experiment to see what works for you and what does not. (It is also not absolutely necessary that this technique will always work. Use this when you don’t have pretrained weights, else experiment and see). <em>[We will see an example at the end]</em><br><strong>E. Test Time Augmentations (TTA) — </strong>Similar to augmenting train images, we can apply similar augmentations on validation or test images. Suppose, we create 5 versions of a validation image, then our answer will be the average of predictions on those 5 images. This accounts for the generalizability of our model, the only downside is that it now takes 5 times more time to do a prediction. (<em>Caution</em>: If you are using pre-defined TTA, make sure that these augmentations align with your dataset as explained in ‘<strong>C</strong>. <strong>Augmentations’ </strong>Else, modify the source code or write on your own or maybe skip it :) ) <em>[We will see an example at the end]</em></p><p>These are some of the most common methods to use your data more effectively, and there are many more ways which I have not listed here.</p><h3><strong>2. Neural Network related improvements</strong></h3><p>The most common are:<br><strong>A. Choosing a larger and deeper architecture — </strong>shift from xresnet18 to xresnet50, or shift from resnets to convnexts/vit/swin transformers. Use this <a href="https://www.kaggle.com/code/jhoward/the-best-vision-models-for-fine-tuning">guide</a> by <a href="https://docs.fast.ai/">fastai </a>for reference. <em>[We will see an example at the end]<br></em><strong>B. Use transfer learning while training — </strong><em>[We will see an example at the end]</em><strong><br>C. Make an Ensemble of networks — </strong>Different model learns slightly different things. Extending the ‘wisdom of the crowd’ principle to deep learning models, train multiple models, and take an average of their predictions as the final decision. <em>[We will see an example at the end]</em></p><h3><strong>3. Loss-related improvements</strong></h3><p>Choosing an appropriate loss is extremely crucial for training a ‘performant’ classifier. For example: choosing between Cross Entropy loss (which is the default choice) or Focal Loss — This choice of loss function is closely interlinked with the distribution of the dataset and the task at hand. For most of the balanced or moderately imbalanced datasets, CE or BCE works well, but you might need to choose Focal Loss for a heavily imbalanced dataset. <br>You have to critically analyze your dataset and then choose a loss function (or craft a new one).</p><h3><strong>4. Optimizer-related improvements</strong></h3><p>a.<strong> Choice of optimizer —</strong> For ex: SGD vs Adam<br>b. <strong>Choice of Hyperparameter</strong>s — Hyperparameters like <strong>learning rate</strong>, and <strong>batch size </strong>are critical to the successful training of the model.<br> — Too low a learning rate, the model can get trapped into a sharp local minima.<br> — Too high a learning rate, the model can jump over the global local minima.<br> — Too small a batch size, weight gradients would have high variances.<br> — Too big a batch size, you could run out of memory or might experience slower convergence. <em>[We will see an example at the end]</em></p><h3><strong>It is time for the implementation of the above-discussed methods. Let’s see some of them in action…</strong></h3><p><em>[Note: Although the code is pretty easy to follow, if you are unfamiliar with fastai, or face any difficulty in understanding it, do not stress too much about it. </em><strong><em>Important </em></strong><em>is to observe how different modifications change the performance of our model. You can later implement this in any framework you are comfortable with.]</em></p><p>The entire notebook is available <a href="https://github.com/mgupta70/medium-blogs/tree/main/Improve%20accuracy%20of%20image%20classifier">here</a> for you to experiment with more options on your own.</p><p>I am using the <a href="https://www.kaggle.com/competitions/paddy-disease-classification">Paddy Doctor: Paddy Disease Classification</a> dataset from Kaggle which is an image classification dataset with 10 classes for paddy (rice) diseases. To see the effectiveness of above-listed methods, we’ll first create a baseline model —</p><ol><li><strong>Baseline: <br>xresnet18 </strong>architecture trained from scratch for 4 epochs on images resized to 224x224</li></ol><pre># Load dataset<br>path = Path(&#39;paddy-disease-classification&#39;)<br>trn_path = path/&#39;train_images&#39;<br><br># Create Dataoaders<br>dblock = DataBlock(blocks=(ImageBlock, CategoryBlock), <br>                  get_items=get_image_files, <br>                  get_y = parent_label, <br>                   item_tfms= Resize(224)) # Resize to 224<br>dls = dblock.dataloaders(trn_path, bs=64)<br><br># Visualize some images<br>dls.train.show_batch(nrows=1, ncols=8)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_etKftzmDNeq6iU8tOF3rg.png" /></figure><pre># create a xresnet18 model<br>model = xresnet18(n_out=dls.c) # nout = number of classes<br>learn = Learner(dls, model, loss_func=CrossEntropyLossFlat(), metrics=accuracy)<br><br># train from scratch for 4 epochs using `fit` with a learning rate of 3e-3<br>learn.fit(4, 3e-3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*wsOVuIq2ZIZuJkjQm6xSNA.png" /></figure><p>So, our Baseline accuracy is 68.1%</p><p>2. <strong>Increase image size from 224 to 352</strong></p><pre># create a function to free up GPU memory<br>def clear_gpu_cache():<br>    gc.collect()<br>    torch.cuda.empty_cache()<br><br># run it<br>clear_gpu_cache() <br>set_seed(42)<br><br># create dataloader with image size of 352<br>dblock = DataBlock(blocks=(ImageBlock, CategoryBlock), <br>                  get_items=get_image_files, <br>                  get_y = parent_label, <br>                   item_tfms= Resize(352))<br>dls = dblock.dataloaders(trn_path, bs=64)<br><br># create a xresnet18 model<br>model = xresnet18(n_out=dls.c)<br>learn = Learner(dls, model, loss_func=CrossEntropyLossFlat(), metrics=accuracy)<br><br># train from scratch for 4 epochs using `fit` with a learning rate of 3e-3<br>learn.fit(4, 3e-3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*tyAnsgeHJmxwRnHXv1WwiQ.png" /></figure><p>Interestingly, our accuracy decreased to 57.9%. Maybe 4 epochs are too less to compare but, generally, this is not the case. Larger image inputs give more information to the model and hence generally result in better performance. I believe training both the models for a sufficiently long time would eventually give more conclusive results. You can experiment on your own. (Also, if you are using larger image sizes, reduce the batch size to avoid getting GPU run out of memory)</p><p><strong>3.</strong> <strong>Use the fit_one_cycle approach by </strong><a href="https://scholar.google.com/citations?user=pwh7Pw4AAAAJ"><strong>Leslie Smith</strong></a><strong> for </strong><a href="https://www.spiedigitallibrary.org/conference-proceedings-of-spie/11006/1100612/Super-convergence--very-fast-training-of-neural-networks-using/10.1117/12.2520589.full"><strong>super-convergence</strong></a><strong> along with augmentations on images of size 224x224.</strong></p><p>Conceptually <strong>fit_one_cycle </strong>means we start training with very low learning rates and then gradually increase it and then again decrease it. We start low so as not to diverge in the beginning, and end low to avoid missing the minimum, while in between we increase the learning rate to enable faster learning. Fastai provides an easy way to implement this by changing `fit` to `fit_one_cycle` (You can also manually choose the lowest and highest learning rate. But for now I am using default values). Fastai also provides an easy way to apply augmentations (as discussed in<strong> section C. Augmentations </strong>of <em>Data-related improvements</em>) by calling `aug_transforms`. In Pytorch one can craft their own augmentation scheme using <a href="https://pytorch.org/vision/stable/transforms.html">Compose</a>.</p><pre>clear_gpu_cache() <br>set_seed(42)<br><br># add aug_transforms to dataloader<br>dblock = DataBlock(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>dls = dblock.dataloaders(trn_path, bs=64)<br><br># create a xresnet18 model<br>model = xresnet18(n_out=dls.c)<br>learn = Learner(dls, model, loss_func=CrossEntropyLossFlat(), metrics=accuracy)<br><br># train from scratch for 4 epochs using `fit_one_cycle` with a learning rate of 3e-3<br>learn.fit_one_cycle(4, 3e-3) <br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*gMlRmMheZtqxbnsz2rh7PQ.png" /></figure><p>This has increased our accuracy by 10%. Now, our model has an accuracy of 78.03% after using fit_one_cycle and augmentations.</p><p><strong>4. Use all modifications in 3. along with Normalize</strong></p><p>Normalization helps in faster convergence. It is generally recommended to use the mean and standard deviation of the dataset that the pretrained model was originally trained on. For example, if you’re using a model pretrained on the ImageNet dataset, you should use the mean and standard deviation values from the ImageNet dataset for normalization. ImageNet statistics are mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].<br>If you are training from scratch then, calculate these statistics for your own dataset as shown below:</p><pre>#intialise the statistics tensors<br>means = tensor([0.,0.,0.]).cuda()<br>stds = tensor([0.,0.,0.]).cuda()<br><br># caluclate number of batches in train dataset<br>num_train_batches = len(dls.train)<br>for x,y in dls.train:<br>    means+=x.mean(dim=[0,2,3])<br>    stds+=x.std(dim=[0,2,3])<br><br># get final statistics by dividing with the number of train batches<br>means/=num_train_batches<br>stds/=num_train_batches<br><br>print(&#39;mean = {} , \n std = {}&#39;.format(mean, std))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*788n8B9nSnZeN65TuCh6Zg.png" /></figure><pre># convert it into a form which can be used as input to the model<br>mean,std = broadcast_vec(1, 4, mean, std)<br><br>set_seed(42)<br>clear_gpu_cache()<br><br># create a dataloader function with Normalize<br>def get_dls(bs,size):<br>    dblock = DataBlock(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=size, min_scale=0.75), Normalize.from_stats(mean = mean, std = std)])<br>    return dblock.dataloaders(trn_path, bs=bs)<br><br>dls = get_dls(64,224)<br>model = xresnet18(n_out = dls.c)<br>learn = Learner(dls, model, loss_func=CrossEntropyLossFlat(), metrics=accuracy)<br><br># train from scratch for 4 epochs using `fit_one_cycle` with a learning rate of 3e-3<br>learn.fit_one_cycle(4, 3e-3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*8byE0S5Imhb64IpXXzqH1w.png" /></figure><p>We witnessed a marginal increase in accuracy from 78.03% to 79.19% after normalization</p><p><strong>5. Everything until 4. + Progressive Resizing</strong></p><p>We will start with images of size 128, train the network for 2 epochs, and then increase the size to 224, and train for the usual 4 epochs.</p><pre>set_seed(42)<br><br># dataloader with image size of 128<br>dls = get_dls(64, 128)<br>learn = Learner(dls, xresnet18(n_out=dls.c), loss_func=CrossEntropyLossFlat(), <br>                metrics=accuracy)<br><br># train it for 2 epochs<br>learn.fit_one_cycle(2, 3e-3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*c6u9r8AUFICON31xGosM-A.png" /></figure><pre>clear_gpu_cache()<br>set_seed(42)<br># Change the dataloader with images of size 224<br>learn.dls = get_dls(64, 224)<br><br># train again for 4 epochs<br>learn.fine_tune(4, 1e-3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*3f05FiE9Wghl-49CjgKfKg.png" /></figure><p>We got a substantial increase from baseline performance of 68% to 83% in this case.</p><p><strong>6. Test-Time-Augmentation TTA</strong></p><p>Similar to augmentations during the training stage, we use TTA during the inference stage, where we apply augmentations to validation/ test images and get average accuracy as the final answer.</p><pre>preds,targs = learn.tta()<br>accuracy(preds, targs).item()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*5xCnagbtaKy9AI6RtHT_RQ.png" /></figure><p>The accuracy remained somewhat the same, close to 83%. In fact, it marginally decreased by 0.3%. It means after TTA, the prediction of a very small number of images (0.3%) was wrong. This is probably linked to the issue highlighted in <strong>section C augmentations</strong> in D<em>ata-related improvements</em>. This is the right time to investigate what TTA is doing to the test images, read the source code and modify it to make it more meaningful for your dataset. <em>[I leave it as an exercise for the reader. Comment if you run into any difficulty and, I will be happy to help you out:) ]</em></p><p><strong>7. Choose a bigger model — shift from xresnet18 to xresnet50</strong></p><p>Again, this is one of the most common and most used methods to increase performance. We will shift from xresnet18 to a larger model xresnet50.</p><pre>set_seed(42)<br><br># dataloader with images of size 128<br>dls = get_dls(64, 128)<br><br># use xresnet50<br>learn = Learner(dls, xresnet50(n_out=dls.c), loss_func=CrossEntropyLossFlat(), <br>                metrics=accuracy)<br><br># train for 2 epochs<br>learn.fit_one_cycle(2, 3e-3)<br><br>clear_gpu_cache()<br>set_seed(42)<br><br># dataloader with images of size 224<br>learn.dls = get_dls(64, 224)<br><br># train for 4epochs<br>learn.fine_tune(4, 1e-3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*IjL9JxHInojsMHZjVMSPSg.png" /></figure><p>We again witnessed a small increase in our accuracy. To get an even higher boost in accuracy, we can use <strong>pretrained models</strong> which we haven’t used until now along with creating an ensemble. Let’s see this in the next section.</p><p><strong>8.</strong> <strong>Ensemble learning with Pre-trained larger and deeper models</strong></p><p>In Ensemble learning, we train multiple models and take an average of their predictions on a test image as our final answer. It works on the same principle as to why a random forest is better than a single decision tree. <br>Use this <a href="https://www.kaggle.com/code/jhoward/the-best-vision-models-for-fine-tuning">guide</a> by <a href="https://docs.fast.ai/">fastai </a>as a reference for model selection.<br>Here, I am also using pretrained weights for transfer learning for each model. <br>Caution — Since we are using ImageNet (pretrained) weights for transfer learning, we need to normalize with respect to the ImageNet dataset.</p><pre># let&#39;s choose 4 models for training <br>models = [&#39;convnext_large_in22k&#39;,  &#39;vit_large_patch16_224&#39;, &#39;swinv2_large_window12_192_22k&#39;, &#39;swin_large_patch4_window7_224&#39;]</pre><pre># function for dataloader with Normalize using ImageNet statistics<br>def get_dls(bs,size):<br>    dblock = DataBlock(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=size, min_scale=0.75), Normalize.from_stats(*imagenet_stats)])<br>    return dblock.dataloaders(trn_path, bs=bs)<br><br><br>def train(arch, bs, size, epochs):<br>    set_seed(42)<br>    clear_gpu_cache() <br>    <br>    dls = get_dls(bs,size) <br>    learn = vision_learner(dls, arch, loss_func=CrossEntropyLossFlat(), metrics=accuracy)<br>    learn.fine_tune(epochs, 1e-3)<br>    clear_gpu_cache()<br><br>    return learn.tta() # Perform tta on validation<br><br># train an ensemble<br>tta_res = []<br>for arch in models:<br>    tta_res.append(train(arch=arch,bs1=64 ,size1=128, bs2=32, size2=224, epochs1=1, epochs2 = 1))</pre><p>Unfortunately, my GPU ran out of memory while doing this but I remember some models’ performance was in the range of 92–96%. Decreasing the batch size would resolve the issue, but I leave it up to you to do it yourself.</p><p>The final results are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*xZZdzRvlAzS1sncrzTkoQQ.png" /></figure><p>I hope this article has given you some familiar and novel information to build a higher-performing image classifier. If you think critically, you can see that many of the discussed approaches are general in nature, meaning they can be applied to various other tasks, and not just image classification. <br>Again, the entire notebook is available <a href="https://github.com/mgupta70/medium-blogs/tree/main/Improve%20accuracy%20of%20image%20classifier">here</a> on my GitHub. <br>These strategies are mostly derived from the <a href="https://course.fast.ai/">fastai course</a> and <a href="https://github.com/fastai/fastbook">fastbook</a>. If you are new to computer vision and looking for a course, take the <a href="https://course.fast.ai/">fastai course</a>.</p><p>Good Luck!! Comment if you know some other strategies to improve models or if you need any clarifications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ce8545e3f97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Computer Vision Blogs: Object Detection with Yolov8 — Train your own custom object detection model]]></title>
            <link>https://medium.com/@mgupta70/computer-vision-blogs-object-detection-with-yolov8-train-your-own-custom-object-detection-model-4a0fd3aaee59?source=rss-c42ce3a0024------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a0fd3aaee59</guid>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[ultralytics]]></category>
            <category><![CDATA[yolov8]]></category>
            <category><![CDATA[custom-object-detection]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Mohit Gupta]]></dc:creator>
            <pubDate>Fri, 11 Aug 2023 18:05:59 GMT</pubDate>
            <atom:updated>2023-09-11T01:58:23.911Z</atom:updated>
            <content:encoded><![CDATA[<h3>Computer Vision Blogs — Object Detection with Yolov8: Train your own custom object detection model</h3><p>If you’ve found your way here, chances are you might be struggling with the intricacies of object detection. I promise you that by the end of this blog, you will be absolutely ready to train a Yolov8 model for your custom dataset. So, let’s get started.</p><p><strong>Where should I get Yolo from?</strong></p><p>You can get Yolo from <a href="https://ultralytics.com/">Ultralytics</a>. Ultralytics is making our lives easier by offering a straightforward method to leverage this neural network. Execute this line in your (Anaconda) command prompt:</p><pre>pip install ultralytics</pre><p>Now you have YOLO on your system. We will see in some time how to access it, but before we proceed, let’s prepare the data that will be fed to the YOLO model.</p><p><strong>How to prepare the data?</strong></p><p>I assume that you have your own image dataset for training an object detection model. In my case, I am using a dataset of car dashboard photos, as depicted in Figure 1. <strong>As a crucial preprocessing step, ensure that all your images have the same shape</strong> (this is very important).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*J3dxXSoYxBsF2gqwFWUV4A.png" /><figcaption>Figure1. Images of Car dashboards</figcaption></figure><p>In this case, my focus is on detecting the Odometer, which provides the total distance traveled by the car. This problem is highly relevant for insurance companies who want to speed up car inspection. Automating the odometer reading process through image analysis, as opposed to manual entry, has the potential to substantially reduce time consumption. I suggest you too start to think about a business problem for your object detection dataset.</p><p>To tell the computer aka Yolo model to find us the odometers, we will have to <em>label </em>the images. In the context of an object detection dataset, <em>labeling </em>means drawing rectangular <em>Bounding Boxes</em> around the object we want our model to detect as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*lQ3wnyEn4qZ6uE-xymRkgQ.png" /><figcaption>Figure2. Drawing Bounding Box around the object we want to detect</figcaption></figure><p>This process of drawing a Bounding Box is known as labeling/ data annotation. You can use this tool — <a href="https://github.com/HumanSignal/labelImg/releases">Labellmg </a>to label your dataset. From this link, download the tool binaries, extract the contents of the zip file, find Labellmg.exe, and launch it to start the annotation process. After completing the labeling, you will have both your annotated images and corresponding .txt files (annotations). The name of the .txt file would be the same as your image filename (This will be done automatically by Labellmg). For 1 bounding box, there will be 5 values in the .txt file like this:</p><pre>0 0.533399 0.638112 0.060904 0.045455</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqyLmT5ERDVCrwQoxJiIUg.png" /><figcaption>Figure3. A Visual Guide to Bounding Box Parameters (Sample Image)</figcaption></figure><p>These values represent the following things. (See Figure 3 for reference)</p><p>First number — 0 — represents <strong>Class</strong>: Odometer in my case. (Suppose, I had another class, say speedometer then there will be one more row in the .txt file which would start with 1)</p><p>Second number — 0.533399 — represents the center x-coordinate of the Bounding Box as a fraction of the image width (i.e. 682/1280).</p><p>Third number — 0.638112— represents the center y-coordinate of the Bounding Box as a fraction of image height (i.e. 459/720).</p><p>Fourth number — 0.060904 — represents the width of the bounding box as a fraction of the image width(i.e. 82/1280).</p><p>Fifth number — 0.045455— represents the height of the bounding box as a fraction of image height (i.e. 32/720).</p><p>Looking directly at these numbers may not make sense to you but they hold significance for computers. After all, we communicate with computers via numbers only. So, when we give this image and its accompanying annotation file to Yolo, the model’s attention will be brought to the Odometer. After you have labeled the entire dataset, your directory should look like what is shown in Figure 4, where for every image there is a corresponding annotation file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*cxv0gJWSZleQtQORQA_CrQ.png" /><figcaption>Figure4. Image files and corresponding annotation files</figcaption></figure><p>Now, we have a) Yolo on our PC, and b) Labelled dataset to train it. Do you think we can now start training?</p><p>Answer- No. If we want to make an object detection model, we want to make sure it is performant. And, how do we ensure it? By testing it first internally and then externally. So, for our internal testing, we will split our dataset into 2 parts: 1st part to train and 2nd part to test it (this is called the validation set which helps in tracking the performance).</p><p>We usually keep 20–30% for our validation set. <strong>IMPORTANT:</strong> While splitting the dataset into train and validation datasets, maintain the directory structure as depicted in Figure 5, where you first create 2 folders namely <strong>images</strong> and <strong>labels</strong> in the main directory. Then create 2 subfolders namely <strong>train</strong> and <strong>val</strong> in each of these 2 folders. Put your train images and validation images in respectively named folders in the <strong>images</strong> folder and do the same thing with the <strong>labels </strong>folder. Why we did do this ?— Let’s just say that Yolo likes data in this format :) (Actually, it is easier to adapt your data according to the algorithm, rather than the other way around.) You can write a custom script to do all of this or use <a href="https://pypi.org/project/split-dataset/">split-dataset</a> for this. (Again!! make sure all images are of the same shape.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*3wVMdsfSc7wtoYRMTgIjQw.png" /><figcaption>Figure5. Folder structure for the data</figcaption></figure><p>Now we have a) Yolo on our PC b) Labelled dataset c) Validation dataset to monitor performance. Do you think we can now start training?</p><p>Answer — No. We are almost done, just one last thing: creating a<em> .yaml</em> file for the dataset. Why? — Yolo itself does not know where our train images are and where our validation images are. Therefore, we convey this vital information to Yolo by means of the <em>.yaml</em> file. The content of this file gives the location of our train and val folders along with class information and it looks something like this:</p><pre>train: C:/Users/car_dataset/images/train<br>val: C:/Users/car_dataset/images/val<br>nc: 1<br>names: [&#39;odometer&#39;]</pre><p>You can see here that we have only given paths to train and val images. The Yolo algorithm is designed to intelligently locate the labels that correspond to these images. Hence, it is important that when you create <strong>train </strong>and <strong>val </strong>folders (as shown in Figure 5), their names should be identical within both <strong>images </strong>and <strong>labels </strong>folders. You can either download this<em> .yaml </em>file from my <a href="https://github.com/mgupta70/medium-blogs/tree/main/Object%20detection%20with%20Yolov8">github </a>and open it in a software like Notepad++ to modify it according to your dataset or you can craft your own using this code snippet.</p><pre>data = {&#39;train&#39;: &#39;C:/Users/car_dataset/images/train&#39;, <br>&#39;val&#39;: &#39;C:/Users/car_dataset/images/val&#39;,<br>&#39;nc&#39;: 1<br>&#39;names&#39;: &#39;&#39;&#39;[&#39;odometer&#39;]&#39;&#39;&#39;<br>}<br><br># Write odometer_dataset.yaml file <br>with open(&#39;odometer_dataset.yaml&#39;, &#39;w&#39;) as file:<br>    yaml.dump(data, file)</pre><p>nc — number of classes. If you have 2, make it 2.</p><p>names — name of classes. If you label odometer as 0 (i.e. 1st class) and speedometer as 1 (i.e. 2nd class), then write : [‘odometer’, ‘speedometer’]</p><p>Now let’s open Jupyter Notebook to train our model!!</p><pre># 1. Import necessary libraries<br>from ultralytics import YOLO # Here we import YOLO <br>import yaml                  # for yaml files <br>import torch<br>from PIL import Image<br>import os<br>import cv2<br>import time<br><br># 2. Choose our yaml file<br>yaml_filename = &#39;odometer_dataset.yaml&#39; <br><br># 3. Create Yolo model<br>model = YOLO(&#39;yolov8n.yaml&#39;) # creates Yolo object from &#39;yolov8n.yaml&#39; configuration file. <br>model = YOLO(&#39;yolov8n.pt&#39;)   # Loads pretrained weights             <br>model = YOLO(&#39;yolov8n.yaml&#39;).load(&#39;yolov8n.pt&#39;)  # build from YAML and transfer weights<br><br># 4. Train the model<br>model.train(data=&#39;{}&#39;.format(yaml_filename), epochs=30,patience=5, batch=16,  imgsz=640) </pre><p>That’s it. Your model will start training. Don’t worry about ‘yolov8n.yaml’ and ‘yolov8n.pt’ as these files will get downloaded automatically once you run the above code.</p><p>Another important thing to note is <strong>imgsz: </strong>which denotes the image size: larger of the image height or width. YOLO can work on rectangular images. If your image is 460x460, you can write 460. But if your image is 1920x1088, then you don’t have to resize it to 460x460, instead, you can write 1920 as <strong>imgsz. </strong>Keep in mind that large images mean smaller batch sizes, and longer training time but potentially more accuracy.</p><p>If you’re curious about the ‘<strong>n</strong>’ in ‘yolov8<strong>n</strong>’, it means ‘<strong>n</strong>ano’ which is rhe smallest variant of Yolov8 with least number of parameters. Yolo architecture is available in various sizes like <strong>s</strong>-small, <strong>m</strong>-medium,<strong> l</strong>-large, and <strong>x</strong>-extra large. Some of them are shown below in Figure 6. Depending on factors such as computation load, speed, and accuracy, individuals can select the model that aligns best with their requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*An2aFzgKt_flqQlAXPB_tQ.png" /><figcaption>Figure6. Variants of Yolo</figcaption></figure><p>Once, the model is trained, you can load the newly trained weights which by default get stored in the ‘<strong>runs</strong>’ folder. This folder is created by Yolo automatically and will have weights in the ‘<strong>runs/train/weights</strong>’ path. Best weights would be saved by the name ‘<strong>best.pt</strong>’. To use this model for new images, load these weights and pass the new images through this model to get the predictions.</p><pre># 5. Load the trained weights<br>model = YOLO(&#39;runs/train/weights/best.pt&#39;)<br><br># 6. to run prediction on 1 image at a time<br>im = Image.open(&#39;new_car_images/car99.jpg&#39;)<br>results = model.predict(source=im, save=True)<br><br># 7. to run prediction on all images in a folder<br>im_dir = &#39;new_car_images/&#39;<br>results = model.predict(source=im_dir, save=True)</pre><p>You can choose #6 if you want to run on a single image else, choose #7 if you want to feed all images of a folder in one go. ‘save = True’ will save the prediction results in the <strong>runs </strong>folder.</p><p>I hope this blog is comprehensive enough to enable you to train your model. However, you can customize it further by changing hyperparameters or you can even play around with different variants of Yolo. To do this, I suggest you visit this <a href="https://docs.ultralytics.com/usage/python/">website </a>at Ultralytics.</p><p>Note: This blog is not about introducing Yolo architecture but quickly adapting it to our dataset. If you have read it, I am sure you will be able to train your model. In case anyone needs it, I have also made all the essential files available on my GitHub <a href="https://github.com/mgupta70/medium-blogs/tree/main/Object%20detection%20with%20Yolov8">here</a>.</p><p>Just like in most business use cases of computer vision, object detection solves a part of a much bigger problem. I started with the business goal of having automated reading of odometers from images. Until now, we have detected the odometer, but to read the digits in the odometer, we will be finetuning an Encoder-Decoder Transformer. We will do this in my next blog. Meanwhile, can you guess why have I chosen to use a Transformer? Why not use standard OCR libraries like Tesseract?</p><p>Stay tuned for my next blog. I will answer these questions and achieve my business goal for this exercise. Have fun!</p><p>References:</p><ol><li>Labellmg: <a href="https://github.com/HumanSignal/labelImg/releases">https://github.com/HumanSignal/labelImg/releases</a></li><li><a href="https://docs.ultralytics.com/usage/python/">https://docs.ultralytics.com/usage/python/</a></li><li><a href="https://docs.ultralytics.com/modes/predict/">https://docs.ultralytics.com/modes/predict/</a></li><li><a href="https://docs.ultralytics.com/modes/train/">https://docs.ultralytics.com/modes/train/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a0fd3aaee59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>