When using image datasets loaded from folders, the key metrics depend on the task. For classification, accuracy is often used to see how many images are correctly labeled. However, if classes are imbalanced, precision and recall become important to understand how well the model finds each class. These metrics help check if the dataset loading and labeling from folders is correct and if the model learns well.
Image dataset from folders in PyTorch - Model Metrics & Evaluation
Predicted
Cat Dog
Actual Cat 45 5
Dog 3 47
TP (Cat) = 45, FP (Cat) = 3, FN (Cat) = 5, TN (Cat) = 47
Total samples = 100This matrix shows how many images were correctly or wrongly classified after loading from folders.
Precision tells us how many images predicted as a class are actually that class. Recall tells us how many images of a class were found by the model.
Example: If you have a folder with many dog images but few cat images, high recall for cats means the model finds most cat images. High precision means when the model says "cat," it is usually correct.
Depending on the use, you might want to optimize for one. For example, in a pet app, you want high precision to avoid wrong labels. In wildlife monitoring, high recall is important to not miss rare animals.
Good: Accuracy above 90%, precision and recall above 85% for all classes means the dataset from folders is well loaded and the model learns well.
Bad: Accuracy below 70%, or very low precision/recall for some classes means problems like mislabeled folders, unbalanced data, or model issues.
- Accuracy paradox: High accuracy can be misleading if one class dominates the dataset loaded from folders.
- Data leakage: If images from the same folder appear in both training and testing sets, metrics will be too optimistic.
- Overfitting indicators: Very high training accuracy but low test accuracy means the model memorizes folder images but does not generalize.
Your model trained on images loaded from folders has 98% accuracy but only 12% recall on a rare class. Is it good for production? Why or why not?
Answer: No, it is not good. The model misses most images of the rare class (low recall), which means it fails to detect important cases even though overall accuracy is high.
Practice
What does torchvision.datasets.ImageFolder do when loading images?
Solution
Step 1: Understand ImageFolder functionality
ImageFolder expects a root directory with subfolders. Each subfolder name is treated as a class label.Step 2: Confirm label assignment
Images inside each subfolder are assigned the label of that folder automatically.Final Answer:
Loads images from folders where each folder name is used as a class label -> Option DQuick Check:
ImageFolder uses folder names as labels [OK]
- Thinking ImageFolder loads images without labels
- Assuming ImageFolder splits data automatically
- Believing ImageFolder converts images to grayscale by default
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)Solution
Step 1: Identify correct transform order
Resize must come before ToTensor because ToTensor expects a PIL image or ndarray.Step 2: Check syntax correctness
transforms.Resize takes a tuple for width and height. transforms.ToTensor converts PIL image to tensor.Final Answer:
transforms.Resize((64, 64)), transforms.ToTensor() -> Option AQuick Check:
Resize then ToTensor is correct order [OK]
- Applying ToTensor before Resize
- Using Resize with a single integer without tuple
- Using ToPILImage instead of ToTensor
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))Solution
Step 1: Calculate number of batches
Dataset size is 100 images, batch size is 20, so number of batches = 100 / 20 = 5.Step 2: Confirm DataLoader length meaning
len(dataloader) returns number of batches per epoch, which is 5 here.Final Answer:
5 -> Option AQuick Check:
100 images / 20 batch size = 5 batches [OK]
- Confusing batch size with number of batches
- Assuming shuffle changes batch count
- Thinking len(dataloader) returns total images
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())Solution
Step 1: Check ImageFolder transform usage
ImageFolder passes PIL images to the transform function, so transforms.ToTensor() works fine alone.Step 2: Confirm no syntax or logic error
Using only ToTensor is valid; resizing is optional but not required.Final Answer:
No error; this code works correctly -> Option CQuick Check:
ImageFolder passes PIL images, ToTensor alone is valid [OK]
- Thinking ToTensor needs Resize always
- Believing ImageFolder needs image paths list
- Assuming ToTensor cannot handle PIL images
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?
Solution
Step 1: Understand data augmentation purpose
RandomHorizontalFlip is a data augmentation used only during training to improve generalization.Step 2: Apply transforms separately for train and validation
Training transform includes RandomHorizontalFlip; validation transform excludes it to keep data consistent.Final Answer:
Use transforms.RandomHorizontalFlip() in training transform only, and a separate transform without flip for validation -> Option BQuick Check:
Augment training only, keep validation unchanged [OK]
- Applying random flip in validation data
- Not separating train and validation transforms
- Placing RandomHorizontalFlip outside Compose
Ready to prove it?
Pass the test and this pattern moves unknown
