Bird
Raised Fist0
PyTorchml~20 mins

Custom detection dataset in PyTorch - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Custom Detection Dataset Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Custom Dataset __getitem__ method
Given the following PyTorch custom dataset code snippet, what is the output type of the __getitem__ method when called with an index?
PyTorch
from torch.utils.data import Dataset

class CustomDetectionDataset(Dataset):
    def __init__(self, images, annotations):
        self.images = images
        self.annotations = annotations

    def __len__(self):
        return len(self.images)

    def __getitem__(self, idx):
        image = self.images[idx]
        target = self.annotations[idx]
        return image, target
AA list containing image and target tensors
BOnly the image tensor at the given index
COnly the target dictionary at the given index
DA tuple containing (image, target) where image is a tensor and target is a dictionary
Attempts:
2 left
💡 Hint
Look at what the __getitem__ method returns explicitly.
❓ data_output
intermediate
1:30remaining
Number of items in Custom Detection Dataset
If a CustomDetectionDataset is initialized with a list of 150 images and a list of 150 corresponding annotations, what will be the output of len(dataset)?
PyTorch
dataset = CustomDetectionDataset(images=[...150 images...], annotations=[...150 annotations...])
print(len(dataset))
A150
B0
CDepends on the length of annotations only
DRaises a TypeError
Attempts:
2 left
💡 Hint
Check the __len__ method implementation.
🔧 Debug
advanced
2:30remaining
Fixing a KeyError in Custom Detection Dataset
Consider this code snippet inside a custom dataset __getitem__ method: image = self.images[idx] target = self.annotations[idx] boxes = target['boxes'] Sometimes, running this code raises a KeyError: 'boxes'. Which option fixes this error by ensuring 'boxes' key exists in target?
PyTorch
def __getitem__(self, idx):
    image = self.images[idx]
    target = self.annotations[idx]
    boxes = target['boxes']
    return image, target
AUse boxes = target.get('boxes', torch.empty((0,4))) to provide an empty tensor if 'boxes' is missing
BReplace boxes = target['boxes'] with boxes = target['box']
CRemove the line boxes = target['boxes'] entirely
DChange target = self.annotations[idx] to target = self.annotations.get(idx)
Attempts:
2 left
💡 Hint
Use a safe way to access dictionary keys that might be missing.
🚀 Application
advanced
3:00remaining
Transforming Images in Custom Detection Dataset
You want to apply a random horizontal flip to images and their bounding boxes in your custom detection dataset. Which approach correctly applies the transform inside __getitem__?
PyTorch
def __getitem__(self, idx):
    image = self.images[idx]
    target = self.annotations[idx]
    if random.random() > 0.5:
        # Apply horizontal flip to image and boxes
        image = image.flip(-1)
        boxes = target['boxes']
        width = image.shape[-1]
        boxes[:, [0, 2]] = width - boxes[:, [2, 0]]
        target['boxes'] = boxes
    return image, target
AThe boxes coordinates are not updated correctly after flip
BThe image.flip(-1) should be image.flip(0) to flip horizontally
CThis code correctly flips both image and bounding boxes horizontally
DThe target dictionary should not be modified inside __getitem__
Attempts:
2 left
💡 Hint
Check how image.flip and box coordinate updates correspond to horizontal flip.
🧠 Conceptual
expert
2:00remaining
Why use a custom detection dataset in PyTorch?
Which of the following is the best reason to create a custom detection dataset class in PyTorch instead of using a built-in dataset?
ATo automatically generate synthetic images
BTo handle unique image and annotation formats not supported by built-in datasets
CTo avoid using DataLoader for batching
DBecause built-in datasets are slower to load images
Attempts:
2 left
💡 Hint
Think about dataset flexibility and formats.

Practice

(1/5)
1. What is the main purpose of creating a Custom detection dataset in PyTorch?
easy
A. To perform image classification without labels
B. To convert images to grayscale only
C. To generate random images for testing
D. To load images and their bounding boxes with labels for training detection models

Solution

  1. Step 1: Understand dataset role in detection

    A detection dataset provides images along with bounding boxes and labels for each object to train detection models.
  2. Step 2: Identify correct purpose

    Classification without labels, random image generation, and grayscale conversion do not provide bounding boxes or labels needed for detection tasks.
  3. Final Answer:

    To load images and their bounding boxes with labels for training detection models -> Option D
  4. Quick Check:

    Detection dataset = images + bounding boxes + labels [OK]
Hint: Detection datasets always include bounding boxes and labels [OK]
Common Mistakes:
  • Thinking detection datasets only have images
  • Confusing detection with classification datasets
  • Ignoring bounding boxes in dataset
2. Which of the following is the correct way to define the __getitem__ method in a custom detection dataset class?
easy
A. def __getitem__(self): return image, label
B. def __getitem__(self, idx): return image, label
C. def __getitem__(self, idx): return image, bounding_boxes, labels
D. def getitem(self, idx): return image, bounding_boxes

Solution

  1. Step 1: Recall __getitem__ signature

    The method must accept an index parameter and return image, bounding boxes, and labels for detection.
  2. Step 2: Check options for correct syntax and return values

    def __getitem__(self, idx): return image, bounding_boxes, labels correctly uses def __getitem__(self, idx): and returns image, bounding boxes, and labels. Others miss parameters or return incomplete data.
  3. Final Answer:

    def __getitem__(self, idx): return image, bounding_boxes, labels -> Option C
  4. Quick Check:

    __getitem__ needs idx and returns image + boxes + labels [OK]
Hint: __getitem__ always takes index and returns image with boxes and labels [OK]
Common Mistakes:
  • Omitting the idx parameter
  • Returning only image and label without boxes
  • Using wrong method name without underscores
3. Given this snippet from a custom detection dataset, what will be the output type of dataset[0]?
class CustomDataset(torch.utils.data.Dataset):
    def __getitem__(self, idx):
        image = self.images[idx]
        boxes = self.boxes[idx]
        labels = self.labels[idx]
        target = {"boxes": boxes, "labels": labels}
        return image, target
medium
A. A tuple containing an image tensor and a dictionary with boxes and labels
B. A list containing image, boxes, and labels separately
C. Only the image tensor
D. A dictionary with keys 'image' and 'target'

Solution

  1. Step 1: Analyze return statement

    The method returns image, target where target is a dictionary with keys 'boxes' and 'labels'.
  2. Step 2: Determine output type

    Returning two items separated by comma means a tuple is returned: (image, target dictionary).
  3. Final Answer:

    A tuple containing an image tensor and a dictionary with boxes and labels -> Option A
  4. Quick Check:

    Return image, target dict = tuple [OK]
Hint: Comma-separated returns form a tuple in Python [OK]
Common Mistakes:
  • Thinking return is a list instead of tuple
  • Assuming only image is returned
  • Confusing dictionary keys with return structure
4. You wrote this __getitem__ method but get an error when loading data:
def __getitem__(self, idx):
    image = self.images[idx]
    boxes = self.boxes[idx]
    labels = self.labels[idx]
    target = {"boxes": boxes, "labels": labels}
    return image, target
What is the most likely cause of the error?
medium
A. Missing return statement
B. boxes and labels are not converted to tensors
C. image is not normalized
D. Incorrect method name without underscores

Solution

  1. Step 1: Check common dataset errors

    Detection models expect bounding boxes and labels as tensors, not raw lists or arrays.
  2. Step 2: Identify missing tensor conversion

    If boxes and labels are not converted to tensors, PyTorch will raise errors during training or data loading.
  3. Final Answer:

    boxes and labels are not converted to tensors -> Option B
  4. Quick Check:

    Boxes and labels must be tensors [OK]
Hint: Always convert boxes and labels to tensors before returning [OK]
Common Mistakes:
  • Forgetting to convert boxes and labels to torch tensors
  • Assuming image normalization fixes tensor errors
  • Using wrong method name causing attribute errors
5. You want to add a transform that flips images horizontally and adjusts bounding boxes accordingly in your custom detection dataset. Which approach is best?
hard
A. Apply the horizontal flip transform to both image and bounding boxes inside __getitem__
B. Flip bounding boxes but not the image
C. Apply the transform only after training the model
D. Apply the horizontal flip transform only to the image inside __getitem__, leave boxes unchanged

Solution

  1. Step 1: Understand transform requirements

    When flipping images, bounding boxes must be adjusted to match the new image layout.
  2. Step 2: Apply transform to both image and boxes

    Applying the transform only to the image or only to boxes causes mismatch and incorrect training data.
  3. Final Answer:

    Apply the horizontal flip transform to both image and bounding boxes inside __getitem__ -> Option A
  4. Quick Check:

    Flip image and boxes together for correct data [OK]
Hint: Transform image and boxes together to keep alignment [OK]
Common Mistakes:
  • Flipping only image or only boxes
  • Applying transforms after training
  • Ignoring bounding box coordinate updates
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