Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/main/deep-learning-specialization/course-4-convolutional-neural-network/Autonomous_driving_application_Car_detection.ipynb
Views: 34199
Autonomous Driving - Car Detection
Welcome to the Week 3 programming assignment! In this notebook, you'll implement object detection using the very powerful YOLO model. Many of the ideas in this notebook are described in the two YOLO papers: Redmon et al., 2016 and Redmon and Farhadi, 2016.
By the end of this assignment, you'll be able to:
Detect objects in a car detection dataset
Implement non-max suppression to increase accuracy
Implement intersection over union
Handle bounding boxes, a type of image annotation popular in deep learning
Important Note on Submission to the AutoGrader
Before submitting your assignment to the AutoGrader, please make sure you are not doing the following:
You have not added any extra
print
statement(s) in the assignment.You have not added any extra code cell(s) in the assignment.
You have not changed any of the function parameters.
You are not using any global variables inside your graded exercises. Unless specifically instructed to do so, please refrain from it and use the local variables instead.
You are not changing the assignment code where it is not required, like creating extra variables.
If you do any of the following, you will get something like, Grader not found
(or similarly unexpected) error upon submitting your assignment. Before asking for help/debugging the errors in your assignment, check for these first. If this is the case, and you don't remember the changes you have made, you can get a fresh copy of the assignment by following these instructions.
Table of Contents
1 - Problem Statement
You are working on a self-driving car. Go you! As a critical component of this project, you'd like to first build a car detection system. To collect data, you've mounted a camera to the hood (meaning the front) of the car, which takes pictures of the road ahead every few seconds as you drive around.
Dataset provided by drive.ai.
You've gathered all these images into a folder and labelled them by drawing bounding boxes around every car you found. Here's an example of what your bounding boxes look like:
If there are 80 classes you want the object detector to recognize, you can represent the class label either as an integer from 1 to 80, or as an 80-dimensional vector (with 80 numbers) one component of which is 1, and the rest of which are 0. The video lectures used the latter representation; in this notebook, you'll use both representations, depending on which is more convenient for a particular step.
In this exercise, you'll discover how YOLO ("You Only Look Once") performs object detection, and then apply it to car detection. Because the YOLO model is very computationally expensive to train, the pre-trained weights are already loaded for you to use.
"You Only Look Once" (YOLO) is a popular algorithm because it achieves high accuracy while also being able to run in real time. This algorithm "only looks once" at the image in the sense that it requires only one forward propagation pass through the network to make predictions. After non-max suppression, it then outputs recognized objects together with the bounding boxes.
2.1 - Model Details
Inputs and outputs
The input is a batch of images, and each image has the shape (m, 608, 608, 3)
The output is a list of bounding boxes along with the recognized classes. Each bounding box is represented by 6 numbers as explained above. If you expand into an 80-dimensional vector, each bounding box is then represented by 85 numbers.
Anchor Boxes
Anchor boxes are chosen by exploring the training data to choose reasonable height/width ratios that represent the different classes. For this assignment, 5 anchor boxes were chosen for you (to cover the 80 classes), and stored in the file './model_data/yolo_anchors.txt'
The dimension of the encoding tensor of the second to last dimension based on the anchor boxes is .
The YOLO architecture is: IMAGE (m, 608, 608, 3) -> DEEP CNN -> ENCODING (m, 19, 19, 5, 85).
Encoding
Let's look in greater detail at what this encoding represents.
If the center/midpoint of an object falls into a grid cell, that grid cell is responsible for detecting that object.
Since you're using 5 anchor boxes, each of the 19 x19 cells thus encodes information about 5 boxes. Anchor boxes are defined only by their width and height.
For simplicity, you'll flatten the last two dimensions of the shape (19, 19, 5, 85) encoding, so the output of the Deep CNN is (19, 19, 425).
Class score
Now, for each box (of each cell) you'll compute the following element-wise product and extract a probability that the box contains a certain class. The class score is : the probability that there is an object times the probability that the object is a certain class .
Example of figure 4
In figure 4, let's say for box 1 (cell 1), the probability that an object exists is . So there's a 60% chance that an object exists in box 1 (cell 1).
The probability that the object is the class "category 3 (a car)" is .
The score for box 1 and for category "3" is .
Let's say you calculate the score for all 80 classes in box 1, and find that the score for the car class (class 3) is the maximum. So you'll assign the score 0.44 and class "3" to this box "1".
Visualizing classes
Here's one way to visualize what YOLO is predicting on an image:
For each of the 19x19 grid cells, find the maximum of the probability scores (taking a max across the 80 classes, one maximum for each of the 5 anchor boxes).
Color that grid cell according to what object that grid cell considers the most likely.
Doing this results in this picture:
Note that this visualization isn't a core part of the YOLO algorithm itself for making predictions; it's just a nice way of visualizing an intermediate result of the algorithm.
Visualizing bounding boxes
Another way to visualize YOLO's output is to plot the bounding boxes that it outputs. Doing that results in a visualization like this:
Non-Max suppression
In the figure above, the only boxes plotted are ones for which the model had assigned a high probability, but this is still too many boxes. You'd like to reduce the algorithm's output to a much smaller number of detected objects.
To do so, you'll use non-max suppression. Specifically, you'll carry out these steps:
Get rid of boxes with a low score. Meaning, the box is not very confident about detecting a class, either due to the low probability of any object, or low probability of this particular class.
Select only one box when several boxes overlap with each other and detect the same object.
2.2 - Filtering with a Threshold on Class Scores
You're going to first apply a filter by thresholding, meaning you'll get rid of any box for which the class "score" is less than a chosen threshold.
The model gives you a total of 19x19x5x85 numbers, with each box described by 85 numbers. It's convenient to rearrange the (19,19,5,85) (or (19,19,425)) dimensional tensor into the following variables:
box_confidence
: tensor of shape containing (confidence probability that there's some object) for each of the 5 boxes predicted in each of the 19x19 cells.boxes
: tensor of shape containing the midpoint and dimensions for each of the 5 boxes in each cell.box_class_probs
: tensor of shape containing the "class probabilities" for each of the 80 classes for each of the 5 boxes per cell.
Exercise 1 - yolo_filter_boxes
Implement yolo_filter_boxes()
.
Compute box scores by doing the elementwise product as described in Figure 4 (). The following code may help you choose the right operator:
This is an example of broadcasting (multiplying vectors of different sizes).
For each box, find:
the index of the class with the maximum box score
the corresponding box score
Useful References * tf.math.argmax * tf.math.reduce_max
Helpful Hints * For the
axis
parameter ofargmax
andreduce_max
, if you want to select the last axis, one way to do so is to setaxis=-1
. This is similar to Python array indexing, where you can select the last position of an array usingarrayname[-1]
. * Applyingreduce_max
normally collapses the axis for which the maximum is applied.keepdims=False
is the default option, and allows that dimension to be removed. You don't need to keep the last dimension after applying the maximum here.Create a mask by using a threshold. As a reminder:
([0.9, 0.3, 0.4, 0.5, 0.1] < 0.4)
returns:[False, True, False, False, True]
. The mask should beTrue
for the boxes you want to keep.Use TensorFlow to apply the mask to
box_class_scores
,boxes
andbox_classes
to filter out the boxes you don't want. You should be left with just the subset of boxes you want to keep.One more useful reference:
And one more helpful hint: 😃
For the
tf.boolean_mask
, you can keep the defaultaxis=None
.
scores[2] = 9.270486
boxes[2] = [ 4.6399336 3.2303846 4.431282 -2.202031 ]
classes[2] = 8
scores.shape = (1789,)
boxes.shape = (1789, 4)
classes.shape = (1789,)
All tests passed!
Expected Output:
scores[2] | 9.270486 |
boxes[2] | [ 4.6399336 3.2303846 4.431282 -2.202031 ] |
classes[2] | 8 |
scores.shape | (1789,) |
boxes.shape | (1789, 4) |
classes.shape | (1789,) |
Note In the test for yolo_filter_boxes
, you're using random numbers to test the function. In real data, the box_class_probs
would contain non-zero values between 0 and 1 for the probabilities. The box coordinates in boxes
would also be chosen so that lengths and heights are non-negative.
Non-max suppression uses the very important function called "Intersection over Union", or IoU.
Exercise 2 - iou
Implement iou()
Some hints:
This code uses the convention that (0,0) is the top-left corner of an image, (1,0) is the upper-right corner, and (1,1) is the lower-right corner. In other words, the (0,0) origin starts at the top left corner of the image. As x increases, you move to the right. As y increases, you move down.
For this exercise, a box is defined using its two corners: upper left and lower right , instead of using the midpoint, height and width. This makes it a bit easier to calculate the intersection.
To calculate the area of a rectangle, multiply its height by its width . Since is the top left and are the bottom right, these differences should be non-negative.
To find the intersection of the two boxes :
Feel free to draw some examples on paper to clarify this conceptually.
The top left corner of the intersection is found by comparing the top left corners of the two boxes and finding a vertex that has an x-coordinate that is closer to the right, and y-coordinate that is closer to the bottom.
The bottom right corner of the intersection is found by comparing the bottom right corners of the two boxes and finding a vertex whose x-coordinate is closer to the left, and the y-coordinate that is closer to the top.
The two boxes may have no intersection. You can detect this if the intersection coordinates you calculate end up being the top right and/or bottom left corners of an intersection box. Another way to think of this is if you calculate the height or width and find that at least one of these lengths is negative, then there is no intersection (intersection area is zero).
The two boxes may intersect at the edges or vertices, in which case the intersection area is still zero. This happens when either the height or width (or both) of the calculated intersection is zero.
Additional Hints
xi1
= maximum of the x1 coordinates of the two boxesyi1
= maximum of the y1 coordinates of the two boxesxi2
= minimum of the x2 coordinates of the two boxesyi2
= minimum of the y2 coordinates of the two boxesinter_area
= You can usemax(height, 0)
andmax(width, 0)
iou for intersecting boxes = 0.14285714285714285
iou for non-intersecting boxes = 0.0
iou for boxes that only touch at vertices = 0.0
iou for boxes that only touch at edges = 0.0
All tests passed!
Expected Output:
2.4 - YOLO Non-max Suppression
You are now ready to implement non-max suppression. The key steps are:
Select the box that has the highest score.
Compute the overlap of this box with all other boxes, and remove boxes that overlap significantly (iou >=
iou_threshold
).Go back to step 1 and iterate until there are no more boxes with a lower score than the currently selected box.
This will remove all boxes that have a large overlap with the selected boxes. Only the "best" boxes remain.
Exercise 3 - yolo_non_max_suppression
Implement yolo_non_max_suppression()
using TensorFlow. TensorFlow has two built-in functions that are used to implement non-max suppression (so you don't actually need to use your iou()
implementation):
Reference documentation:
Note that in the version of TensorFlow used here, there is no parameter score_threshold
(it's shown in the documentation for the latest version) so trying to set this value will result in an error message: got an unexpected keyword argument score_threshold
.
scores[2] = 8.147684
boxes[2] = [ 6.0797963 3.743308 1.3914018 -0.34089637]
classes[2] = 1.7079165
scores.shape = (10,)
boxes.shape = (10, 4)
classes.shape = (10,)
All tests passed!
Expected Output:
scores[2] | 8.147684 |
boxes[2] | [ 6.0797963 3.743308 1.3914018 -0.34089637] |
classes[2] | 1.7079165 |
scores.shape | (10,) |
boxes.shape | (10, 4) |
classes.shape | (10,) |
2.5 - Wrapping Up the Filtering
It's time to implement a function taking the output of the deep CNN (the 19x19x5x85 dimensional encoding) and filtering through all the boxes using the functions you've just implemented.
Exercise 4 - yolo_eval
Implement yolo_eval()
which takes the output of the YOLO encoding and filters the boxes using score threshold and NMS. There's just one last implementational detail you have to know. There're a few ways of representing boxes, such as via their corners or via their midpoint and height/width. YOLO converts between a few such formats at different times, using the following functions (which are provided):
which converts the yolo box coordinates (x,y,w,h) to box corners' coordinates (x1, y1, x2, y2) to fit the input of yolo_filter_boxes
YOLO's network was trained to run on 608x608 images. If you are testing this data on a different size image -- for example, the car detection dataset had 720x1280 images -- this step rescales the boxes so that they can be plotted on top of the original 720x1280 image.
Don't worry about these two functions; you'll see where they need to be called below.
scores[2] = 171.60194
boxes[2] = [-1240.3483 -3212.5881 -645.78 2024.3052]
classes[2] = 16
scores.shape = (10,)
boxes.shape = (10, 4)
classes.shape = (10,)
All tests passed!
Expected Output:
scores[2] | 171.60194 |
boxes[2] | [-1240.3483 -3212.5881 -645.78 2024.3052] |
classes[2] | 16 |
scores.shape | (10,) |
boxes.shape | (10, 4) |
classes.shape | (10,) |
3.1 - Defining Classes, Anchors and Image Shape
You're trying to detect 80 classes, and are using 5 anchor boxes. The information on the 80 classes and 5 boxes is gathered in two files: "coco_classes.txt" and "yolo_anchors.txt". You'll read class names and anchors from text files. The car detection dataset has 720x1280 images, which are pre-processed into 608x608 images.
3.2 - Loading a Pre-trained Model
Training a YOLO model takes a very long time and requires a fairly large dataset of labelled bounding boxes for a large range of target classes. You are going to load an existing pre-trained Keras YOLO model stored in "yolo.h5". These weights come from the official YOLO website, and were converted using a function written by Allan Zelener. References are at the end of this notebook. Technically, these are the parameters from the "YOLOv2" model, but are simply referred to as "YOLO" in this notebook.
Run the cell below to load the model from this file.
This loads the weights of a trained YOLO model. Here's a summary of the layers your model contains:
Note: On some computers, you may see a warning message from Keras. Don't worry about it if you do -- this is fine!
Reminder: This model converts a preprocessed batch of input images (shape: (m, 608, 608, 3)) into a tensor of shape (m, 19, 19, 5, 85) as explained in Figure (2).
3.3 - Convert Output of the Model to Usable Bounding Box Tensors
The output of yolo_model
is a (m, 19, 19, 5, 85) tensor that needs to pass through non-trivial processing and conversion. You will need to call yolo_head
to format the encoding of the model you got from yolo_model
into something decipherable:
yolo_model_outputs = yolo_model(image_data) yolo_outputs = yolo_head(yolo_model_outputs, anchors, len(class_names)) The variable yolo_outputs
will be defined as a set of 4 tensors that you can then use as input by your yolo_eval function. If you are curious about how yolo_head is implemented, you can find the function definition in the file keras_yolo.py
. The file is also located in your workspace in this path: yad2k/models/keras_yolo.py
.
3.5 - Run the YOLO on an Image
Let the fun begin! You will create a graph that can be summarized as follows:
yolo_model.input
is given to yolo_model
. The model is used to compute the output yolo_model.output
yolo_model.output
is processed by yolo_head
. It gives you yolo_outputs
yolo_outputs
goes through a filtering function, yolo_eval
. It outputs your predictions: out_scores
, out_boxes
, out_classes
.
Now, we have implemented for you the predict(image_file)
function, which runs the graph to test YOLO on an image to compute out_scores
, out_boxes
, out_classes
.
The code below also uses the following function:
which opens the image file and scales, reshapes and normalizes the image. It returns the outputs:
Run the following cell on the "test.jpg" image to verify that your function is correct.
Expected Output:
Found 10 boxes for images/test.jpg | |
car | 0.89 (367, 300) (745, 648) |
car | 0.80 (761, 282) (942, 412) |
car | 0.74 (159, 303) (346, 440) |
car | 0.70 (947, 324) (1280, 705) |
bus | 0.67 (5, 266) (220, 407) |
car | 0.66 (706, 279) (786, 350) |
car | 0.60 (925, 285) (1045, 374) |
car | 0.44 (336, 296) (378, 335) |
car | 0.37 (965, 273) (1022, 292) |
traffic light | 00.36 (681, 195) (692, 214) |
The model you've just run is actually able to detect 80 different classes listed in "coco_classes.txt". To test the model on your own images: 1. Click on "File" in the upper bar of this notebook, then click "Open" to go on your Coursera Hub. 2. Add your image to this Jupyter Notebook's directory, in the "images" folder 3. Write your image's name in the cell above code 4. Run the code and see the output of the algorithm!
If you were to run your session in a for loop over all your images. Here's what you would get:
Thanks to drive.ai for providing this dataset!
4 - Summary for YOLO
Input image (608, 608, 3)
The input image goes through a CNN, resulting in a (19,19,5,85) dimensional output.
After flattening the last two dimensions, the output is a volume of shape (19, 19, 425):
Each cell in a 19x19 grid over the input image gives 425 numbers.
425 = 5 x 85 because each cell contains predictions for 5 boxes, corresponding to 5 anchor boxes, as seen in lecture.
85 = 5 + 80 where 5 is because has 5 numbers, and 80 is the number of classes we'd like to detect
You then select only few boxes based on:
Score-thresholding: throw away boxes that have detected a class with a score less than the threshold
Non-max suppression: Compute the Intersection over Union and avoid selecting overlapping boxes
This gives you YOLO's final output.
What you should remember:
YOLO is a state-of-the-art object detection model that is fast and accurate
It runs an input image through a CNN, which outputs a 19x19x5x85 dimensional volume.
The encoding can be seen as a grid where each of the 19x19 cells contains information about 5 boxes.
You filter through all the boxes using non-max suppression. Specifically:
Score thresholding on the probability of detecting a class to keep only accurate (high probability) boxes
Intersection over Union (IoU) thresholding to eliminate overlapping boxes
Because training a YOLO model from randomly initialized weights is non-trivial and requires a large dataset as well as lot of computation, previously trained model parameters were used in this exercise. If you wish, you can also try fine-tuning the YOLO model with your own dataset, though this would be a fairly non-trivial exercise.
Congratulations! You've come to the end of this assignment.
Here's a quick recap of all you've accomplished.
You've:
Detected objects in a car detection dataset
Implemented non-max suppression to achieve better accuracy
Implemented intersection over union as a function of NMS
Created usable bounding box tensors from the model's predictions
Amazing work! If you'd like to know more about the origins of these ideas, spend some time on the papers referenced below.
5 - References
The ideas presented in this notebook came primarily from the two YOLO papers. The implementation here also took significant inspiration and used many components from Allan Zelener's GitHub repository. The pre-trained weights used in this exercise came from the official YOLO website.
Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi - You Only Look Once: Unified, Real-Time Object Detection (2015)
Joseph Redmon, Ali Farhadi - YOLO9000: Better, Faster, Stronger (2016)
Allan Zelener - YAD2K: Yet Another Darknet 2 Keras
The official YOLO website (https://pjreddie.com/darknet/yolo/)
Car detection dataset
The Drive.ai Sample Dataset (provided by drive.ai) is licensed under a Creative Commons Attribution 4.0 International License. Thanks to Brody Huval, Chih Hu and Rahul Patel for providing this data.