emnist_letters / emnist_letters.py
tanganke's picture
Upload folder using huggingface_hub
50aa98f verified
raw
history blame
2.83 kB
import struct
import numpy as np
import datasets
from datasets.tasks import ImageClassification
_URL = "./raw/"
_URLS = {
"train_images": "emnist-letters-train-images-idx3-ubyte.gz",
"train_labels": "emnist-letters-train-labels-idx1-ubyte.gz",
"test_images": "emnist-letters-test-images-idx3-ubyte.gz",
"test_labels": "emnist-letters-test-labels-idx1-ubyte.gz",
}
class EMNIST(datasets.GeneratorBasedBuilder):
BUILDER_CONFIGS = [
datasets.BuilderConfig(
name="emnist-letters",
version=datasets.Version("1.0.0"),
)
]
def _info(self):
return datasets.DatasetInfo(
features=datasets.Features(
{
"image": datasets.Image(),
"label": datasets.features.ClassLabel(
names=list(chr(i) for i in range(65, 91))
),
}
),
supervised_keys=("image", "label"),
task_templates=[
ImageClassification(
image_column="image",
label_column="label",
)
],
)
def _split_generators(self, dl_manager):
urls_to_download = {key: _URL + fname for key, fname in _URLS.items()}
downloaded_files = dl_manager.download_and_extract(urls_to_download)
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"filepath": (
downloaded_files["train_images"],
downloaded_files["train_labels"],
),
"split": "train",
},
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={
"filepath": (
downloaded_files["test_images"],
downloaded_files["test_labels"],
),
"split": "test",
},
),
]
def _generate_examples(self, filepath, split):
"""This function returns the examples in the raw form."""
# Images
with open(filepath[0], "rb") as f:
# First 16 bytes contain some metadata
_ = f.read(4)
size = struct.unpack(">I", f.read(4))[0]
_ = f.read(8)
images = np.frombuffer(f.read(), dtype=np.uint8).reshape(size, 28, 28)
# Labels
with open(filepath[1], "rb") as f:
# First 8 bytes contain some metadata
_ = f.read(8)
labels = np.frombuffer(f.read(), dtype=np.uint8) - 1
for idx in range(size):
yield idx, {"image": images[idx], "label": str(labels[idx])}