|
""" |
|
Dataset builder for ImageNet-100. |
|
|
|
References: |
|
https://huggingface.co/datasets/imagenet-1k/blob/main/imagenet-1k.py |
|
""" |
|
|
|
import os |
|
from pathlib import Path |
|
from typing import List |
|
|
|
import datasets |
|
from datasets.tasks import ImageClassification |
|
|
|
from .classes import IMAGENET100_CLASSES |
|
|
|
_CITATION = """\ |
|
@inproceedings{tian2020contrastive, |
|
title={Contrastive multiview coding}, |
|
author={Tian, Yonglong and Krishnan, Dilip and Isola, Phillip}, |
|
booktitle={Computer Vision--ECCV 2020: 16th European Conference, Glasgow, UK, August 23--28, 2020, Proceedings, Part XI 16}, |
|
pages={776--794}, |
|
year={2020}, |
|
organization={Springer} |
|
} |
|
""" |
|
|
|
_HOMEPAGE = "https://github.com/HobbitLong/CMC" |
|
|
|
_DESCRIPTION = f"""\ |
|
ImageNet-100 is a subset of ImageNet with 100 classes randomly selected from the original ImageNet-1k dataset. |
|
""" |
|
|
|
_IMAGENET_ROOT = os.environ.get("IMAGENET_ROOT", "/data/imagenet") |
|
|
|
_DATA_URL = { |
|
"train": [f"{_IMAGENET_ROOT}/train/{label}" for label in IMAGENET100_CLASSES], |
|
"val": [f"{_IMAGENET_ROOT}/val/{label}" for label in IMAGENET100_CLASSES], |
|
} |
|
|
|
|
|
class Imagenet100(datasets.GeneratorBasedBuilder): |
|
VERSION = datasets.Version("1.0.0") |
|
|
|
DEFAULT_WRITER_BATCH_SIZE = 1000 |
|
|
|
def _info(self): |
|
assert len(IMAGENET100_CLASSES) == 100 |
|
return datasets.DatasetInfo( |
|
description=_DESCRIPTION, |
|
features=datasets.Features( |
|
{ |
|
"image": datasets.Image(), |
|
"label": datasets.ClassLabel( |
|
names=list(IMAGENET100_CLASSES.values()) |
|
), |
|
} |
|
), |
|
homepage=_HOMEPAGE, |
|
citation=_CITATION, |
|
task_templates=[ |
|
ImageClassification(image_column="image", label_column="label") |
|
], |
|
) |
|
|
|
def _split_generators(self, dl_manager): |
|
"""Returns SplitGenerators.""" |
|
|
|
return [ |
|
datasets.SplitGenerator( |
|
name=datasets.Split.TRAIN, |
|
gen_kwargs={"folders": _DATA_URL["train"]}, |
|
), |
|
datasets.SplitGenerator( |
|
name=datasets.Split.VALIDATION, |
|
gen_kwargs={"folders": _DATA_URL["val"]}, |
|
), |
|
] |
|
|
|
def _generate_examples(self, folders: List[str]): |
|
"""Yields examples.""" |
|
idx = 0 |
|
for folder in folders: |
|
synset_id = Path(folder).name |
|
label = IMAGENET100_CLASSES[synset_id] |
|
|
|
for path in Path(folder).glob("*.JPEG"): |
|
ex = {"image": str(path), "label": label} |
|
yield idx, ex |
|
idx += 1 |
|
|