Bird
Raised Fist0
PyTorchml~20 mins

Image dataset from folders in PyTorch - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Image Dataset Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of loading images with ImageFolder
What will be the output shape of the first image tensor loaded using torchvision.datasets.ImageFolder with default ToTensor transform?
PyTorch
from torchvision import datasets, transforms
transform = transforms.ToTensor()
dataset = datasets.ImageFolder(root='data/train', transform=transform)
image, label = dataset[0]
print(image.shape)
Atorch.Size([H, W]) where H and W are image height and width
Btorch.Size([H, W, 3]) where H and W are image height and width
Ctorch.Size([1, H, W]) where H and W are image height and width
Dtorch.Size([3, H, W]) where H and W are image height and width
Attempts:
2 left
๐Ÿ’ก Hint
Remember that ToTensor converts images to CxHxW format.
โ“ data_output
intermediate
2:00remaining
Number of classes in ImageFolder dataset
Given an ImageFolder dataset loaded from a folder with subfolders 'cats', 'dogs', and 'rabbits', what is the value of dataset.classes?
PyTorch
from torchvision import datasets
 dataset = datasets.ImageFolder(root='data/train')
print(dataset.classes)
A['rabbits', 'dogs', 'cats']
B['dogs', 'cats', 'rabbits']
C['cats', 'dogs', 'rabbits']
D['cats', 'rabbits', 'dogs']
Attempts:
2 left
๐Ÿ’ก Hint
ImageFolder sorts folder names alphabetically to assign classes.
๐Ÿ”ง Debug
advanced
2:00remaining
Identify error loading images with ImageFolder
What error will occur when running this code if the root folder contains a file that is not an image or folder? from torchvision import datasets dataset = datasets.ImageFolder(root='data/train') image, label = dataset[0]
PyTorch
from torchvision import datasets
dataset = datasets.ImageFolder(root='data/train')
image, label = dataset[0]
APIL.UnidentifiedImageError
BIndexError
CFileNotFoundError
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
ImageFolder tries to open all files as images.
๐Ÿš€ Application
advanced
2:00remaining
Transform pipeline for ImageFolder dataset
Which transform pipeline correctly resizes images to 128x128, converts to tensor, and normalizes with mean=0.5 and std=0.5 for all channels?
Atransforms.Compose([transforms.ToTensor(), transforms.Resize((128,128)), transforms.Normalize((0.5,), (0.5,))])
Btransforms.Compose([transforms.Resize((128,128)), transforms.ToTensor(), transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))])
Ctransforms.Compose([transforms.Resize(128), transforms.ToTensor(), transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5))])
Dtransforms.Compose([transforms.Resize((128,128)), transforms.Normalize((0.5,0.5,0.5), (0.5,0.5,0.5)), transforms.ToTensor()])
Attempts:
2 left
๐Ÿ’ก Hint
Resize should come before ToTensor, and Normalize after ToTensor.
๐Ÿง  Conceptual
expert
2:00remaining
Why use ImageFolder for image datasets?
What is the main advantage of using torchvision.datasets.ImageFolder to load image datasets organized in folders?
AIt automatically assigns labels based on folder names and loads images efficiently.
BIt converts images to grayscale automatically.
CIt only works with PNG images.
DIt requires images to be in a single folder without subfolders.
Attempts:
2 left
๐Ÿ’ก Hint
Think about how labels are assigned in ImageFolder.

Practice

(1/5)
1.

What does torchvision.datasets.ImageFolder do when loading images?

easy
A. Loads images and converts them to grayscale only
B. Loads images from a single folder without labels
C. Loads images and automatically splits them into training and testing sets
D. Loads images from folders where each folder name is used as a class label

Solution

  1. Step 1: Understand ImageFolder functionality

    ImageFolder expects a root directory with subfolders. Each subfolder name is treated as a class label.
  2. Step 2: Confirm label assignment

    Images inside each subfolder are assigned the label of that folder automatically.
  3. Final Answer:

    Loads images from folders where each folder name is used as a class label -> Option D
  4. Quick Check:

    ImageFolder uses folder names as labels [OK]
Hint: Remember: folder names become labels in ImageFolder [OK]
Common Mistakes:
  • Thinking ImageFolder loads images without labels
  • Assuming ImageFolder splits data automatically
  • Believing ImageFolder converts images to grayscale by default
2.

Which of the following is the correct way to apply a transform that resizes images to 64x64 and converts them to tensors when using ImageFolder?

transform = transforms.Compose([
    ?
])
dataset = ImageFolder(root='data/train', transform=transform)
easy
A. transforms.Resize((64, 64)), transforms.ToTensor()
B. transforms.ToTensor(), transforms.Resize(64)
C. transforms.Resize(64), transforms.ToTensor()
D. transforms.ToPILImage(), transforms.Resize((64, 64))

Solution

  1. Step 1: Identify correct transform order

    Resize must come before ToTensor because ToTensor expects a PIL image or ndarray.
  2. Step 2: Check syntax correctness

    transforms.Resize takes a tuple for width and height. transforms.ToTensor converts PIL image to tensor.
  3. Final Answer:

    transforms.Resize((64, 64)), transforms.ToTensor() -> Option A
  4. Quick Check:

    Resize then ToTensor is correct order [OK]
Hint: Resize first, then convert to tensor [OK]
Common Mistakes:
  • Applying ToTensor before Resize
  • Using Resize with a single integer without tuple
  • Using ToPILImage instead of ToTensor
3.

Given the following code, what will len(dataloader) print if the dataset has 100 images and batch_size=20?

from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader
from torchvision import transforms

transform = transforms.Compose([
    transforms.Resize((32, 32)),
    transforms.ToTensor()
])
dataset = ImageFolder(root='data/train', transform=transform)
dataloader = DataLoader(dataset, batch_size=20, shuffle=True)

print(len(dataloader))
medium
A. 5
B. 20
C. 100
D. 1

Solution

  1. Step 1: Calculate number of batches

    Dataset size is 100 images, batch size is 20, so number of batches = 100 / 20 = 5.
  2. Step 2: Confirm DataLoader length meaning

    len(dataloader) returns number of batches per epoch, which is 5 here.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    100 images / 20 batch size = 5 batches [OK]
Hint: len(dataloader) = total images รท batch size [OK]
Common Mistakes:
  • Confusing batch size with number of batches
  • Assuming shuffle changes batch count
  • Thinking len(dataloader) returns total images
4.

What is wrong with this code snippet for loading an image dataset?

from torchvision.datasets import ImageFolder
from torchvision import transforms

dataset = ImageFolder(root='data/train', transform=transforms.ToTensor())
medium
A. transforms.ToTensor() cannot be used alone without resizing or other transforms
B. transforms.ToTensor() expects a PIL image, but ImageFolder provides file paths
C. No error; this code works correctly
D. ImageFolder requires a list of image paths, not a root folder

Solution

  1. Step 1: Check ImageFolder transform usage

    ImageFolder passes PIL images to the transform function, so transforms.ToTensor() works fine alone.
  2. Step 2: Confirm no syntax or logic error

    Using only ToTensor is valid; resizing is optional but not required.
  3. Final Answer:

    No error; this code works correctly -> Option C
  4. Quick Check:

    ImageFolder passes PIL images, ToTensor alone is valid [OK]
Hint: ImageFolder sends PIL images, ToTensor alone is valid [OK]
Common Mistakes:
  • Thinking ToTensor needs Resize always
  • Believing ImageFolder needs image paths list
  • Assuming ToTensor cannot handle PIL images
5.

You want to load images from folders and apply a transform that randomly flips images horizontally during training but not during validation. How can you set up ImageFolder and transforms for this?

hard
A. Use transforms.RandomHorizontalFlip() in both training and validation transforms
B. Use transforms.RandomHorizontalFlip() in training transform only, and a separate transform without flip for validation
C. Use transforms.RandomHorizontalFlip() only in validation transform
D. Use transforms.RandomHorizontalFlip() outside of transforms.Compose

Solution

  1. Step 1: Understand data augmentation purpose

    RandomHorizontalFlip is a data augmentation used only during training to improve generalization.
  2. Step 2: Apply transforms separately for train and validation

    Training transform includes RandomHorizontalFlip; validation transform excludes it to keep data consistent.
  3. Final Answer:

    Use transforms.RandomHorizontalFlip() in training transform only, and a separate transform without flip for validation -> Option B
  4. Quick Check:

    Augment training only, keep validation unchanged [OK]
Hint: Apply random flip only in training transforms [OK]
Common Mistakes:
  • Applying random flip in validation data
  • Not separating train and validation transforms
  • Placing RandomHorizontalFlip outside Compose
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