• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""Functions for downloading and reading MNIST data (deprecated).
16
17This module and all its submodules are deprecated. See
18[contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md)
19for migration instructions.
20"""
21
22from __future__ import absolute_import
23from __future__ import division
24from __future__ import print_function
25
26import gzip
27
28import numpy
29from six.moves import xrange  # pylint: disable=redefined-builtin
30
31from tensorflow.contrib.learn.python.learn.datasets import base
32from tensorflow.python.framework import dtypes
33from tensorflow.python.framework import random_seed
34from tensorflow.python.platform import gfile
35from tensorflow.python.util.deprecation import deprecated
36
37# CVDF mirror of http://yann.lecun.com/exdb/mnist/
38DEFAULT_SOURCE_URL = 'https://storage.googleapis.com/cvdf-datasets/mnist/'
39
40
41def _read32(bytestream):
42  dt = numpy.dtype(numpy.uint32).newbyteorder('>')
43  return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
44
45
46@deprecated(None, 'Please use tf.data to implement this functionality.')
47def extract_images(f):
48  """Extract the images into a 4D uint8 numpy array [index, y, x, depth].
49
50  Args:
51    f: A file object that can be passed into a gzip reader.
52
53  Returns:
54    data: A 4D uint8 numpy array [index, y, x, depth].
55
56  Raises:
57    ValueError: If the bytestream does not start with 2051.
58
59  """
60  print('Extracting', f.name)
61  with gzip.GzipFile(fileobj=f) as bytestream:
62    magic = _read32(bytestream)
63    if magic != 2051:
64      raise ValueError('Invalid magic number %d in MNIST image file: %s' %
65                       (magic, f.name))
66    num_images = _read32(bytestream)
67    rows = _read32(bytestream)
68    cols = _read32(bytestream)
69    buf = bytestream.read(rows * cols * num_images)
70    data = numpy.frombuffer(buf, dtype=numpy.uint8)
71    data = data.reshape(num_images, rows, cols, 1)
72    return data
73
74
75@deprecated(None, 'Please use tf.one_hot on tensors.')
76def dense_to_one_hot(labels_dense, num_classes):
77  """Convert class labels from scalars to one-hot vectors."""
78  num_labels = labels_dense.shape[0]
79  index_offset = numpy.arange(num_labels) * num_classes
80  labels_one_hot = numpy.zeros((num_labels, num_classes))
81  labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
82  return labels_one_hot
83
84
85@deprecated(None, 'Please use tf.data to implement this functionality.')
86def extract_labels(f, one_hot=False, num_classes=10):
87  """Extract the labels into a 1D uint8 numpy array [index].
88
89  Args:
90    f: A file object that can be passed into a gzip reader.
91    one_hot: Does one hot encoding for the result.
92    num_classes: Number of classes for the one hot encoding.
93
94  Returns:
95    labels: a 1D uint8 numpy array.
96
97  Raises:
98    ValueError: If the bystream doesn't start with 2049.
99  """
100  print('Extracting', f.name)
101  with gzip.GzipFile(fileobj=f) as bytestream:
102    magic = _read32(bytestream)
103    if magic != 2049:
104      raise ValueError('Invalid magic number %d in MNIST label file: %s' %
105                       (magic, f.name))
106    num_items = _read32(bytestream)
107    buf = bytestream.read(num_items)
108    labels = numpy.frombuffer(buf, dtype=numpy.uint8)
109    if one_hot:
110      return dense_to_one_hot(labels, num_classes)
111    return labels
112
113
114class DataSet(object):
115  """Container class for a dataset (deprecated).
116
117  THIS CLASS IS DEPRECATED. See
118  [contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md)
119  for general migration instructions.
120  """
121
122  @deprecated(None, 'Please use alternatives such as official/mnist/dataset.py'
123              ' from tensorflow/models.')
124  def __init__(self,
125               images,
126               labels,
127               fake_data=False,
128               one_hot=False,
129               dtype=dtypes.float32,
130               reshape=True,
131               seed=None):
132    """Construct a DataSet.
133    one_hot arg is used only if fake_data is true.  `dtype` can be either
134    `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
135    `[0, 1]`.  Seed arg provides for convenient deterministic testing.
136    """
137    seed1, seed2 = random_seed.get_seed(seed)
138    # If op level seed is not set, use whatever graph level seed is returned
139    numpy.random.seed(seed1 if seed is None else seed2)
140    dtype = dtypes.as_dtype(dtype).base_dtype
141    if dtype not in (dtypes.uint8, dtypes.float32):
142      raise TypeError(
143          'Invalid image dtype %r, expected uint8 or float32' % dtype)
144    if fake_data:
145      self._num_examples = 10000
146      self.one_hot = one_hot
147    else:
148      assert images.shape[0] == labels.shape[0], (
149          'images.shape: %s labels.shape: %s' % (images.shape, labels.shape))
150      self._num_examples = images.shape[0]
151
152      # Convert shape from [num examples, rows, columns, depth]
153      # to [num examples, rows*columns] (assuming depth == 1)
154      if reshape:
155        assert images.shape[3] == 1
156        images = images.reshape(images.shape[0],
157                                images.shape[1] * images.shape[2])
158      if dtype == dtypes.float32:
159        # Convert from [0, 255] -> [0.0, 1.0].
160        images = images.astype(numpy.float32)
161        images = numpy.multiply(images, 1.0 / 255.0)
162    self._images = images
163    self._labels = labels
164    self._epochs_completed = 0
165    self._index_in_epoch = 0
166
167  @property
168  def images(self):
169    return self._images
170
171  @property
172  def labels(self):
173    return self._labels
174
175  @property
176  def num_examples(self):
177    return self._num_examples
178
179  @property
180  def epochs_completed(self):
181    return self._epochs_completed
182
183  def next_batch(self, batch_size, fake_data=False, shuffle=True):
184    """Return the next `batch_size` examples from this data set."""
185    if fake_data:
186      fake_image = [1] * 784
187      if self.one_hot:
188        fake_label = [1] + [0] * 9
189      else:
190        fake_label = 0
191      return [fake_image for _ in xrange(batch_size)], [
192          fake_label for _ in xrange(batch_size)
193      ]
194    start = self._index_in_epoch
195    # Shuffle for the first epoch
196    if self._epochs_completed == 0 and start == 0 and shuffle:
197      perm0 = numpy.arange(self._num_examples)
198      numpy.random.shuffle(perm0)
199      self._images = self.images[perm0]
200      self._labels = self.labels[perm0]
201    # Go to the next epoch
202    if start + batch_size > self._num_examples:
203      # Finished epoch
204      self._epochs_completed += 1
205      # Get the rest examples in this epoch
206      rest_num_examples = self._num_examples - start
207      images_rest_part = self._images[start:self._num_examples]
208      labels_rest_part = self._labels[start:self._num_examples]
209      # Shuffle the data
210      if shuffle:
211        perm = numpy.arange(self._num_examples)
212        numpy.random.shuffle(perm)
213        self._images = self.images[perm]
214        self._labels = self.labels[perm]
215      # Start next epoch
216      start = 0
217      self._index_in_epoch = batch_size - rest_num_examples
218      end = self._index_in_epoch
219      images_new_part = self._images[start:end]
220      labels_new_part = self._labels[start:end]
221      return numpy.concatenate(
222          (images_rest_part, images_new_part), axis=0), numpy.concatenate(
223              (labels_rest_part, labels_new_part), axis=0)
224    else:
225      self._index_in_epoch += batch_size
226      end = self._index_in_epoch
227      return self._images[start:end], self._labels[start:end]
228
229
230@deprecated(None, 'Please use alternatives such as official/mnist/dataset.py'
231            ' from tensorflow/models.')
232def read_data_sets(train_dir,
233                   fake_data=False,
234                   one_hot=False,
235                   dtype=dtypes.float32,
236                   reshape=True,
237                   validation_size=5000,
238                   seed=None,
239                   source_url=DEFAULT_SOURCE_URL):
240  if fake_data:
241
242    def fake():
243      return DataSet(
244          [], [], fake_data=True, one_hot=one_hot, dtype=dtype, seed=seed)
245
246    train = fake()
247    validation = fake()
248    test = fake()
249    return base.Datasets(train=train, validation=validation, test=test)
250
251  if not source_url:  # empty string check
252    source_url = DEFAULT_SOURCE_URL
253
254  TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
255  TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
256  TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
257  TEST_LABELS = 't10k-labels-idx1-ubyte.gz'
258
259  local_file = base.maybe_download(TRAIN_IMAGES, train_dir,
260                                   source_url + TRAIN_IMAGES)
261  with gfile.Open(local_file, 'rb') as f:
262    train_images = extract_images(f)
263
264  local_file = base.maybe_download(TRAIN_LABELS, train_dir,
265                                   source_url + TRAIN_LABELS)
266  with gfile.Open(local_file, 'rb') as f:
267    train_labels = extract_labels(f, one_hot=one_hot)
268
269  local_file = base.maybe_download(TEST_IMAGES, train_dir,
270                                   source_url + TEST_IMAGES)
271  with gfile.Open(local_file, 'rb') as f:
272    test_images = extract_images(f)
273
274  local_file = base.maybe_download(TEST_LABELS, train_dir,
275                                   source_url + TEST_LABELS)
276  with gfile.Open(local_file, 'rb') as f:
277    test_labels = extract_labels(f, one_hot=one_hot)
278
279  if not 0 <= validation_size <= len(train_images):
280    raise ValueError('Validation size should be between 0 and {}. Received: {}.'
281                     .format(len(train_images), validation_size))
282
283  validation_images = train_images[:validation_size]
284  validation_labels = train_labels[:validation_size]
285  train_images = train_images[validation_size:]
286  train_labels = train_labels[validation_size:]
287
288  options = dict(dtype=dtype, reshape=reshape, seed=seed)
289
290  train = DataSet(train_images, train_labels, **options)
291  validation = DataSet(validation_images, validation_labels, **options)
292  test = DataSet(test_images, test_labels, **options)
293
294  return base.Datasets(train=train, validation=validation, test=test)
295
296
297@deprecated(None, 'Please use alternatives such as official/mnist/dataset.py'
298            ' from tensorflow/models.')
299def load_mnist(train_dir='MNIST-data'):
300  return read_data_sets(train_dir)
301