Datasets:
Upload mini_imagenet_c_loader.py (#2)
Browse files- Upload mini_imagenet_c_loader.py (ec2b6fc77e5ce9c3f5c90894468c8ff0465f6bde)
- mini_imagenet_c_loader.py +133 -0
mini_imagenet_c_loader.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import webdataset as wds
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import torch
|
| 5 |
+
from torchvision import transforms
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import io
|
| 8 |
+
|
| 9 |
+
def identity(x):
|
| 10 |
+
return x
|
| 11 |
+
|
| 12 |
+
def pil_decoder(key, data):
|
| 13 |
+
"""Decodes image data from bytes to a PIL Image."""
|
| 14 |
+
if not key.endswith((".jpg", ".jpeg", ".png")):
|
| 15 |
+
return None
|
| 16 |
+
try:
|
| 17 |
+
return Image.open(io.BytesIO(data)).convert("RGB")
|
| 18 |
+
except Exception:
|
| 19 |
+
return None
|
| 20 |
+
|
| 21 |
+
def cls_decoder(key, data):
|
| 22 |
+
"""Decodes class label from bytes."""
|
| 23 |
+
if not key.endswith(".cls"):
|
| 24 |
+
return None
|
| 25 |
+
try:
|
| 26 |
+
return int(data.decode('utf-8'))
|
| 27 |
+
except (ValueError, UnicodeDecodeError):
|
| 28 |
+
return None
|
| 29 |
+
|
| 30 |
+
class MiniImageNetCWebDataset(torch.utils.data.IterableDataset):
|
| 31 |
+
"""
|
| 32 |
+
A PyTorch Dataset for the WebDataset version of MiniImageNet-C.
|
| 33 |
+
|
| 34 |
+
Args:
|
| 35 |
+
root (str): The root directory of the WebDataset shards.
|
| 36 |
+
corruption (str): The corruption type to load (e.g., 'gaussian_noise').
|
| 37 |
+
severity (int): The severity level (should be 5 for MiniImageNet-C).
|
| 38 |
+
transform (callable, optional): A function/transform that takes in a PIL image
|
| 39 |
+
and returns a transformed version. E.g, `transforms.ToTensor()`.
|
| 40 |
+
target_transform (callable, optional): A function/transform that takes in the
|
| 41 |
+
target and transforms it.
|
| 42 |
+
"""
|
| 43 |
+
def __init__(self, root, corruption, severity=5, transform=None, target_transform=None):
|
| 44 |
+
self.root = Path(root)
|
| 45 |
+
self.corruption = corruption
|
| 46 |
+
self.severity = severity
|
| 47 |
+
self.transform = transform if transform is not None else identity
|
| 48 |
+
self.target_transform = target_transform if target_transform is not None else identity
|
| 49 |
+
|
| 50 |
+
self.shard_path = self.root / self.corruption / str(self.severity)
|
| 51 |
+
if not self.shard_path.exists():
|
| 52 |
+
raise FileNotFoundError(f"Shards not found at: {self.shard_path}")
|
| 53 |
+
|
| 54 |
+
shard_urls = [str(p) for p in sorted(self.shard_path.glob("*.tar"))]
|
| 55 |
+
if not shard_urls:
|
| 56 |
+
raise FileNotFoundError(f"No .tar shards found in {self.shard_path}")
|
| 57 |
+
|
| 58 |
+
self.dataset = (
|
| 59 |
+
wds.WebDataset(shard_urls, shardshuffle=True)
|
| 60 |
+
.decode(pil_decoder, cls_decoder)
|
| 61 |
+
.to_tuple("jpg", "cls")
|
| 62 |
+
.map(self.apply_transforms)
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def apply_transforms(self, sample):
|
| 66 |
+
image, target = sample
|
| 67 |
+
return self.transform(image), self.target_transform(target)
|
| 68 |
+
|
| 69 |
+
def __iter__(self):
|
| 70 |
+
return iter(self.dataset)
|
| 71 |
+
|
| 72 |
+
def __len__(self):
|
| 73 |
+
# The length of a WebDataset is not trivially known beforehand.
|
| 74 |
+
# You can estimate it or, if needed, iterate through it once to count.
|
| 75 |
+
# For Mini-ImageNet-C, each class has 50 images, and there are 1000 classes.
|
| 76 |
+
return 50 * 1000
|
| 77 |
+
|
| 78 |
+
# Example Usage
|
| 79 |
+
if __name__ == '__main__':
|
| 80 |
+
print("Example of how to use MiniImageNetCWebDataset")
|
| 81 |
+
|
| 82 |
+
# This assumes you have a 'mini-imagenet-c-webdataset' directory
|
| 83 |
+
# created by the convert_to_webdataset.py script.
|
| 84 |
+
dataset_root = "../data/mini-imagenet-c-webdataset"
|
| 85 |
+
if not Path(dataset_root).exists():
|
| 86 |
+
print(f"\nERROR: Example dataset root '{dataset_root}' not found.")
|
| 87 |
+
print("Please run 'python data/scripts/convert_to_webdataset.py' first.")
|
| 88 |
+
exit()
|
| 89 |
+
|
| 90 |
+
# Define transformations for the images
|
| 91 |
+
image_transform = transforms.Compose([
|
| 92 |
+
transforms.Resize((224, 224)),
|
| 93 |
+
transforms.ToTensor(),
|
| 94 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 95 |
+
])
|
| 96 |
+
|
| 97 |
+
# 1. Create a dataset for a specific corruption
|
| 98 |
+
try:
|
| 99 |
+
corruption_type = 'gaussian_noise'
|
| 100 |
+
print(f"\nLoading dataset for corruption: '{corruption_type}'")
|
| 101 |
+
|
| 102 |
+
dataset = MiniImageNetCWebDataset(
|
| 103 |
+
root=dataset_root,
|
| 104 |
+
corruption=corruption_type,
|
| 105 |
+
transform=image_transform
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# 2. Create a DataLoader
|
| 109 |
+
# WebDataset is designed for streaming, so shuffling is handled differently.
|
| 110 |
+
# For shuffling, you typically shuffle the shard URLs and the samples within each shard.
|
| 111 |
+
# The loader here provides a basic sequential stream.
|
| 112 |
+
dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, num_workers=4)
|
| 113 |
+
|
| 114 |
+
# 3. Iterate through a few batches
|
| 115 |
+
print("Iterating through a few batches...")
|
| 116 |
+
for i, (images, labels) in enumerate(dataloader):
|
| 117 |
+
if i >= 3:
|
| 118 |
+
break
|
| 119 |
+
print(f" Batch {i+1}:")
|
| 120 |
+
print(f" Images shape: {images.shape}")
|
| 121 |
+
print(f" Labels shape: {labels.shape}")
|
| 122 |
+
print(f" Sample labels: {labels[:4].tolist()}")
|
| 123 |
+
|
| 124 |
+
print("\nExample finished successfully!")
|
| 125 |
+
|
| 126 |
+
except FileNotFoundError as e:
|
| 127 |
+
print(f"\nERROR: Could not run example. {e}")
|
| 128 |
+
print("Please ensure the WebDataset has been generated and the paths are correct.")
|
| 129 |
+
|
| 130 |
+
except ImportError:
|
| 131 |
+
print("\nERROR: 'webdataset' library not found.")
|
| 132 |
+
print("Please install it by running: pip install webdataset")
|
| 133 |
+
|