<?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 Pablo García Mesa on Medium]]></title>
        <description><![CDATA[Stories by Pablo García Mesa on Medium]]></description>
        <link>https://medium.com/@pgmesa?source=rss-e4efcb8ad46e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4HihaeUDs3uXbwr97WX4aA.jpeg</url>
            <title>Stories by Pablo García Mesa on Medium</title>
            <link>https://medium.com/@pgmesa?source=rss-e4efcb8ad46e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:34:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pgmesa/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[Understanding YOLOv5 Loss: A Comprehensive Analysis]]></title>
            <link>https://pgmesa.medium.com/understanding-yolov5-loss-a-comprehensive-analysis-ffe35e6203e0?source=rss-e4efcb8ad46e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffe35e6203e0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Pablo García Mesa]]></dc:creator>
            <pubDate>Mon, 10 Jun 2024 22:36:56 GMT</pubDate>
            <atom:updated>2024-06-10T22:36:56.437Z</atom:updated>
            <content:encoded><![CDATA[<h4>LAST UPDATED: JUNE 11, 2024</h4><h4>A Step-by-Step Breakdown of the Source Code and Mathematical Formulation</h4><p>YOLOv5 🚀 has been one of the most widely used YOLO algorithms during the last few years, and is still very popular today. YOLOv5 introduced some improvements to the YOLOv4 architecture, enhancing its performance and becoming one of the most accurate and fast object detection models available. YOLOv5 is more than just a single model architecture, it is a comprehensive <a href="https://github.com/ultralytics/yolov5">repository</a> with many features for training and evaluating YOLOv5 models. It was created by <a href="https://www.linkedin.com/in/glenn-jocher/">Glenn Jocher</a>, the founder of <a href="https://www.ultralytics.com/">Ultralytics</a>, in 2020, and is still maintained by the Ultralytics team and subject to changes.</p><p>Recently, I have been trying to implement the YOLOv5 model from scratch, and the loss function has been one of the toughest parts to fully understand, as there is very little information explaining how it has actually been implemented in the repository. Moreover, there is no published paper or official mathematical formulation of the loss function (at least I have not found it). However, Ultralytrics has a <a href="https://docs.ultralytics.com/yolov5/tutorials/architecture_description/">documentation website</a> where some YOLOv5 concepts are explained.</p><p>Despite being helpful to review, it was not sufficient to fully understand and implement the loss function from scratch. For this reason, I saw no other way but to analyze the source code step by step, trying to understand every detail of their implementation.</p><p>In this article, I would like to review and provide a thorough explanation of everything I have found out during my analysis of the YOLOv5 loss function. Despite the complexity of some aspects, I intend to make it easily digestible to save time for those of you who may be going through the same process or are just curious about the topic. I will discuss three main things:</p><ul><li>Firstly, I will provide an in-depth conceptual explanation of the rationale behind the YOLOv5 loss implementation, drawn from my experience analyzing the source code and reviewing the documentation.</li><li>Secondly, I will examine each line of code step by step with a guided example to better understand the actual implementation and show how it is efficiently implemented using PyTorch in the <a href="https://github.com/ultralytics/yolov5">official YOLOv5 Ultralytics repository</a>.</li><li>Finally, I will provide a mathematical formulation for the reviewed implementation of the YOLOv5 loss function, which I believe can be valuable to readers.</li></ul><p>Additionally, I have created a <a href="https://github.com/pgmesa/yolo-from-scratch">GitHub repository</a> with the entire source code analysis, as well as a cleaned and fully documented implementation of the YOLOv5 and YOLOv3 loss functions, following the concepts explained in the first section.</p><p>⚠️This article assumes that you have a good understanding of PyTorch and the basics of the YOLO architecture, such as anchors, prediction layers, bounding box prediction formulas, etc.</p><h3><strong>1. Conceptual Explanation</strong></h3><p>Before diving into the code, let me first explain the concepts visually, so that later we can delve into the code and see how they are implemented.</p><h4><strong>Loss Components</strong></h4><p>The loss is made up of three different parts:</p><ul><li><strong><em>Class loss</em></strong><em>: </em>It is the loss associated with the error in the classification task. It uses Binary Cross Entropy (BCE) to support multi-label classification.</li><li><strong><em>Objectness loss</em></strong>: It is the loss associated with the error in detecting the presence of an object in a particular grid cell. It also uses BCE.</li><li><strong><em>Bounding box loss</em></strong>: It is the loss associated with the bounding box prediction error. This is a regression task and, like YOLOv4, it uses the IoU loss (CIoU by default), which has been shown to perform better than MSE for this problem.</li></ul><p>These losses are computed for each prediction layer and then summed up. Each loss component is weighted to control its contribution (tunable hyperparameters). Additionally, the objectness loss has an extra weight that varies for each prediction layer to ensure predictions at different scales contribute appropriately to the total loss. Below is the summarized loss formula for a single sample (P3, P4 and P5 refer to each of the three default prediction layers):</p><figure><img alt="Summarized YOLOv5 loss formula for a single sample" src="https://cdn-images-1.medium.com/max/892/1*RRVPY1EXcphlf5ZpFPfxOQ.png" /><figcaption>Summarized YOLOv5 loss formula for a single sample. Source: Image by the author.</figcaption></figure><h4>Bounding Box Prediction Formulas</h4><p>YOLOv5 introduces a new formula for calculating the bounding box predictions that differs from the previous YOLO versions:</p><figure><img alt="YOLOv2-v3 bounding box prediction formulas" src="https://cdn-images-1.medium.com/max/1024/1*hGJvuPivOqQzKsmtozVQxw.png" /><figcaption>YOLOv2-v3 bounding box prediction formulas. Source: Image by the author.</figcaption></figure><figure><img alt="YOLOv5 bounding box prediction formulas" src="https://cdn-images-1.medium.com/max/1024/1*jdvMLj3WrsQCmtjz7qLoGw.png" /><figcaption>YOLOv5 bounding box prediction formulas. Source: Image by the author.</figcaption></figure><p>As explained in the <a href="https://docs.ultralytics.com/yolov5/tutorials/architecture_description/#43-eliminate-grid-sensitivity">Ultralytics documentation</a>, these formulas address the issue of grid sensitivity in <em>bx</em> and <em>by</em> and impose a boundary to the <em>bw</em> and <em>bh</em> predictions to avoid previous problems such as runaway gradients, instabilities and NaN losses due to the unbounded exponential function.</p><p>The range for <em>bx </em>and <em>by </em>is now from -0.5 to 1.5, while <em>bw </em>and <em>bh </em>range from 0 to 4. Consequently, the maximum adjustment allowed for a predefined anchor box’s width (<em>pw</em>) or height (<em>ph</em>) to align with our ground truth (GT) box is 4 times its original size. This is crucial because if, for example, a selected anchor has <em>pw=0.8</em> and the ground truth width <em>bw=4.7</em>, it becomes impossible for that cell to accurately predict the ground truth box. This limitation occurs because the maximum adjustment possible for <em>pw</em> is 4 times, resulting in 0.8 * 4 = 3.2, which is still considerably less than 4.7.</p><h4><strong>Terminology explanation</strong></h4><p>The terminology used in the realm of YOLO can sometimes be a little confusing, so let’s first clarify some concepts that will be used in the following sections of the article:</p><ul><li><strong><em>Anchors</em></strong>: They refer to a predefined set of bounding boxes that serve as reference points for object detection models. These anchors are typically chosen to represent a diverse range of object shapes and sizes effectively. They are usually computed by running a k-means clustering algorithm on the bounding boxes from a custom dataset, extracting the best k anchors that minimize the difference between the predicted and actual bounding boxes. This helps the model generalize better to objects of varying scales and aspect ratios.</li><li><strong><em>Cell anchor or cell prediction box</em></strong>: Each cell in a YOLO model can predict N bounding boxes. Typically, the number of boxes a model layer can predict is set to the number of selected anchor boxes for that layer. In this way, each cell prediction box is assigned to a different anchor box and is therefore responsible for predicting different object shapes. These cell prediction boxes will also be called cell anchors, referring to the fact that each prediction box uses a different anchor as the base prediction shape.</li><li><strong><em>Targets or Ground Truth (GT)</em></strong>: These refer to the object annotation information, such as the bounding box and object class.</li><li><strong><em>Built-Targets</em></strong>: In this article, this term will refer to the processed targets after being output from the <em>build_targets </em>function. Each built-target contains information about the indices of the cell anchors that are tasked with predicting a target (object) and its associated information.</li></ul><p>The diagram below further explains these concepts:</p><figure><img alt="Diagram illustrating key concepts in YOLO terminology, including anchors, cell anchors, targets (ground truth), and built-targets" src="https://cdn-images-1.medium.com/max/1024/1*YxsPyoKJLQ6Ie3xq4z8LmA.png" /><figcaption>Diagram illustrating important concepts in YOLO terminology. Source: Image by the author.</figcaption></figure><h4><strong>Assigning Targets to Cell Anchors</strong></h4><p>In previous YOLO versions, such as YOLOv3, usually the process of assigning targets (ground truth objects) to cell anchors followed a different approach than in YOLOv5.</p><ol><li><strong>YOLOv3 approach</strong></li></ol><p>In YOLOv3, for each prediction layer, we calculate for each target which is the grid cell that contains the center point of the ground truth object. Then, once the target has been assigned to that cell, we compare the bounding box with each of the predefined layer anchors and select the one that has the greater IoU with the ground truth box.</p><p>When the best-fitting anchor falls below a certain threshold (<em>iou_t</em>), it is discarded, and the target is not used in that specific layer, awaiting a better fit with the anchors of a different prediction layer. If there is a good match for that target with anchors from different layers, the same target is assigned to a cell anchor across different scales.</p><p>Lastly, imagine that more than one cell anchor is a very good fit for an object, let’s say that two out of the three different predefined anchors have an <em>IoU &gt; ignore_t </em>(<em>ignore_t </em>can be equal to<em> iou_t </em>or different)<em>.</em> In this case, as only one can be selected<em>, </em>then the remaining anchors that have not been selected as the best ones, but still have a very good overlap with the ground truth, are ignored in the objectness loss computation. This way, we avoid penalizing good anchor boxes that have not been selected, which could cause training instabilities.</p><figure><img alt="YOLOv3 summarized approach to assigning targets to anchors" src="https://cdn-images-1.medium.com/max/1024/1*rOFQoB1zCTTmC0S6wrGCdw.png" /><figcaption>YOLOv3 summarized approach to assigning targets to anchors. Source: Image by the author.</figcaption></figure><p>Note that with this approach, each target can only be assigned to one cell, the one that contains the center point of the object in that specific prediction layer/scale and only to the best fitting anchor, if the IoU is good enough. Additionally, the same target can be assigned at the same time to other cell anchor of different prediction scales.</p><p>2. <strong>YOLOv5 Approach</strong></p><p>In YOLOv5, as in YOLOv3, for each layer, we start by calculating, for each target, which is the grid cell that contains the center point of the ground truth object. From this point onwards, things start to differ.</p><p>First, we compare each target (ground truth) to each anchor, and we select all the anchors, not only the best one, that meet the following requirement <em>rmax &lt; anchor_t:</em></p><figure><img alt="Anchor-Target fit evaluation formulas" src="https://cdn-images-1.medium.com/max/1024/1*AjXW98cfIBW75ewhsA9m-g.png" /><figcaption>Anchor-Target fit evaluation formulas. Source: Image by the author.</figcaption></figure><p>But what does this mean? Well, this is just another way of evaluating whether an anchor box is a good fit for a ground truth box. By default, the parameter <em>anchor_t </em>is usually set to 4.</p><p>But why 4? If you remember the previous part about the new bounding box prediction formulas, the maximum change we can apply to the sides of the anchor box is 4 times their original size. Hence, if <em>rmax</em>, which represents the maximum ratio in either width or height, exceeds 4, we won’t be able to fit the ground truth object under any circumstances. The following diagrams illustrate this concept with two examples:</p><figure><img alt="Anchors fit evaluation example: Anchors smaller than ground truth object" src="https://cdn-images-1.medium.com/max/1024/1*DmWu7IkllwH5S4a0Eod3iA.png" /><figcaption>Anchors fit evaluation example: Anchors smaller than ground truth object. Source: Image by the author.</figcaption></figure><figure><img alt="Anchors fit evaluation example: Anchors bigger than ground truth object" src="https://cdn-images-1.medium.com/max/1024/1*gi1omGZBbA59zdVMwir7ww.png" /><figcaption>Anchors fit evaluation example: Anchors bigger than ground truth object. Source: Image by the author.</figcaption></figure><p>So what we are saying is, if there’s no way to perfectly fit the anchor box to the ground truth object, discard it, but select all the others that can be modified to fit the GT box.</p><p><strong>Now that we understand how target-anchor pairs are created, let’s examine how cells are chosen.</strong></p><p>With these new formulas, it’s important to note that predictions for each cell are no longer confined to that cell alone. Each cell can now predict <em>x</em>, <em>y</em> coordinates that extend beyond its boundaries. This is due to the added offsets, expanding the range from -0.5 to 1.5.</p><figure><img alt="YOLOv3-v5 (x, y) prediction boundaries" src="https://cdn-images-1.medium.com/max/1024/1*sb7C3e_G0L43M7fTEmw5vA.png" /><figcaption>YOLOv3-v5 (x, y) prediction boundaries. Source: Image by the author.</figcaption></figure><p>For this reason, in YOLOv5, they have implemented a strategy in which they attempt to select more than one cell per target. They choose adjacent cells to the one containing the center of the object. Each main cell is divided into four sectors, and adjacent cells are selected based on the center point’s location.</p><p>If the center point is in the top-left corner, the top and left cells will also be selected, and so on. Therefore, if any of the anchors is a good fit, a minimum of one cell is selected for each ground truth object, with the possibility of adding one or two more cells depending on the cell and center point locations on the grid.</p><figure><img alt="YOLOv5 summarized approach to assigning targets to anchors" src="https://cdn-images-1.medium.com/max/1024/1*_N-NH7OvoU6_OTrvuvMLmA.png" /><figcaption>YOLOv5 summarized approach to assigning targets to anchors. Source: Image by the author.</figcaption></figure><p>By implementing this change, the number of cell anchors considered to contain an object increases in each prediction layer. Now, more cells are tasked with predicting an object, rather than just one as in YOLOv3. As a result, this amplifies the number of positive samples for the model’s prediction, enhancing its sensitivity to such instances and refining its ability to distinguish objects from the background.</p><h3><strong>2. Source Code Explanation</strong></h3><p>We will follow a guided example so that everything is easier to understand. Suppose we have input a batch of 2 images of size 320x320 into the model. Our dataset has 20 classes, and the number of anchors per layer is 3. Our model uses the default three prediction layers of the YOLOv5 architecture, with strides [P3: 8, P4: 16, P5: 32].</p><p>The input variables for the loss function are <em>p </em>and <em>targets</em>:</p><ul><li><em>p </em>is a list of <em>torch.Tensor</em> objects, each one corresponding to a different prediction layer (small:P3, medium:P4 and large:P5 objects). Each tensor has a shape<em> (batch_size, num_anchors, num_cells_y, num_cells_x, 5+num_classes)</em>.</li><li><em>targets </em>is a <em>torch.Tensor</em> object of shape <em>(num_targets, 6)</em>. Each element contains <em>(img_id, class, x, y, w, h)</em> for each ground truth. All coordinates and size values <em>(x, y, w, h)</em> are scaled in the range [0, 1]. So, if the bounding box of an object has values (280, 130, 30, 50), its scaled values would be (280/img_size_x, 130/img_size_y, 30/img_size_x, 50/img_size_y).</li></ul><p>In this case, the prediction heads would output 3 tensors of shape:</p><ul><li>P3: (2, 3, 320//8, 320//8, 5+20) = (2, 3, 40, 40, 25)</li><li>P4: (2, 3, 320//16, 320//16, 5+20) = (2, 3, 20, 20, 25)</li><li>P5: (2, 3, 320//32, 320//32, 5+20) = (2, 3, 10, 10, 25)</li></ul><p>Let’s suppose that Image 1 has 3 objects and Image 2 has 2 objects. In total, we have 5 target objects (ground truths). Therefore, <em>targets </em>would have shape (5, 6).</p><p>Below is the code that defines the initial variables for our analysis:</p><pre>device = &#39;cpu&#39;<br>img_size = 320<br>num_classes = 20; num_layers = 3<br>anchor_t = 4.0<br><br># Loss weights<br>balance = [4.0, 1.0, 0.4]<br>lambda_box = 0.05; lambda_obj = 0.7; lambda_cls = 0.3<br><br>anchors = torch.tensor([<br>    # P3 anchors<br>    [[ 1.25000,  1.62500],[ 2.00000,  3.75000],[ 4.12500,  2.87500]], <br>    # P4 anchors<br>    [[ 1.87500,  3.81250],[ 3.87500,  2.81250],[ 3.68750,  7.43750]], <br>    # P5 anchors<br>    [[ 3.62500,  2.81250],[ 4.87500,  6.18750],[11.65625, 10.18750]], <br>])<br>assert anchors.shape[0] == num_layers<br>num_anchors = anchors.shape[1]<br><br>targets = torch.tensor([<br>        [ 0.00000, 14.00000,  0.49535,  0.50528,  0.15267,  0.56956],<br>        [ 0.00000,  0.00000,  0.54872,  0.92491,  0.05361,  0.03183],<br>        [ 0.00000,  0.00000,  0.36780,  0.98716,  0.06031,  0.02567],<br>        [ 1.00000,  6.00000,  0.97072,  0.04398,  0.05856,  0.08796],<br>        [ 1.00000, 16.00000,  0.70696,  0.10348,  0.32971,  0.16793],<br>])<br>batch_size = len(targets[:,:1].unique())<br><br>strides = [8, 16, 32]<br>p = [<br>    torch.randn((batch_size, num_anchors, img_size//strides[i], img_size//strides[i], 5 + num_classes)) <br>    for i in range(num_layers)<br>]<br><br>print(&quot;Targets Shape:&quot;, targets.shape)<br>print(&quot;Anchors Shape:&quot;, anchors.shape)<br>for i, pi in enumerate(p):<br>    print(f&quot;Layer P{i+3} Shape:&quot;, pi.shape)<br><br>====================================================================<br><br>&gt;&gt;&gt; Targets Shape: torch.Size([5, 6])<br>&gt;&gt;&gt; Anchors Shape: torch.Size([3, 3, 2])<br>&gt;&gt;&gt; Layer P3 Shape: torch.Size([2, 3, 40, 40, 25])<br>&gt;&gt;&gt; Layer P4 Shape: torch.Size([2, 3, 20, 20, 25])<br>&gt;&gt;&gt; Layer P5 Shape: torch.Size([2, 3, 10, 10, 25])</pre><p>The file we are going to analyze is located in <a href="https://github.com/ultralytics/yolov5/blob/master/utils/loss.py">utils/loss.py</a>. In case the repository changes in the future after publishing this article, and maybe the link provided is broken or the code has changed, I will leave here the current <a href="https://github.com/ultralytics/yolov5/tree/c0380fd85549c8b315bb1fb2f423f9297e9744ec">GitHub commit</a> I used in the analysis, so you can go to <a href="https://github.com/ultralytics/yolov5/blob/c0380fd85549c8b315bb1fb2f423f9297e9744ec/utils/loss.py">utils/loss.py</a> and review the code we are going to examine now.</p><p>The important code part is defined in the <em>ComputeLoss </em>class. Let’s review each method of this class:</p><blockquote>__init__</blockquote><pre>class ComputeLoss:<br>    sort_obj_iou = False<br><br>    # Compute losses<br>    def __init__(self, model, autobalance=False):<br>        &quot;&quot;&quot;Initializes ComputeLoss with model and autobalance option, autobalances losses if True.&quot;&quot;&quot;<br>        device = next(model.parameters()).device  # get model device<br>        h = model.hyp  # hyperparameters<br><br>        # Define criteria<br>        BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h[&quot;cls_pw&quot;]], device=device))<br>        BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h[&quot;obj_pw&quot;]], device=device))<br><br>        # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3<br>        self.cp, self.cn = smooth_BCE(eps=h.get(&quot;label_smoothing&quot;, 0.0))  # positive, negative BCE targets<br><br>        # Focal loss<br>        g = h[&quot;fl_gamma&quot;]  # focal loss gamma<br>        if g &gt; 0:<br>            BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)<br><br>        m = de_parallel(model).model[-1]  # Detect() module<br>        self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02])  # P3-P7<br>        self.ssi = list(m.stride).index(16) if autobalance else 0  # stride 16 index<br>        self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance<br>        self.na = m.na  # number of anchors<br>        self.nc = m.nc  # number of classes<br>        self.nl = m.nl  # number of layers<br>        self.anchors = m.anchors<br>        self.device = device</pre><p>This first part initializes the loss class function. The important things to pay attention to here are:</p><ul><li><strong><em>BCEcls</em></strong> and <strong><em>BCEobj</em></strong> are BCEWithLogitsLoss instances, with the possibility to specify a weight for the positive sample loss, which is useful in cases where the dataset is imbalanced.</li><li>Label smoothing by default is not used. Therefore, <strong><em>self.cp = 1</em></strong> (class positive value) and <strong><em>self.cn = 0</em></strong><em> </em>(class negative value).</li><li>Focal loss is also not used by default, <strong><em>g = h[“fl_gamma”] = 0</em></strong><em>.</em></li><li><strong><em>de_parallel()</em></strong> function removes DataParallel or DistributedDataParallel wrappers in case of multiple GPUs being used and returns a single GPU model. It is not important for understanding the loss function.</li><li><strong><em>self.balance</em></strong> will be [4.0, 1.0, 0.4] when number of layers is 3, which is our case.</li><li>We can ignore <strong><em>self.ssi</em></strong>, because we are not going to use autobalance (changes iteratively the balance value of each layer objectness loss weight). This feature is useful for optimizing the balance parameter for custom datasets, but it is not used by default.</li><li><strong><em>self.na</em></strong> is the number of anchors in each layer and by default is 3,<strong><em> self.nc</em></strong> is the number of classes in the dataset and <strong><em>self.nl</em></strong> is the number of prediction layers, which by default is also 3.</li><li><strong><em>self.anchors</em></strong> stores the predefined anchors of each prediction layer.</li></ul><blockquote><em>build_targets</em></blockquote><p>The <em>__call__ </em>method performs the forward pass, calculating the losses for each prediction layer. Before explaining how the <em>__call__ </em>method computes the loss, let’s first describe the <em>build_targets </em>method. This method is invoked in the initial lines of the <em>__call__ </em>function and it is responsible for assigning targets to cell anchors and preparing them for loss computation according to the YOLOv5 formulation. Let’s go through this step by step:</p><pre>def build_targets(self, p, targets):<br>    &quot;&quot;&quot;Prepares model targets from input targets (image,class,x,y,w,h) for loss computation, returning class, box,<br>    indices, and anchors.<br>    &quot;&quot;&quot;<br>    na, nt = self.na, targets.shape[0]  # number of anchors, targets<br>    tcls, tbox, indices, anch = [], [], [], []<br>    gain = torch.ones(7, device=self.device)  # normalized to gridspace gain<br>    ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt)  # same as .repeat_interleave(nt)<br>    targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2)  # append anchor indices<br><br>    g = 0.5  # bias<br>    off = (<br>        torch.tensor(<br>            [<br>                [0, 0],<br>                [1, 0],<br>                [0, 1],<br>                [-1, 0],<br>                [0, -1],  # j,k,l,m<br>                # [1, 1], [1, -1], [-1, 1], [-1, -1],  # jk,jm,lk,lm<br>            ],<br>            device=self.device,<br>        ).float()<br>        * g<br>    )  # offset</pre><p>This is the first part of the function. Steps:</p><ol><li>Store the values of number of anchors and targets (<em>na = 3, nt = 5</em>)</li><li>Initialize the output of the function (<em>tcls, tbox, indices, anc</em>h) with empty lists.</li><li>Initialize the <em>gain </em>tensor that will be used later for scaling the targets in each layer (<em>shape=(7,)</em>).</li><li>Map each target to each anchor</li></ol><pre>ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt)  # same as .repeat_interleave(nt)<br>targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2)  # append anchor indices</pre><p>The purpose of the above 2 lines of code is to create a tensor that maps each target to each anchor. We have 3 anchors in each prediction layer, so we want to compare each target (GT) to each of the 3 anchors, resulting in 5*3=15 comparisons. To achieve this, we repeat the <em>target </em>tensor (<em>Size([5,6])</em>) 3 times along a new first dimension, creating a tensor of shape <em>[3, 5, 6]</em>. Then, we append the index of the anchor (<em>ai</em>) to each target array, resulting in a shape of <em>[3, 5, 7]</em>, where each target contains <em>(img_id, class, x, y, w, h, anchor_id)</em>.</p><blockquote><strong>Note</strong>: <em>ai[…, None]</em> is equivalent to <em>ai.unsqueeze(-1)</em>, which adds a size-one dimension at the end. <em>Size([3,5]) -&gt; Size([3,5,1])</em>.</blockquote><pre>ai<br>&gt;&gt;&gt; tensor([[0., 0., 0., 0., 0.],<br>            [1., 1., 1., 1., 1.],<br>            [2., 2., 2., 2., 2.]]) # Anchor indices<br><br>targets<br>&gt;&gt;&gt; tensor([<br>    [[ 0.0000, 14.0000,  0.4954,  0.5053,  0.1527,  0.5696,  0.0000],<br>     [ 0.0000,  0.0000,  0.5487,  0.9249,  0.0536,  0.0318,  0.0000],<br>     [ 0.0000,  0.0000,  0.3678,  0.9872,  0.0603,  0.0257,  0.0000],<br>     [ 1.0000,  6.0000,  0.9707,  0.0440,  0.0586,  0.0880,  0.0000],<br>     [ 1.0000, 16.0000,  0.7070,  0.1035,  0.3297,  0.1679,  0.0000]],<br><br>    [[ 0.0000, 14.0000,  0.4954,  0.5053,  0.1527,  0.5696,  1.0000],<br>     [ 0.0000,  0.0000,  0.5487,  0.9249,  0.0536,  0.0318,  1.0000],<br>     [ 0.0000,  0.0000,  0.3678,  0.9872,  0.0603,  0.0257,  1.0000],<br>     [ 1.0000,  6.0000,  0.9707,  0.0440,  0.0586,  0.0880,  1.0000],<br>     [ 1.0000, 16.0000,  0.7070,  0.1035,  0.3297,  0.1679,  1.0000]],<br><br>    [[ 0.0000, 14.0000,  0.4954,  0.5053,  0.1527,  0.5696,  2.0000],<br>     [ 0.0000,  0.0000,  0.5487,  0.9249,  0.0536,  0.0318,  2.0000],<br>     [ 0.0000,  0.0000,  0.3678,  0.9872,  0.0603,  0.0257,  2.0000],<br>     [ 1.0000,  6.0000,  0.9707,  0.0440,  0.0586,  0.0880,  2.0000],<br>     [ 1.0000, 16.0000,  0.7070,  0.1035,  0.3297,  0.1679,  2.0000]]])</pre><p>5. Define the offsets in each grid direction (<em>j, k, l, m</em>) (left, up, right, down)</p><pre># j,k,l,m<br>torch.tensor(<br>  [[0, 0], [1, 0], [0, 1], [-1, 0], [0, -1]],<br>   device=self.device<br>).float() * g</pre><p>These offsets will be subtracted from the built-targets grid coordinates <em>(gxy - offsets)</em>, so a 1 actually represents a -1 unit in that dimension. For example, <em>[1, 0] (j)</em>, indicates subtracting 1 unit in the <em>x-</em>dimension, referring to the left adjacent cell.</p><p>The <em>g </em>term scales these adjustments to 0.5 units, which is sufficient because positive offsets [0.5, 0] and [0, 0.5] are always subtracted from values with a decimal part less than 0.5, while negative offsets [-0.5, 0] and [0, -0.5] are always subtracted from values with a decimal part greater than 0.5. This consistently changes the integer part of the grid coordinate value, and therefore the grid cell index.</p><p>Now, let’s explain the logic behind the target-anchors assignment:</p><pre> for i in range(self.nl):<br>    anchors, shape = self.anchors[i], p[i].shape<br>    gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]]  # xyxy gain<br><br>    # Match targets to anchors<br>    t = targets * gain  # shape(3,n,7)<br>    if nt:<br>        # Matches<br>        r = t[..., 4:6] / anchors[:, None]  # wh ratio<br>        j = torch.max(r, 1 / r).max(2)[0] &lt; self.hyp[&quot;anchor_t&quot;]  # compare<br>        # j = wh_iou(anchors, t[:, 4:6]) &gt; model.hyp[&#39;iou_t&#39;]  # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))<br>        t = t[j]  # filter<br><br>        # Offsets<br>        gxy = t[:, 2:4]  # grid xy<br>        gxi = gain[[2, 3]] - gxy  # inverse<br>        j, k = ((gxy % 1 &lt; g) &amp; (gxy &gt; 1)).T<br>        l, m = ((gxi % 1 &lt; g) &amp; (gxi &gt; 1)).T<br>        j = torch.stack((torch.ones_like(j), j, k, l, m))<br>        t = t.repeat((5, 1, 1))[j]<br>        offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]<br>    else:<br>        t = targets[0]<br>        offsets = 0</pre><p>For each prediction layer output (let’s assume we are using the P3 output, <em>i = 0</em>) we get the anchors for that layer, determine the output shape and scale <em>x, y, w, h</em> with respect to the grid size of that layer.</p><pre>anchors, shape = self.anchors[i], p[i].shape<br>gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]]  # xyxy gain<br><br># Match targets to anchors<br>t = targets * gain  # shape(3,n,7)</pre><pre>i<br>&gt;&gt;&gt; 0<br><br>anchors<br>&gt;&gt;&gt; tensor([[1.2500, 1.6250],<br>            [2.0000, 3.7500],<br>            [4.1250, 2.8750]])<br><br>shape<br>&gt;&gt;&gt; torch.Size([2, 3, 40, 40, 25])<br><br>gain<br>&gt;&gt;&gt; tensor([1., 1., 40., 40., 40., 40., 1.])<br><br>t<br>&gt;&gt;&gt; tensor([[<br>       [ 0.0000, 14.0000, 19.8140, 20.2112,  6.1068, 22.7824,  0.0000],<br>       [ 0.0000,  0.0000, 21.9488, 36.9964,  2.1444,  1.2732,  0.0000],<br>       [ 0.0000,  0.0000, 14.7120, 39.4864,  2.4124,  1.0268,  0.0000],<br>       [ 1.0000,  6.0000, 38.8288,  1.7592,  2.3424,  3.5184,  0.0000],<br>       [ 1.0000, 16.0000, 28.2784,  4.1392, 13.1884,  6.7172,  0.0000]],<br><br>      [[ 0.0000, 14.0000, 19.8140, 20.2112,  6.1068, 22.7824,  1.0000],<br>       [ 0.0000,  0.0000, 21.9488, 36.9964,  2.1444,  1.2732,  1.0000],<br>       [ 0.0000,  0.0000, 14.7120, 39.4864,  2.4124,  1.0268,  1.0000],<br>       [ 1.0000,  6.0000, 38.8288,  1.7592,  2.3424,  3.5184,  1.0000],<br>       [ 1.0000, 16.0000, 28.2784,  4.1392, 13.1884,  6.7172,  1.0000]],<br><br>      [[ 0.0000, 14.0000, 19.8140, 20.2112,  6.1068, 22.7824,  2.0000],<br>       [ 0.0000,  0.0000, 21.9488, 36.9964,  2.1444,  1.2732,  2.0000],<br>       [ 0.0000,  0.0000, 14.7120, 39.4864,  2.4124,  1.0268,  2.0000],<br>       [ 1.0000,  6.0000, 38.8288,  1.7592,  2.3424,  3.5184,  2.0000],<br>       [ 1.0000, 16.0000, 28.2784,  4.1392, 13.1884,  6.7172,  2.0000]]])</pre><p>We then check if the anchors meet the requirement <em>rmax &lt; anchor_t</em>, which we reviewed previously. Here, <em>r (Size([3,5,2]))</em> contains the <em>rw </em>and <em>rh </em>target-anchor ratios. Using <em>torch.max(r, 1 / r).max(2)[0]</em>, we obtain <em>rmax</em>, while <em>j (Size([3,5]))</em> represents a boolean mask indicating whether each target-anchor pair meets the requirement. Finally, as the last step, <em>t </em>is filtered to only contain those that meet this requirement, resulting in a change in its size to <em>[num_pairs_selected, 7]</em>:</p><pre># Matches<br>r = t[..., 4:6] / anchors[:, None]  # wh ratio<br>j = torch.max(r, 1 / r).max(2)[0] &lt; self.hyp[&quot;anchor_t&quot;]  # compare<br>t = t[j]  # filter</pre><pre>j<br>&gt;&gt;&gt; tensor([[False,  True,  True,  True, False],<br>            [False,  True,  True,  True, False],<br>            [False,  True,  True,  True,  True]])<br><br>t[j]<br>&gt;&gt;&gt; tensor([<br>      [ 0.0000,  0.0000, 21.9488, 36.9964,  2.1444,  1.2732,  0.0000],<br>      [ 0.0000,  0.0000, 14.7120, 39.4864,  2.4124,  1.0268,  0.0000],<br>      [ 1.0000,  6.0000, 38.8288,  1.7592,  2.3424,  3.5184,  0.0000],<br>      [ 0.0000,  0.0000, 21.9488, 36.9964,  2.1444,  1.2732,  1.0000],<br>      [ 0.0000,  0.0000, 14.7120, 39.4864,  2.4124,  1.0268,  1.0000],<br>      [ 1.0000,  6.0000, 38.8288,  1.7592,  2.3424,  3.5184,  1.0000],<br>      [ 0.0000,  0.0000, 21.9488, 36.9964,  2.1444,  1.2732,  2.0000],<br>      [ 0.0000,  0.0000, 14.7120, 39.4864,  2.4124,  1.0268,  2.0000],<br>      [ 1.0000,  6.0000, 38.8288,  1.7592,  2.3424,  3.5184,  2.0000],<br>      [ 1.0000, 16.0000, 28.2784,  4.1392, 13.1884,  6.7172,  2.0000]])<br><br>t[j].shape<br>&gt;&gt;&gt; torch.Size([10, 7])</pre><p>Now that we have the target-anchor pairs that passed the filter, let’s assign them to the cell that contains their center point and also to the adjacent cells, as reviewed earlier, depending on the location of the center point within the cell.</p><pre># Offsets<br>gxy = t[:, 2:4]  # grid xy<br>gxi = gain[[2, 3]] - gxy  # inverse<br>j, k = ((gxy % 1 &lt; g) &amp; (gxy &gt; 1)).T<br>l, m = ((gxi % 1 &lt; g) &amp; (gxi &gt; 1)).T</pre><p>To explain this part, which can be a little confusing at first, let’s clarify two things. First, the <em>x % 1</em> operator is used to obtain the decimal part of a number <em>x </em>(e.g., 3.72 % 1 = 0.72). Second, the variables <em>j, k, l, m</em> correspond to each direction in the grid cell:</p><ul><li>The variables <em>j </em>and<em> l </em>respectively stores whether the center point is on the left/right side of the middle vertical line of the cell and if there’s a cell to the left/right of the current one or if we’re at the grid’s edge. If both conditions are true, the left/right adjacent cell will also be selected.</li><li>The variables <em>k </em>and <em>m </em>respectively stores whether the center point is above/below the middle horizontal line of the cell and if there’s a cell above/below the current one or if we’re at the grid’s edge. If both conditions are true, the upper/bottom adjacent cell will also be selected.</li></ul><p>To compute the conditions for <em>l </em>and <em>m</em>, the strategy involves reversing the coordinates of the origin of the grid cell (<em>gxi = gain[[2, 3]] - gxy</em>) and applying the same conditions as in <em>j </em>and <em>k</em>, respectively. This process is illustrated in the figure below:</p><figure><img alt="Example computation of conditions (j, k, l, m)" src="https://cdn-images-1.medium.com/max/851/1*Z7zWVdY_YHiq1i-TBytusw.png" /><figcaption>Example computation of conditions (j, k, l, m). Source: Image by the author</figcaption></figure><p>Once all conditions are computed, a large boolean mask is created to select all main cells (where the center point lies) and their respective adjacent cells selected (stored in <em>j, k, l, m</em>).</p><pre>j = torch.stack((torch.ones_like(j), j, k, l, m))<br>t = t.repeat((5, 1, 1))[j]</pre><pre>j<br>&gt;&gt;&gt; tensor([<br>  # Select main cell, where the object center point lies<br>  [ True,  True,  True,  True,  True,  True,  True,  True,  True,  True],<br>  # Select the adjacent cell to the left of the main cell<br>  [False, False, False, False, False, False, False, False, False,  True],<br>  # Select the adjacent cell above the main cell<br>  [False,  True, False, False,  True, False, False,  True, False,  True],<br>  # Select the adjacent cell to the right of the main cell<br>  [ True,  True,  True,  True,  True,  True,  True,  True,  True, False],<br>  # Select the adjacent cell below the main cell<br>  [ True, False,  True,  True, False,  True,  True, False,  True, False]])<br><br>t.shape<br>&gt;&gt;&gt; torch.Size([30, 7])</pre><p>So, the number of built-targets will range from the minimum of the number of first filtered target-anchor pairs (10) to three times that (30), due to the possibility of selecting up to two more cells per main cell.</p><p>However, the built-targets stored at this point in <em>t </em>are not accurate because the (<em>x, y)</em> coordinates still refer to the main cell. Therefore, the offsets are computed using the previously defined direction offsets <em>(off) </em>and are stored to be applied in the next and final step.</p><pre>offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]</pre><p>As the last step of this function, we prepare the final built-targets for loss computation:</p><pre>  # Define<br>  bc, gxy, gwh, a = t.chunk(4, 1)  # (image, class), grid xy, grid wh, anchors<br>  a, (b, c) = a.long().view(-1), bc.long().T  # anchors, image, class<br>  gij = (gxy - offsets).long()<br>  gi, gj = gij.T  # grid indices<br><br>  # Append<br>  indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1)))  # image, anchor, grid<br>  tbox.append(torch.cat((gxy - gij, gwh), 1))  # box<br>  anch.append(anchors[a])  # anchors<br>  tcls.append(c)  # class<br><br>return tcls, tbox, indices, anch</pre><p>In this step, the corresponding grid cell indices for each built-target are computed using the previously calculated offsets (<em>gij = (gxy - offsets).long()</em>). This operation extracts the integer part (cell indices) of the modified (<em>x, y</em>) coordinates:</p><pre>gxy[12:17]<br>&gt;&gt;&gt; tensor([[14.7120, 39.4864],<br>            [14.7120, 39.4864],<br>            [28.2784,  4.1392],<br>            [21.9488, 36.9964],<br>            [14.7120, 39.4864]])<br><br>offsets[12:17]<br>&gt;&gt;&gt; tensor([[ 0.0000,  0.5000],<br>            [ 0.0000,  0.5000],<br>            [ 0.0000,  0.5000],<br>            [-0.5000,  0.0000],<br>            [-0.5000,  0.0000]])<br><br>gxy[12:17] - offsets[12:17]<br>&gt;&gt;&gt; tensor([[14.7120, 38.9864],<br>            [14.7120, 38.9864],<br>            [28.2784,  3.6392],<br>            [22.4488, 36.9964],<br>            [15.2120, 39.4864]])<br><br>gij[12:17]<br>&gt;&gt;&gt; tensor([[14, 38],<br>            [14, 38],<br>            [28,  3],<br>            [22, 36],<br>            [15, 39]])</pre><p>Finally, the function returns 4 outputs:</p><ul><li><strong><em>indices </em></strong><em>(list[tuple[Tensor]])</em>: A list of 3 tuples, one for each layer, containing tensors representing indices for sample indices, cell anchor indices, and grid cell indices. They are used to extract the corresponding model predictions, in which a ground truth object has been assigned.</li><li><strong><em>tbox </em></strong><em>(list[Tensor])</em>: A list of 3 tensors, one for each layer, containing target bounding boxes (<em>x, y, w, h</em>). The (<em>x, y</em>) values are normalized in the range of -0.5 to 1.5, while (<em>w, h</em>) values are adjusted with respect to the layer grid size, ranging from 0 to the number of grid cells along the corresponding axis.</li><li><strong><em>anch </em></strong><em>(list[Tensor])</em>: A list of 3 tensors, one for each layer, containing the anchor (<em>w, h)</em> values of each selected cell anchor.</li><li><strong><em>tcls </em></strong><em>(list[Tensor])</em>: A list of 3 tensors, one for each layer, containing the target class labels.</li></ul><blockquote>__call__</blockquote><p>Once we’ve built the targets, the worst part is over.</p><pre>def __call__(self, p, targets):  # predictions, targets<br>    &quot;&quot;&quot;Performs forward pass, calculating class, box, and object loss for given predictions and targets.&quot;&quot;&quot;<br>    lcls = torch.zeros(1, device=self.device)  # class loss<br>    lbox = torch.zeros(1, device=self.device)  # box loss<br>    lobj = torch.zeros(1, device=self.device)  # object loss<br>    tcls, tbox, indices, anchors = self.build_targets(p, targets)  # targets<br>  <br>    # Losses<br>    for i, pi in enumerate(p):  # layer index, layer predictions<br>        b, a, gj, gi = indices[i]  # image, anchor, gridy, gridx<br>        tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device)  # target obj<br>  <br>        n = b.shape[0]  # number of targets<br>        if n:<br>            # pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1)  # faster, requires torch 1.8.0<br>            pxy, pwh, _, pcls = pi[b, a, gj, gi].split((2, 2, 1, self.nc), 1)  # target-subset of predictions</pre><p>For each prediction layer, we extract the predictions that are responsible for detecting an object. These specific predictions, selected from the entire prediction tensor (<em>pi</em>) using indices calculated in <em>build_targets</em>, are used to compute the box loss, objectness loss, and class loss. The remaining predictions, which are not assigned to a ground truth, will only contribute to the computation of the objectness loss.</p><h4><strong>Bounding Box Regression Loss</strong></h4><pre># Regression<br>pxy = pxy.sigmoid() * 2 - 0.5<br>pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]<br>pbox = torch.cat((pxy, pwh), 1)  # predicted box<br>iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze()  # iou(prediction, target)<br>lbox += (1.0 - iou).mean()  # iou loss</pre><p>This part is straightforward: we apply the formulas to the bounding box predictions, calculate the CIoU (Complete Intersection over Union), and compute the loss as (1 - CIoU). The final box loss is averaged over the number of built-targets in that layer.</p><h4><strong>Define Objectness Targets</strong></h4><pre># Objectness<br>iou = iou.detach().clamp(0).type(tobj.dtype)<br>if self.sort_obj_iou:<br>    j = iou.argsort()<br>    b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j]<br>if self.gr &lt; 1:<br>    iou = (1.0 - self.gr) + self.gr * iou<br>tobj[b, a, gj, gi] = iou  # iou ratio</pre><p>In this part, since <em>self.sort_obj_iou</em> is false and <em>self.gr</em> is always 1.0, we can simplify it to:</p><pre># Objectness<br>iou = iou.detach().clamp(0).type(tobj.dtype)<br>tobj[b, a, gj, gi] = iou  # iou ratio</pre><p>This part prepares the target objectness score for computing the objectness loss in a later step. We set the target objectness score (<em>tobj</em>) for the predictions that should predict an object to be equal to the CIoU calculated in the previous step.</p><p>This could alternatively be set to 1.0, indicating that the model should predict there is an object there. However, by setting it to the CIoU loss, the model predicts how well it thinks the bounding box prediction encloses the target object (<em>tobj[b, a, gj, gi] = iou</em>), instead of simply predicting the presence of an object regardless of the bounding box quality (<em>tobj[b, a, gj, gi] = 1.0</em>). This approach, as mentioned by Glenn Jocher in a <a href="https://github.com/ultralytics/yolov5/issues/6952">GitHub Issue</a>, helps sort out low-accuracy detections during Non-Maximum Suppression (NMS).</p><h4><strong>Classification Loss</strong></h4><pre># Classification<br>if self.nc &gt; 1:  # cls loss (only if multiple classes)<br>    t = torch.full_like(pcls, self.cn, device=self.device)  # targets<br>    t[range(n), tcls[i]] = self.cp<br>    lcls += self.BCEcls(pcls, t)  # BCE</pre><p>This part is straightforward as well. We apply the binary cross-entropy (BCE) loss to the class predictions. The variable <em>t</em> contains the target binary classes for each object, where 1.0 indicates the object belongs to that class and 0 indicates it does not. Remember, YOLOv5 is designed to predict multi-label objects, meaning an object can belong to multiple classes simultaneously (e.g., a dog and a husky). Similar to the bounding box loss, we average the class loss by summing all contributions and dividing by the number of built-targets and the number of classes. This is achieved using the default ‘<em>mean</em>’ reduction parameter of the BCELoss function.</p><h4><strong>Objectness Loss</strong></h4><pre>obji = self.BCEobj(pi[..., 4], tobj)<br>lobj += obji * self.balance[i]  # obj loss</pre><p>The last part is the objectness loss, which involves calculating the binary cross-entropy (BCE) loss between the predicted objectness values and the previously computed target objectness values (0 if no object should be detected and CIoU otherwise). Here, we also average the loss by leaving unchanged the BCE reduction parameter to <em>‘mean’</em>. Since we use all the predictions from that layer, we sum them and then divide by (<em>batch_size * num_anchors * num_cells_x * num_cells_y</em>). We also apply the corresponding layer objectness loss weight defined in the <em>self.balance</em> variable.</p><h4><strong>Final Output</strong></h4><p>Finally, after repeating these steps for each layer and aggregating the loss results, we apply the corresponding weights to each loss component and return the results.</p><pre>lbox *= self.hyp[&quot;box&quot;]<br>lobj *= self.hyp[&quot;obj&quot;]<br>lcls *= self.hyp[&quot;cls&quot;]<br>bs = tobj.shape[0]  # batch size<br><br>return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()</pre><p>This function returns two outputs: the first one is the final aggregated loss, which is scaled by the batch size (<em>bs</em>), and the second one is a tensor with each loss component separated and detached from the PyTorch graph. In the <a href="https://github.com/ultralytics/yolov5/blob/master/train.py">train.py file</a> (line 383), you can see that the former output will be used to backpropagate the gradients, while the latter one is solely for visualization in the progress bar during training and for computing the running mean losses. Therefore, it’s important to bear in mind that the actual loss being used is not the same as what you are visualizing, as the first one is scaled and dependent on the size of each input batch. This distinction can be important when training with dynamic input batch sizes.</p><h3>3. Mathematical formulation</h3><p>After this intensive analysis covering every aspect of the current YOLOv5 loss implementation, a good way to conclude would be to express it in a mathematical formulation. I believe having a mathematical formulation for this loss function, as implemented in the official source code we have just examined, can be valuable.</p><p>The following formula represents the loss function for an input batch of <em>B </em>samples/images:</p><ul><li>The “<em>gt</em>” superscript indicates ground truth.</li><li><em>L</em> is the number of prediction layers, <em>X</em> and <em>Y</em> are the number of cells along each axis, <em>A</em> is the number of anchors, <em>C</em> is the number of classes and <em>B</em> is the batch size.</li><li>Each model prediction (the last dimension of the output tensor in each layer) is in the form (<em>x, y, w, h, obj, *classes</em>). In the formulas, “<em>b”</em> represents the bounding box (<em>x, y, w, h</em>), “<em>O” </em>represents the confidence or objectness score (<em>obj</em>), and “<em>y”</em> represents the array of class predictions (*<em>classes</em>).</li></ul><figure><img alt="YOLOv5 loss equations" src="https://cdn-images-1.medium.com/max/1024/1*bPrefxdZ5zXqAEfs7pRhiA.png" /><figcaption>YOLOv5 loss equations. Source: Image by the author</figcaption></figure><figure><img alt="Binary Cross-Entropy, IoU and CIoU equations" src="https://cdn-images-1.medium.com/max/1024/1*s5ZCNeGxy1J7j8vYhMA8rg.png" /><figcaption>Ancillary equations 1. Source: Image by the author</figcaption></figure><figure><img alt="CIoU expanded equations" src="https://cdn-images-1.medium.com/max/1024/1*IMbfw-boKxlvS_3JGtMTpg.png" /><figcaption>Ancillary equations 2, CIoU expanded equations. Source: Image by the author</figcaption></figure><p>And this concludes our journey! I sincerely hope this article has been useful to you (or at least interesting) and relatively easy to follow, despite delving into some rather intricate subjects. If you have any questions or feedback, please don’t hesitate to share them in the comments below 😃.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffe35e6203e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>