|
| 1 | +# coding=utf-8 |
| 2 | +# Copyright 2019 The TensorFlow Datasets Authors. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""Corrupted MNIST Dataset. |
| 17 | +
|
| 18 | +MNISTCorrupted is a dataset generated by adding 15 corruptions to the test |
| 19 | +images in the MNIST dataset. This dataset wraps the static, corrupted MNIST |
| 20 | +test images uploaded by the original authors. |
| 21 | +""" |
| 22 | + |
| 23 | +from __future__ import absolute_import |
| 24 | +from __future__ import division |
| 25 | +from __future__ import print_function |
| 26 | + |
| 27 | +import os |
| 28 | + |
| 29 | +import numpy as np |
| 30 | +import tensorflow as tf |
| 31 | +from tensorflow_datasets.core import api_utils |
| 32 | +from tensorflow_datasets.image import mnist |
| 33 | +import tensorflow_datasets.public_api as tfds |
| 34 | + |
| 35 | +_DESCRIPTION = """\ |
| 36 | +MNISTCorrupted is a dataset generated by adding 15 corruptions to the test |
| 37 | +images in the MNIST dataset. This dataset wraps the static, corrupted MNIST |
| 38 | +test images uploaded by the original authors |
| 39 | +""" |
| 40 | + |
| 41 | +_CITATION = """ |
| 42 | +@article{mu2019mnist, |
| 43 | + title={MNIST-C: A Robustness Benchmark for Computer Vision}, |
| 44 | + author={Mu, Norman and Gilmer, Justin}, |
| 45 | + journal={arXiv preprint arXiv:1906.02337}, |
| 46 | + year={2019} |
| 47 | +} |
| 48 | +""" |
| 49 | + |
| 50 | +_DOWNLOAD_URL = 'https://zenodo.org/record/3239543/files/mnist_c.zip' |
| 51 | +_CORRUPTIONS = [ |
| 52 | + 'identity', |
| 53 | + 'shot_noise', |
| 54 | + 'impulse_noise', |
| 55 | + 'glass_blur', |
| 56 | + 'motion_blur', |
| 57 | + 'shear', |
| 58 | + 'scale', |
| 59 | + 'rotate', |
| 60 | + 'brightness', |
| 61 | + 'translate', |
| 62 | + 'stripe', |
| 63 | + 'fog', |
| 64 | + 'spatter', |
| 65 | + 'dotted_line', |
| 66 | + 'zigzag', |
| 67 | + 'canny_edges', |
| 68 | +] |
| 69 | +_DIRNAME = 'mnist_c' |
| 70 | +_TRAIN_IMAGES_FILENAME = 'train_images.npy' |
| 71 | +_TEST_IMAGES_FILENAME = 'test_images.npy' |
| 72 | +_TRAIN_LABELS_FILENAME = 'train_labels.npy' |
| 73 | +_TEST_LABELS_FILENAME = 'test_labels.npy' |
| 74 | + |
| 75 | + |
| 76 | +class MNISTCorruptedConfig(tfds.core.BuilderConfig): |
| 77 | + """BuilderConfig for MNISTcorrupted.""" |
| 78 | + |
| 79 | + @api_utils.disallow_positional_args |
| 80 | + def __init__(self, corruption_type, **kwargs): |
| 81 | + """Constructor. |
| 82 | +
|
| 83 | + Args: |
| 84 | + corruption_type: string, name of corruption from _CORRUPTIONS. |
| 85 | + **kwargs: keyword arguments forwarded to super. |
| 86 | + """ |
| 87 | + super(MNISTCorruptedConfig, self).__init__(**kwargs) |
| 88 | + self.corruption = corruption_type |
| 89 | + |
| 90 | + |
| 91 | +def _make_builder_configs(): |
| 92 | + """Construct a list of BuilderConfigs. |
| 93 | +
|
| 94 | + Construct a list of 15 MNISTCorruptedConfig objects, corresponding to |
| 95 | + the 15 corruption types. |
| 96 | +
|
| 97 | + Returns: |
| 98 | + A list of 15 MNISTCorruptedConfig objects. |
| 99 | + """ |
| 100 | + config_list = [] |
| 101 | + for corruption in _CORRUPTIONS: |
| 102 | + config_list.append( |
| 103 | + MNISTCorruptedConfig( |
| 104 | + name=corruption, |
| 105 | + version='0.0.1', |
| 106 | + description='Corruption method: ' + corruption, |
| 107 | + corruption_type=corruption, |
| 108 | + )) |
| 109 | + return config_list |
| 110 | + |
| 111 | + |
| 112 | +class MNISTCorrupted(tfds.core.GeneratorBasedBuilder): |
| 113 | + """Corrupted MNIST dataset.""" |
| 114 | + BUILDER_CONFIGS = _make_builder_configs() |
| 115 | + |
| 116 | + def _info(self): |
| 117 | + """Returns basic information of dataset. |
| 118 | +
|
| 119 | + Returns: |
| 120 | + tfds.core.DatasetInfo. |
| 121 | + """ |
| 122 | + return tfds.core.DatasetInfo( |
| 123 | + builder=self, |
| 124 | + description=_DESCRIPTION, |
| 125 | + features=tfds.features.FeaturesDict({ |
| 126 | + 'image': |
| 127 | + tfds.features.Image(shape=mnist.MNIST_IMAGE_SHAPE), |
| 128 | + 'label': |
| 129 | + tfds.features.ClassLabel(num_classes=mnist.MNIST_NUM_CLASSES), |
| 130 | + }), |
| 131 | + supervised_keys=('image', 'label'), |
| 132 | + urls=['https://github.com/google-research/mnist-c'], |
| 133 | + citation=_CITATION) |
| 134 | + |
| 135 | + def _split_generators(self, dl_manager): |
| 136 | + """Return the train, test split of MNIST-C. |
| 137 | +
|
| 138 | + Args: |
| 139 | + dl_manager: download manager object. |
| 140 | +
|
| 141 | + Returns: |
| 142 | + train split, test split. |
| 143 | + """ |
| 144 | + path = dl_manager.download_and_extract(_DOWNLOAD_URL) |
| 145 | + return [ |
| 146 | + tfds.core.SplitGenerator( |
| 147 | + name=tfds.Split.TRAIN, |
| 148 | + num_shards=1, |
| 149 | + gen_kwargs={ |
| 150 | + 'data_dir': os.path.join(path, _DIRNAME), |
| 151 | + 'is_train': True |
| 152 | + }), |
| 153 | + tfds.core.SplitGenerator( |
| 154 | + name=tfds.Split.TEST, |
| 155 | + num_shards=1, |
| 156 | + gen_kwargs={ |
| 157 | + 'data_dir': os.path.join(path, _DIRNAME), |
| 158 | + 'is_train': False |
| 159 | + }), |
| 160 | + ] |
| 161 | + |
| 162 | + def _generate_examples(self, data_dir, is_train): |
| 163 | + """Generate corrupted MNIST data. |
| 164 | +
|
| 165 | + Apply corruptions to the raw images according to self.corruption_type. |
| 166 | +
|
| 167 | + Args: |
| 168 | + data_dir: root directory of downloaded dataset |
| 169 | + is_train: whether to return train images or test images |
| 170 | +
|
| 171 | + Yields: |
| 172 | + dictionary with image file and label. |
| 173 | + """ |
| 174 | + corruption = self.builder_config.corruption |
| 175 | + |
| 176 | + if is_train: |
| 177 | + images_file = os.path.join(data_dir, corruption, _TRAIN_IMAGES_FILENAME) |
| 178 | + labels_file = os.path.join(data_dir, corruption, _TRAIN_LABELS_FILENAME) |
| 179 | + else: |
| 180 | + images_file = os.path.join(data_dir, corruption, _TEST_IMAGES_FILENAME) |
| 181 | + labels_file = os.path.join(data_dir, corruption, _TEST_LABELS_FILENAME) |
| 182 | + |
| 183 | + with tf.io.gfile.GFile(labels_file, mode='rb') as f: |
| 184 | + labels = np.load(f) |
| 185 | + |
| 186 | + with tf.io.gfile.GFile(images_file, mode='rb') as f: |
| 187 | + images = np.load(f) |
| 188 | + |
| 189 | + for image, label in zip(images, labels): |
| 190 | + yield { |
| 191 | + 'image': image, |
| 192 | + 'label': label, |
| 193 | + } |
0 commit comments