To create a generalized, robust, and scalable data loader pipeline using the datasets library, we'll develop a DataLoader class. This class will handle loading datasets either by name or from a local path, support various data formats, and provide flexibility for further data manipulation. The implementation adheres to PEP-8 standards, includes type hints, and incorporates comprehensive error handling to ensure robustness and scalability.
Key Features of the DataLoader Class:
- Flexible Dataset Loading: Accepts either a dataset name from the
datasets library or a local file path (CSV, JSON).
- Comprehensive Error Handling: Catches and handles exceptions gracefully, providing meaningful error messages.
- Type Hints and Documentation: Enhances code clarity and maintainability.
- Scalability: Designed to handle large datasets efficiently with options for batch and parallel processing.
- Utility Methods: Includes methods for data transformation, splitting, and saving/loading datasets.
Code Implementation
import sys
from typing import Union, Dict, Any, Optional
from datasets import (
load_dataset,
Dataset,
DatasetDict,
concatenate_datasets,
split_dataset,
)
from datasets import Features, Value, ClassLabel, Sequence
import pandas as pd
import json
import os
class DataLoader:
"""
A generalized, robust, and scalable data loader pipeline using the `datasets` library.
Attributes:
dataset (Union[Dataset, DatasetDict]): The loaded dataset.
"""
def __init__(self, dataset_identifier: str, cache_dir: Optional[str] = None) -> None:
"""
Initializes the DataLoader with the dataset identifier (name or path).
Args:
dataset_identifier (str): The name of the dataset from the `datasets` library or the path to a local dataset file.
cache_dir (Optional[str]): Path to cache directory. Defaults to None.
Raises:
ValueError: If the dataset_identifier is invalid or loading fails.
"""
self.dataset: Union[Dataset, DatasetDict]
try:
if cache_dir:
self.dataset = load_dataset(dataset_identifier, cache_dir=cache_dir)
else:
self.dataset = load_dataset(dataset_identifier)
except Exception as e:
raise ValueError(
f"Failed to load dataset '{dataset_identifier}'. Error: {e}"
) from e
@classmethod
def from_path(
cls,
file_path: str,
file_type: str,
cache_dir: Optional[str] = None,
**kwargs: Any
) -> "DataLoader":
"""
Alternative constructor to load dataset from a local file path.
Args:
file_path (str): Path to the dataset file.
file_type (str): Type of the file ('csv', 'json', etc.).
cache_dir (Optional[str]): Path to cache directory. Defaults to None.
**kwargs: Additional arguments for `load_dataset`.
Returns:
DataLoader: An instance of DataLoader with the loaded dataset.
Raises:
ValueError: If the file type is unsupported or loading fails.
"""
supported_formats = {'csv', 'json', 'parquet', 'txt'}
if file_type.lower() not in supported_formats:
raise ValueError(
f"Unsupported file type '{file_type}'. Supported types are: {supported_formats}"
)
try:
dataset = load_dataset(file_type, data_files=file_path, cache_dir=cache_dir, **kwargs)
instance = cls.__new__(cls)
instance.dataset = dataset
return instance
except Exception as e:
raise ValueError(
f"Failed to load dataset from '{file_path}'. Error: {e}"
) from e
def get_features(self) -> Dict[str, Any]:
"""
Retrieves the features of the dataset.
Returns:
Dict[str, Any]: A dictionary of feature names and their types.
"""
return self.dataset.features
def get_shape(self) -> Dict[str, int]:
"""
Retrieves the shape (number of examples) of the dataset.
Returns:
Dict[str, int]: A dictionary with dataset split names and their sizes.
"""
if isinstance(self.dataset, DatasetDict):
return {split: len(data) for split, data in self.dataset.items()}
return {"default": len(self.dataset)}
def map(
self,
function: Any,
batched: bool = False,
batch_size: Optional[int] = None,
num_proc: Optional[int] = None,
**kwargs: Any
) -> None:
"""
Applies a function to all elements in the dataset.
Args:
function (Callable): The function to apply.
batched (bool): Whether to apply the function in batches. Defaults to False.
batch_size (Optional[int]): Batch size for batched mapping. Defaults to None.
num_proc (Optional[int]): Number of processes for parallel mapping. Defaults to None.
**kwargs: Additional arguments for `map`.
"""
try:
self.dataset = self.dataset.map(
function,
batched=batched,
batch_size=batch_size,
num_proc=num_proc,
**kwargs
)
except Exception as e:
raise RuntimeError(f"Failed to apply map function. Error: {e}") from e
def filter(self, condition: Any, **kwargs: Any) -> None:
"""
Filters the dataset based on a condition.
Args:
condition (Callable): A function that returns True for examples to keep.
**kwargs: Additional arguments for `filter`.
"""
try:
self.dataset = self.dataset.filter(condition, **kwargs)
except Exception as e:
raise RuntimeError(f"Failed to filter dataset. Error: {e}") from e
def save(self, save_path: str) -> None:
"""
Saves the dataset to the specified path.
Args:
save_path (str): Path where the dataset will be saved.
"""
try:
self.dataset.save_to_disk(save_path)
except Exception as e:
raise RuntimeError(f"Failed to save dataset to '{save_path}'. Error: {e}") from e
@classmethod
def load_from_disk(cls, load_path: str) -> "DataLoader":
"""
Loads a dataset from the specified disk path.
Args:
load_path (str): Path where the dataset is saved.
Returns:
DataLoader: An instance of DataLoader with the loaded dataset.
Raises:
ValueError: If loading fails.
"""
try:
dataset = load_dataset("json", data_files=load_path) # Adjust format as needed
instance = cls.__new__(cls)
instance.dataset = dataset
return instance
except Exception as e:
raise ValueError(
f"Failed to load dataset from disk '{load_path}'. Error: {e}"
) from e
def get_sample(self, index: int) -> Dict[str, Any]:
"""
Retrieves a single example from the dataset.
Args:
index (int): The index of the example to retrieve.
Returns:
Dict[str, Any]: The dataset example.
Raises:
IndexError: If the index is out of bounds.
"""
try:
return self.dataset[index]
except IndexError as e:
raise IndexError(f"Index {index} is out of bounds. Error: {e}") from e
except Exception as e:
raise RuntimeError(f"Failed to retrieve sample at index {index}. Error: {e}") from e
def to_pandas(self) -> pd.DataFrame:
"""
Converts the dataset to a pandas DataFrame.
Returns:
pd.DataFrame: The dataset as a DataFrame.
Raises:
RuntimeError: If conversion fails.
"""
try:
return self.dataset.to_pandas()
except Exception as e:
raise RuntimeError(f"Failed to convert dataset to pandas DataFrame. Error: {e}") from e
def shuffle(self, seed: Optional[int] = None) -> None:
"""
Shuffles the dataset.
Args:
seed (Optional[int]): Seed for reproducibility. Defaults to None.
"""
try:
self.dataset = self.dataset.shuffle(seed=seed)
except Exception as e:
raise RuntimeError(f"Failed to shuffle dataset. Error: {e}") from e
def split(self, test_size: float = 0.2, **kwargs: Any) -> Dict[str, "DataLoader"]:
"""
Splits the dataset into training and testing sets.
Args:
test_size (float): Proportion of the dataset to include in the test split.
**kwargs: Additional arguments for `train_test_split`.
Returns:
Dict[str, DataLoader]: A dictionary with 'train' and 'test' DataLoader instances.
"""
try:
split = self.dataset.train_test_split(test_size=test_size, **kwargs)
return {
"train": self.__class__.__new__(self.__class__),
"test": self.__class__.__new__(self.__class__),
}.update({
"train": DataLoader.__new__(DataLoader),
"test": DataLoader.__new__(DataLoader),
}).__dict__.update({
"train": DataLoader.__new__(DataLoader),
"test": DataLoader.__new__(DataLoader),
}) or {
"train": DataLoader.__new__(DataLoader).setter('dataset', split['train']),
"test": DataLoader.__new__(DataLoader).setter('dataset', split['test']),
}
except Exception as e:
raise RuntimeError(f"Failed to split dataset. Error: {e}") from e
def concatenate(self, other: "DataLoader") -> None:
"""
Concatenates another DataLoader's dataset to this dataset.
Args:
other (DataLoader): Another DataLoader instance to concatenate.
Raises:
TypeError: If datasets are not compatible for concatenation.
RuntimeError: If concatenation fails.
"""
try:
if isinstance(self.dataset, DatasetDict) or isinstance(other.dataset, DatasetDict):
raise TypeError("Concatenation of DatasetDict objects is not supported.")
self.dataset = concatenate_datasets([self.dataset, other.dataset])
except Exception as e:
raise RuntimeError(f"Failed to concatenate datasets. Error: {e}") from e
def cleanup_cache(self) -> None:
"""
Cleans up the cache files of the dataset.
"""
try:
self.dataset.cleanup_cache_files()
except Exception as e:
raise RuntimeError(f"Failed to clean up cache files. Error: {e}") from e
def main() -> None:
"""
Demonstrates the usage of DataLoader with example test cases.
"""
# Example 1: Load a dataset by name
try:
print("Loading 'ag_news' dataset by name...")
loader = DataLoader("ag_news")
print(f"Features: {loader.get_features()}")
print(f"Shape: {loader.get_shape()}")
sample = loader.get_sample(0)
print(f"Sample Example: {sample}")
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
# Example 2: Load a dataset from a CSV file
try:
# Create a sample CSV file
csv_path = "sample_data.csv"
df = pd.DataFrame({
"text": ["I love programming.", "Python is great!", "Data science is fascinating."],
"label": [1, 0, 1]
})
df.to_csv(csv_path, index=False)
print(f"\nLoading dataset from '{csv_path}'...")
loader_csv = DataLoader.from_path(csv_path, file_type="csv")
print(f"Features: {loader_csv.get_features()}")
print(f"Shape: {loader_csv.get_shape()}")
sample_csv = loader_csv.get_sample(1)
print(f"Sample Example: {sample_csv}")
# Cleanup the sample CSV file
os.remove(csv_path)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
# Example 3: Apply a map function to tokenize text
try:
def tokenize(example: Dict[str, Any]) -> Dict[str, Any]:
example["tokens"] = example["text"].split()
return example
print("\nApplying tokenize function to the 'ag_news' dataset...")
loader.map(tokenize, batched=False)
token_sample = loader.get_sample(0)
print(f"Tokenized Sample: {token_sample}")
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
# Example 4: Shuffle and split the dataset
try:
print("\nShuffling the dataset...")
loader.shuffle(seed=42)
print("Splitting the dataset into train and test...")
splits = loader.split(test_size=0.1)
print(f"Train size: {splits['train'].get_shape()}")
print(f"Test size: {splits['test'].get_shape()}")
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
if __name__ == "__main__":
main()
Explanation of the Code
-
DataLoader Class:
- Initialization: Loads a dataset either by name or path. If a path is provided, it can handle different file types like CSV and JSON.
- Class Methods: Provides an alternative constructor
from_path to handle local files.
- Utility Methods: Includes methods to get dataset features, shape, apply transformations (
map and filter), save and load datasets from disk, shuffle, split, concatenate, and clean up cache.
- Error Handling: Each method includes try-except blocks to catch and raise meaningful errors, ensuring robustness.
-
Main Function:
- Example 1: Demonstrates loading a dataset by name (
ag_news), retrieving its features, shape, and a sample example.
- Example 2: Shows how to load a dataset from a local CSV file. It creates a sample CSV file, loads it, displays its features and a sample, and then cleans up the file.
- Example 3: Applies a simple tokenization function to the loaded dataset using the
map method.
- Example 4: Illustrates shuffling the dataset and splitting it into training and testing subsets.
-
PEP-8 Compliance and Type Hints: The code follows PEP-8 standards for readability and structure. Type hints are used extensively to clarify the expected types of variables and function returns.
-
Scalability and Efficiency: The map and filter methods support batch and parallel processing, allowing the pipeline to handle large datasets efficiently.
-
Comprehensive Error Handling: By catching exceptions and providing clear error messages, the pipeline ensures robustness against unexpected issues during data loading and processing.
Running the Code
Ensure you have the datasets library installed. You can install it using:
pip install datasets pandas
Then, run the script:
python data_loader.py
This will execute the main function, demonstrating various functionalities of the DataLoader class with example datasets.