Bird
Raised Fist0

Implement IoU and Non-Max Suppression for Object Detection

CODINGintermediateInterview freq: high
Choose your preparation mode6 modes available
▶
Execution Trace
Step 1/4
Box A and Box B

Calculating IoU for Box A and Box B results in 0.5.

🎯 Understanding how IoU is calculated between two boxes.
def iou(box1, box2):
    x1 = max(box1[0], box2[0])
    y1 = max(box1[1], box2[1])
    x2 = min(box1[2], box2[2])
    y2 = min(box1[3], box2[3])
    inter_area = max(0, x2 - x1) * max(0, y2 - y1)
    box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
    box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
    union_area = box1_area + box2_area - inter_area
    return inter_area / union_area
Box A and Box C

Calculating IoU for Box A and Box C results in 0.3.

🎯 Recognizing how different box positions affect IoU.
iou_ac = iou(box_a, box_c)
print(f'IoU between A and C: {iou_ac}')
Non-Max Suppression

Box A is kept, Box B is discarded due to higher IoU with Box A.

🎯 Applying Non-Max Suppression to filter boxes.
def non_max_suppression(boxes, scores, threshold):
    indices = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)
    selected_boxes = []
    while indices:
        current = indices.pop(0)
        selected_boxes.append(boxes[current])
        indices = [i for i in indices if iou(boxes[current], boxes[i]) < threshold]
    return selected_boxes
Final Box Selection

Box A is selected as the final bounding box.

🎯 Finalizing the selection of boxes after suppression.
selected_boxes = non_max_suppression(boxes, scores, threshold)
print(f'Selected boxes: {selected_boxes}')
📊
Diagram
Diagram
┌───────────────────────────────────────────────────────────────┐
│ Initial Boxes:                                                │
│ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐         │
│ │ Box A         │ │ Box B         │ │ Box C         │         │
│ │ (x1, y1, x2, y2) │ │ (x1, y1, x2, y2) │ │ (x1, y1, x2, y2) │ │
│ └───────────────┘ └───────────────┘ └───────────────┘         │
│ IoU Calculation:                                              │
│ ┌───────────────┐ ┌───────────────┐                           │
│ │ IoU(A, B) = 0.5 │ │ IoU(A, C) = 0.3 │                        │
│ └───────────────┘ └───────────────┘                           │
│ Non-Max Suppression:                                          │
│ ┌───────────────┐ ┌───────────────┐                           │
│ │ Keep Box A    │ │ Discard Box B │                           │
│ └───────────────┘ └───────────────┘                           │
└───────────────────────────────────────────────────────────────┘
  • Initial Boxes: The starting set of bounding boxes.
  • IoU Calculation: Intersection over Union values between boxes.
  • Non-Max Suppression: Decision to keep or discard boxes based on IoU.
🔑
Key Moments
▲
Q: Why is IoU important in object detection?
A: IoU measures the overlap between predicted and ground truth boxes, crucial for evaluating detection accuracy.
Q: How does Non-Max Suppression improve detection results?
A: It reduces redundancy by keeping only the most relevant bounding boxes, improving precision.
Q: What happens if the IoU threshold is set too high?
A: A high threshold may discard too many boxes, potentially missing true positives.

This document explains the implementation of IoU and Non-Max Suppression in object detection. The ASCII diagram shows the initial bounding boxes, the IoU calculations between them, and the application of Non-Max Suppression to retain the most relevant boxes. The execution trace provides a step-by-step breakdown of the algorithm, highlighting key moments such as IoU calculation and box selection. Understanding these concepts is crucial for optimizing object detection models by ensuring accurate and efficient bounding box predictions.

Primary Focus

✓ Implementing IoU and Non-Max Suppression algorithms

Practice

(1/5)
1. What is the time complexity of applying Min-Max scaling to a dataset with n samples and m features?
easy
A. O(n * m)
B. O(m)
C. O(n^2)
D. O(n)

Solution

  1. Step 1: Understand Min-Max Scaling

    Min-Max scaling requires computing the min and max for each feature, which involves iterating over all samples for each feature.
  2. Step 2: Calculate Complexity

    For each of the m features, we iterate over n samples, resulting in O(n * m) complexity.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Min-Max scaling is O(n * m). [OK]
Hint: Min-Max scaling is O(n * m). [OK]
Common Mistakes:
2. What does the following Python code snippet output when implementing the K-Means clustering algorithm from scratch?
import numpy as np

# Sample data
X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])

# Initial centroids
centroids = np.array([[1, 2], [10, 2]])

# Calculate distances
for i in range(len(X)):
    distances = np.linalg.norm(X[i] - centroids, axis=1)
    print(distances)
easy
A. Prints the distances between each point and the second centroid only.
B. Prints the pairwise distances between each point and both centroids.
C. Prints the distances between each point and the first centroid only.
D. Prints the sum of distances for each point to both centroids.

Solution

  1. Step 1: Understand the code logic

    The code calculates the Euclidean distance from each data point to both centroids.
  2. Step 2: Eliminate wrong options

    Prints the distances between each point and the first centroid only. and C are incorrect because the code calculates distances to both centroids, not just one. Prints the sum of distances for each point to both centroids. is incorrect because it doesn't sum the distances.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Distances to all centroids, not just one. [OK]
Hint: Distances to all centroids, not just one. [OK]
Common Mistakes:
3.
import numpy as np
from scipy.spatial import distance

X_train = np.array([[1, 2], [3, 4], [5, 6]])
X_test = np.array([[1, 2]])

# Calculate distances
D = distance.cdist(X_test, X_train, 'euclidean')

print(D)
What does the above code output?
easy
A. array([[0., 2.828, 5.656]])
B. array([[0., 2., 4.]])
C. array([[0., 2.236, 4.472]])
D. array([[0., 2.828, 4.472]])

Solution

  1. Step 1: Understand the function

    The cdist function computes the distance between each pair of the two collections of inputs.
  2. Step 2: Calculate the distances

    The Euclidean distance from [1, 2] to each point in X_train is calculated as [0., 2.828, 4.472].
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Euclidean distance formula: √((x2-x1)² + (y2-y1)²) [OK]
Hint: Euclidean distance formula: √((x2-x1)² + (y2-y1)²) [OK]
Common Mistakes:
4. What does the following Python code snippet output when implementing a simple bagging technique for a Random Forest?
import numpy as np
from sklearn.utils import resample

X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])

# Bagging
bagged_X = resample(X, n_samples=3, replace=True, random_state=42)
print(bagged_X)
easy
A. An array with 3 samples, possibly with duplicates, from X
B. An array with 3 unique samples from X
C. An array with 4 samples, each appearing once
D. An array with 2 samples, each appearing twice

Solution

  1. Step 1: Understand Bagging with Replacement

    Bagging involves sampling with replacement, meaning samples can be repeated.
  2. Step 2: Analyze Code Output

    The code uses resample with replace=True, so duplicates are possible.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Bagging allows duplicates [OK]
Hint: Bagging allows duplicates [OK]
Common Mistakes:
5. In a dataset with highly imbalanced classes, which cross-validation technique is most appropriate?
medium
A. Stratified K-Fold
B. Standard K-Fold
C. Leave-One-Out
D. ShuffleSplit

Solution

  1. Step 1: Consider class imbalance

    Stratified K-Fold ensures each fold has the same class distribution as the entire dataset.
  2. Step 2: Eliminate wrong options

    Standard K-Fold and D do not preserve class distribution. Leave-One-Out is inefficient for large datasets.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Use Stratified K-Fold for class balance. [OK]
Hint: Use Stratified K-Fold for class balance. [OK]
Common Mistakes:
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard