import numpy as np
from dataloader_rs import PyDataloader, PyDataset
class Points(PyDataset):
def __init__(self) -> None:
super().__init__()
x = np.arange(12, dtype=np.float32)
self.features = np.stack([x, x * x], axis=1) self.labels = np.arange(12) % 3
def __len__(self) -> int:
return len(self.labels)
def __getitem__(self, index: int) -> dict:
return {"features": self.features[index], "label": int(self.labels[index])}
def __getitems__(self, indices: list[int]) -> list[dict]:
features = self.features[indices]
labels = self.labels[indices]
return [
{"features": f, "label": int(label)} for f, label in zip(features, labels, strict=True)
]
def to_arrays(items: list[dict]) -> dict[str, np.ndarray]:
return {key: np.stack([item[key] for item in items]) for key in items[0]}
def main() -> None:
plain = PyDataloader(Points(), batch_size=4)
print("a list:", next(iter(plain))[:2], "...")
loader = PyDataloader(
Points(), batch_size=4, shuffle=True, seed=0, num_workers=2, collate_fn=to_arrays
)
for batch in loader:
print(f"features {batch['features'].shape}, labels {batch['label']}")
stacked = PyDataloader(
Points(), batch_size=6, collate_fn=lambda items: np.stack([i["features"] for i in items])
)
print("np.stack:", [batch.shape for batch in stacked])
if __name__ == "__main__":
main()