import csv import datasets import numpy as np _HOMEPAGE = 'http://yann.lecun.com/exdb/mnist/' _LICENSE = '-' _DESCRIPTION = '''\ The MNIST database of handwritten digits, available from this page, has a training set of 60,000 examples, and a test set of 10,000 examples. It is a subset of a larger set available from NIST. The digits have been size-normalized and centered in a fixed-size image. ''' _CITATION = '''-''' _NAMES = list('0123456789') class MNISTConfig(datasets.BuilderConfig): '''Builder Config for MNIST''' def __init__( self, description, homepage, **kwargs ): super(MNISTConfig, self).__init__( version=datasets.Version('1.0.0', ''), **kwargs ) self.description = description self.homepage = homepage self.train_image_url = 'data/train.csv' self.test_image_url = 'data/test.csv' class MNIST(datasets.GeneratorBasedBuilder): BUILDER_CONFIGS = [ MNISTConfig( description=_DESCRIPTION, homepage=_HOMEPAGE ) ] def _info(self): features = datasets.Features({ 'image': datasets.Image(mode='L', decode=True, id=None), 'label': datasets.ClassLabel(names=_NAMES) }) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, homepage=_HOMEPAGE, license=_LICENSE, citation=_CITATION ) def _split_generators(self, dl_manager): train_image_path = dl_manager.download( self.config.train_image_url ) test_image_path = dl_manager.download( self.config.test_image_url ) return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ 'data_path': f'{train_image_path}' } ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ 'data_path': f'{test_image_path}' } ) ] def _generate_examples(self, data_path): idx = 0 with open(data_path, newline='', encoding='utf-8') as csvfile: csvreader = csv.reader(csvfile) next(csvreader) for row in csvreader: example = { 'image': np.array(row[1:], np.uint8).reshape(28, 28), 'label': row[0] } yield idx, example idx += 1