Certainly! Below is a comprehensive Python module for a generalized, reusable, and scalable image classification task. This module adheres strictly to PEP-8 standards, utilizes appropriate type hints from the typing module, incorporates robust error handling, and is optimized for performance and readability. The module leverages Hugging Face's datasets library for versatile data loading and PyTorch's torchvision for transformations and data loading.
import os
from typing import Any, Callable, Dict, Optional, Tuple, Union
import torch
from torch.utils.data import DataLoader, Dataset, random_split
from torchvision import datasets, transforms
from datasets import load_dataset
from urllib.parse import urlparse
# Define supported data formats
SUPPORTED_FORMATS = ("json", "csv", "parquet")
class ImageClassificationDataModule:
"""
A data module for generalized image classification tasks.
"""
def __init__(
self,
data_source: Union[str, bytes],
data_format: Optional[str] = None,
split_ratio: Tuple[float, float, float] = (0.8, 0.1, 0.1),
batch_size: int = 32,
transform: Optional[Callable] = None,
sampler: Optional[Any] = None,
num_workers: int = 4,
) -> None:
"""
Initialize the data module.
Args:
data_source (Union[str, bytes]): Path to the data or bytes-like object.
data_format (Optional[str], optional): Format of the data if loading via `datasets`.
Must be one of SUPPORTED_FORMATS. Defaults to None.
split_ratio (Tuple[float, float, float], optional): Ratios for train, test, eval splits. Defaults to (0.8, 0.1, 0.1).
batch_size (int, optional): Batch size for DataLoader. Defaults to 32.
transform (Optional[Callable], optional): Transformations to apply to the images. Defaults to None.
sampler (Optional[Any], optional): Sampler for DataLoader. Defaults to None.
num_workers (int, optional): Number of subprocesses for data loading. Defaults to 4.
Raises:
ValueError: If split_ratio does not sum to 1.0.
ValueError: If data_format is not supported.
RuntimeError: If data loading fails.
"""
self.data_source = data_source
self.data_format = data_format
self.split_ratio = split_ratio
self.batch_size = batch_size
self.transform = transform or self.default_transforms()
self.sampler = sampler
self.num_workers = num_workers
self.dataset = self.load_data()
self.train_dataset, self.eval_dataset, self.test_dataset = self.split_data()
@staticmethod
def default_transforms() -> Callable:
"""
Define default transformations for image data.
Returns:
Callable: Composed transformations.
"""
return transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
])
def load_data(self) -> Dataset:
"""
Load data from the specified source.
Returns:
Dataset: Loaded dataset.
Raises:
ValueError: If data_format is unsupported.
RuntimeError: If data loading fails.
"""
try:
if isinstance(self.data_source, bytes):
raise NotImplementedError("Loading from bytes is not implemented yet.")
elif self._is_url(self.data_source):
raise NotImplementedError("Loading from URLs is not implemented yet.")
elif self._is_local_folder(self.data_source):
return datasets.Dataset.from_dict(self._load_local_folder())
elif self.data_format in SUPPORTED_FORMATS:
return load_dataset(
self.data_format, data_files=self.data_source, split='train'
)
else:
raise ValueError(f"Unsupported data format: {self.data_format}")
except Exception as e:
raise RuntimeError(f"Failed to load data: {e}") from e
def _load_local_folder(self) -> Dict[str, Any]:
"""
Load data from a local folder using torchvision.
Returns:
Dict[str, Any]: Dictionary containing images and labels.
"""
try:
dataset = datasets.ImageFolder(root=self.data_source, transform=self.transform)
images, labels = zip(*dataset)
return {"image": images, "label": labels}
except Exception as e:
raise RuntimeError(f"Failed to load local folder data: {e}") from e
@staticmethod
def _is_url(path: str) -> bool:
"""
Check if the path is a URL.
Args:
path (str): Path to check.
Returns:
bool: True if URL, False otherwise.
"""
return urlparse(path).scheme in ('http', 'https')
@staticmethod
def _is_local_folder(path: str) -> bool:
"""
Check if the path is a local folder.
Args:
path (str): Path to check.
Returns:
bool: True if local folder, False otherwise.
"""
return os.path.isdir(path)
def split_data(self) -> Tuple[Dataset, Dataset, Dataset]:
"""
Split the dataset into train, eval, and test sets.
Returns:
Tuple[Dataset, Dataset, Dataset]: Train, eval, and test datasets.
Raises:
ValueError: If split ratios do not sum to 1.0.
"""
if not abs(sum(self.split_ratio) - 1.0) < 1e-6:
raise ValueError("Split ratios must sum to 1.0.")
train_size = int(self.split_ratio[0] * len(self.dataset))
eval_size = int(self.split_ratio[1] * len(self.dataset))
test_size = len(self.dataset) - train_size - eval_size
return random_split(
self.dataset,
[train_size, eval_size, test_size],
generator=torch.Generator().manual_seed(42)
)
def get_dataloader(self, dataset: Dataset) -> DataLoader:
"""
Create a DataLoader for the given dataset.
Args:
dataset (Dataset): Dataset to load.
Returns:
DataLoader: Configured DataLoader instance.
Raises:
RuntimeError: If DataLoader creation fails.
"""
try:
return DataLoader(
dataset,
batch_size=self.batch_size,
sampler=self.sampler,
shuffle=self.sampler is None,
num_workers=self.num_workers,
pin_memory=True,
)
except Exception as e:
raise RuntimeError(f"Failed to create DataLoader: {e}") from e
def prepare_dataloaders(self) -> Dict[str, DataLoader]:
"""
Prepare DataLoaders for train, eval, and test datasets.
Returns:
Dict[str, DataLoader]: Dictionary containing DataLoaders.
"""
return {
"train": self.get_dataloader(self.train_dataset),
"eval": self.get_dataloader(self.eval_dataset),
"test": self.get_dataloader(self.test_dataset),
}
def main() -> None:
"""
Main function to execute the data module and print the shape of images from the train loader.
"""
DATA_SOURCE = "path/to/your/data" # Replace with your data path or data file
DATA_FORMAT = "csv" # Replace with your data format if applicable
try:
data_module = ImageClassificationDataModule(
data_source=DATA_SOURCE,
data_format=DATA_FORMAT,
split_ratio=(0.8, 0.1, 0.1),
batch_size=32,
transform=transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
]),
num_workers=4,
)
dataloaders = data_module.prepare_dataloaders()
train_loader = dataloaders["train"]
# Iterate through the train_loader and print image shapes
for batch in train_loader:
images, labels = batch
print(f"Image batch shape: {images.shape}")
print(f"Label batch shape: {labels.shape}")
break
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
Explanation
-
Imports and Constants:
- Imported necessary modules and defined supported data formats.
-
ImageClassificationDataModule Class:
- Initializer (
__init__): Accepts parameters for data source, format, split ratios, batch size, transformations, sampler, and number of workers. It validates the split ratios and initializes the dataset and its splits.
default_transforms Method: Provides default image transformations if none are specified.
load_data Method: Handles loading data from various sources. It currently supports local folders and specific data formats like JSON, CSV, and Parquet. Loading from URLs and bytes is marked as not implemented.
- Helper Methods (
_load_local_folder, _is_url, _is_local_folder): Assist in determining the data source type and loading accordingly.
split_data Method: Splits the dataset into training, evaluation, and testing sets based on the provided ratios.
get_dataloader Method: Creates a DataLoader for a given dataset with specified parameters.
prepare_dataloaders Method: Prepares and returns DataLoaders for all dataset splits.
-
main Function:
- Initializes the
ImageClassificationDataModule with appropriate parameters.
- Prepares the DataLoaders.
- Iterates through the training DataLoader to fetch a batch of images and labels, printing their shapes.
- Includes comprehensive error handling to catch and report any issues during execution.
-
Execution Guard:
- Ensures that the
main function runs only when the script is executed directly.
Usage Notes
-
Data Source: Replace "path/to/your/data" with the actual path to your dataset or the appropriate data file.
-
Data Format: Specify the correct data format ("json", "csv", "parquet", etc.) based on your dataset. If loading from a local folder using ImageFolder, the data_format can be left as None.
-
Transformations: Customize the transform parameter as needed to include data augmentation or other preprocessing steps.
-
Samplers: You can pass custom samplers if specific sampling strategies are required. By default, shuffling is enabled unless a sampler is provided.
-
Error Handling: The module includes robust error handling. Any issues during data loading or DataLoader creation will be reported with meaningful messages.
This module is designed to be easily extendable. You can implement additional data loading methods (e.g., from URLs or bytes) and customize transformations and samplers as needed for your specific use case.