Bird
Raised Fist0

Implement Mean Average Precision (mAP) for Object Detection

CODINGadvancedInterview freq: medium
Choose your preparation mode6 modes available
▶
Execution Trace
Step 1/5
IoU Calculation

IoU for Box A and Box 1 is 0.75, indicating a good overlap.

🎯 Understanding IoU is crucial for evaluating detection accuracy.
def calculate_iou(box1, box2):
    x_left = max(box1[0], box2[0])
    y_top = max(box1[1], box2[1])
    x_right = min(box1[2], box2[2])
    y_bottom = min(box1[3], box2[3])
    if x_right < x_left or y_bottom < y_top:
        return 0.0
    intersection_area = (x_right - x_left) * (y_bottom - y_top)
    box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1])
    box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1])
    iou = intersection_area / float(box1_area + box2_area - intersection_area)
    return iou
Precision Calculation

Precision is 0.8 after evaluating the first set of predictions.

🎯 Precision measures the accuracy of positive predictions.
def calculate_precision(tp, fp):
    if tp + fp == 0:
        return 0.0
    return tp / (tp + fp)
Recall Calculation

Recall is 0.67, indicating the proportion of actual positives captured.

🎯 Recall is key for understanding model sensitivity.
def calculate_recall(tp, fn):
    if tp + fn == 0:
        return 0.0
    return tp / (tp + fn)
Precision-Recall Curve

The curve shows a drop in precision as recall increases.

🎯 The trade-off between precision and recall is visualized here.
import matplotlib.pyplot as plt
def plot_precision_recall_curve(precisions, recalls):
    plt.figure()
    plt.plot(recalls, precisions, marker='.')
    plt.xlabel('Recall')
    plt.ylabel('Precision')
    plt.title('Precision-Recall Curve')
    plt.show()
mAP Calculation

mAP is calculated as 0.72, summarizing the model's performance.

🎯 mAP provides a single metric for model evaluation.
def calculate_map(precision_recall_curve):
    return np.mean(precision_recall_curve)
📊
Diagram
Diagram
┌──────────────────────────────────────────────────────────────┐
│  Ground Truth Boxes                                          │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐        │
│  │  Box 1       │  │  Box 2       │  │  Box 3       │        │
│  └──────────────┘  └──────────────┘  └──────────────┘        │
│                                                              │
│  Predicted Boxes                                             │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐        │
│  │  Box A       │  │  Box B       │  │  Box C       │        │
│  └──────────────┘  └──────────────┘  └──────────────┘        │
│                                                              │
│  IoU Calculation                                             │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐        │
│  │  IoU 1       │  │  IoU 2       │  │  IoU 3       │        │
│  └──────────────┘  └──────────────┘  └──────────────┘        │
│                                                              │
│  Precision-Recall Curve                                      │
│  ┌────────────────────────────────────────────────────────┐  │
│  │                                                        │  │
│  │                                                        │  │
│  └────────────────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────────────┘
  • Ground Truth Boxes: Actual object locations
  • Predicted Boxes: Model's predicted locations
  • IoU Calculation: Intersection over Union for each box pair
  • Precision-Recall Curve: Evaluates model performance
  • mAP Calculation: Area under the precision-recall curve
🔑
Key Moments
▲
Q: Why is IoU important in object detection?
A: IoU measures the overlap between predicted and ground truth boxes, crucial for determining detection accuracy.
Q: What does the precision-recall curve illustrate?
A: It shows the trade-off between precision and recall, helping to evaluate model performance across different thresholds.
Q: How does mAP summarize model performance?
A: mAP averages precision across recall levels, providing a single metric to assess overall detection quality.

This diagram and trace explain the implementation of Mean Average Precision (mAP) for object detection. It covers the calculation of Intersection over Union (IoU) for evaluating overlaps between predicted and ground truth boxes, and the derivation of precision and recall metrics. The precision-recall curve is plotted to visualize the trade-off between these metrics. Finally, mAP is calculated as the area under this curve, providing a comprehensive measure of the model's detection performance.

Primary Focus

✓ Implementing mAP for object detection

Practice

(1/5)
1.
import numpy as np

def cosine_similarity(a, b):
    dot_product = np.dot(a, b)
    norm_a = np.linalg.norm(a)
    norm_b = np.linalg.norm(b)
    return dot_product / (norm_a * norm_b)

vector1 = np.array([1, 2, 3])
vector2 = np.array([4, 5, 6])

result = cosine_similarity(vector1, vector2)
print(result)
easy
A. 0.9746318461970762
B. 0.9999999999999998
C. 1.0
D. 0.0

Solution

  1. Step 1: Calculate dot product and norms

    Dot product = 32, norm_a = 3.7416573867739413, norm_b = 8.774964387392123.
  2. Step 2: Compute cosine similarity

    Cosine similarity = 32 / (3.7416573867739413 * 8.774964387392123) = 0.9746318461970762.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Dot product over product of norms. [OK]
Hint: Dot product over product of norms. [OK]
Common Mistakes:
2. What is the time complexity of computing the forward pass for a single layer in a neural network using NumPy?
easy
A. O(n^2)
B. O(n)
C. O(n log n)
D. O(1)

Solution

  1. Step 1: Identify operations

    Forward pass involves matrix-vector multiplication.
  2. Step 2: Determine complexity

    Matrix-vector multiplication is O(n) where n is the number of neurons.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Matrix-vector multiplication is O(n) [OK]
Hint: Matrix-vector multiplication is O(n) [OK]
Common Mistakes:
3. What is the time complexity of updating the embeddings for a single word pair in the Skip-Gram model with negative sampling?
easy
A. O(k)
B. O(vocab_size)
C. O(n)
D. O(1)

Solution

  1. Step 1: Identify the operations involved

    Updating embeddings involves computing gradients and updating weights for the target word and k negative samples.
  2. Step 2: Determine the complexity

    Each update involves a constant number of operations per sample, leading to O(k) complexity where k is the number of negative samples.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Complexity is O(k) due to k negative samples [OK]
Hint: Complexity is O(k) due to k negative samples [OK]
Common Mistakes:
4. You implemented PCA but the variance explained by the first principal component is unexpectedly low. What is the most likely cause?
medium
A. Data was not centered before computing the covariance matrix.
B. Eigenvectors were not normalized.
C. Covariance matrix was computed using rowvar=True.
D. Too few principal components were selected.

Solution

  1. Step 1: Identify the impact of centering data

    Centering data is crucial for PCA as it ensures the covariance matrix reflects true variance.
  2. Step 2: Eliminate wrong options

    Eigenvectors were not normalized. is incorrect because normalization affects direction, not variance. Covariance matrix was computed using rowvar=True. affects orientation, not variance. Too few principal components were selected. is irrelevant to the variance of the first component.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Center data before PCA to capture variance. [OK]
Hint: Center data before PCA to capture variance. [OK]
Common Mistakes:
5. How can you optimize the implementation of linear regression using gradient descent for large datasets?
hard
A. Use a single feature at a time.
B. Use a smaller learning rate.
C. Increase the number of iterations.
D. Implement mini-batch gradient descent.

Solution

  1. Step 1: Identify scalability issues

    Full-batch gradient descent is computationally expensive for large datasets.
  2. Step 2: Choose an optimization strategy

    Mini-batch gradient descent reduces computation per iteration and can converge faster.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Mini-batch reduces computation, speeds convergence. [OK]
Hint: Mini-batch reduces computation, speeds convergence. [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