liveBook · Manning

YOLO

As explained in Deep Learning with R, Third Edition

You Only Look Once is a family of single-stage object detection models that predict object locations and categories in a single network evaluation.

YOLO (You Only Look Once) is a family of single-stage object detectors: it predicts bounding boxes and object labels in one step. For applications such as real-time detection, this is generally faster and more efficient than first proposing regions and then classifying them, though accuracy may be slightly lower. section 12.1.2 section 12.2.2

A simplified YOLO detector

A detector for COCO images can use a pretrained ResNet backbone, resize inputs to 448 × 448, and predict on a 6 × 6 grid. Each cell produces one box with a confidence score and probabilities for 91 labels. Unlike the original YOLO model, which predicted multiple boxes per cell, this simplified version predicts one. section 12.2.2

Listing 12.5 Loading the ResNet model
image_size <- c(448, 448)

backbone <- keras_hub$models$Backbone$from_preset(
  "resnet_50_imagenet"
)
preprocessor <- keras_hub$layers$ImageConverter$from_preset(
  "resnet_50_imagenet",
  image_size = shape(image_size)
)

Load the pretrained ResNet backbone and its matching image preprocessor. section 12.2.2

Listing 12.6 Attaching a YOLO prediction head
grid_size <- 6L
num_labels <- 91L

inputs <- keras_input(shape = c(image_size, 3))
x <- inputs |>
  backbone() |>
  layer_conv_2d(512, c(3, 3), strides = c(2, 2)) |>  #1
  layer_flatten() |> 
  layer_dense(2048, activation = "relu",
              kernel_initializer = "glorot_normal") |>  #2
  layer_dropout(0.5) |> 
  layer_dense(grid_size * grid_size * (num_labels + 5)) |> 
  layer_reshape(c(grid_size, grid_size, num_labels + 5))  #3

box_predictions <- x@r[.., 1:5]  #4
class_predictions <- layer_activation_softmax(x@r[.., 6:NA]) 
outputs <- list(box = box_predictions, class = class_predictions)
model <- keras_model(inputs, outputs)

Attach a prediction head that reshapes the output into grid cells, boxes, and class probabilities. section 12.2.2

The backbone extracts image features; the prediction head turns them into a box and class probabilities for each grid location. Most locations contain no object, so their box confidence should be near zero. A class probability map identifies the object categories associated with image regions. section 12.2.2 section 12.4

To train the simplified detector:

  • Convert labeled boxes into grid targets. Mark intersecting cells with class labels, translate boxes into grid coordinates, and use confidence 1 for labeled boxes and 0 elsewhere. This simplified preparation does not handle overlapping boxes. section 12.2.3
  • Load and preprocess images in batches with tf.data, and reserve a validation set. Streaming avoids loading the whole image dataset into memory at once. section 12.2.3
  • Combine sparse categorical crossentropy for classes with a custom box loss. Train box coordinates only where labeled boxes exist; use zero confidence for empty cells and intersection over union (IoU) as the confidence target for occupied cells. section 12.2.4
  • Give box placement more weight, reduce the contribution of empty-cell confidence errors, and use square roots of box dimensions so large boxes do not dominate the loss. section 12.2.4
Listing 12.10 Defining the YOLO bounding box loss
signed_sqrt <- function(x) {
  op_sign(x) * op_sqrt(op_abs(x) + config_epsilon())
}

box_loss <- function(true, pred) {
  unpack <- \(x) list(x[.., 1:2], x[.., 3:4], x[.., 5:NA])  #1
  .[xy_true, wh_true, conf_true] <- unpack(true)  #1
  .[xy_pred, wh_pred, conf_pred] <- unpack(pred)  #1

  no_object <- conf_true == 0 #2

  xy_error <- op_square(xy_true - xy_pred)  #3
  wh_error <- op_square(signed_sqrt(wh_true) - signed_sqrt(wh_pred)) 

  iou <- intersection_over_union(true, pred)  #4
  conf_target <- op_where(no_object, 0, op_expand_dims(iou, -1))  #4
  conf_error <- op_square(conf_target - conf_pred)  #4

  error <- op_concatenate(axis = -1, list(  #5
    op_where(no_object, 0, xy_error  * 5),  #5
    op_where(no_object, 0, wh_error  * 5),  #5
    op_where(no_object, conf_error * 0.5, conf_error)  #5
  )) #5

  op_sum(error, axis = c(2, 3, 4))  #6
}

Inspect the custom loss, including the IoU confidence target and loss scaling. section 12.2.4

After training, draw predicted boxes and labels over a validation image. A confidence cutoff can suppress low-confidence boxes; drawing every prediction helps inspect what the detector outputs. section 12.2.4

How Deep Learning with R, Third Edition covers it

How deep it goes
Builds a simplified original YOLO detector through grid targets, a prediction head, custom loss, training, and visualization; omits multiple boxes per cell.
Examples
Uses COCO images and a 6 × 6 prediction grid to illustrate training targets and visualized detections.
What you can do after
Build it from scratch as a simplified detector using a pretrained backbone, grid-based targets, and a custom loss.
How it connects
Connects object detection with convolutional neural networks, ResNet, bounding boxes, class probabilities, and intersection over union.

Also explained in

Compare how 3 books explain YOLO →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with R, Third Edition. The section links point to the parts of the book it draws on.