import_data.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. """Functions for downloading and reading MNIST data."""
  2. from __future__ import absolute_import
  3. from __future__ import division
  4. from __future__ import print_function
  5. import gzip
  6. import os
  7. import numpy
  8. from six.moves import urllib
  9. from six.moves import xrange # pylint: disable=redefined-builtin
  10. SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
  11. def maybe_download(filename, work_directory):
  12. """Download the data from Yann's website, unless it's already here."""
  13. if not os.path.exists(work_directory):
  14. os.mkdir(work_directory)
  15. filepath = os.path.join(work_directory, filename)
  16. if not os.path.exists(filepath):
  17. filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)
  18. statinfo = os.stat(filepath)
  19. print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
  20. return filepath
  21. def _read32(bytestream):
  22. dt = numpy.dtype(numpy.uint32).newbyteorder('>')
  23. return numpy.frombuffer(bytestream.read(4), dtype=dt)
  24. def extract_images(filename):
  25. """Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
  26. print('Extracting', filename)
  27. with gzip.open(filename) as bytestream:
  28. magic = _read32(bytestream)
  29. if magic != 2051:
  30. raise ValueError(
  31. 'Invalid magic number %d in MNIST image file: %s' %
  32. (magic, filename))
  33. num_images = _read32(bytestream)
  34. rows = _read32(bytestream)
  35. cols = _read32(bytestream)
  36. buf = bytestream.read(rows * cols * num_images)
  37. data = numpy.frombuffer(buf, dtype=numpy.uint8)
  38. data = data.reshape(num_images, rows, cols, 1)
  39. return data
  40. def dense_to_one_hot(labels_dense, num_classes=10):
  41. """Convert class labels from scalars to one-hot vectors."""
  42. num_labels = labels_dense.shape[0]
  43. index_offset = numpy.arange(num_labels) * num_classes
  44. labels_one_hot = numpy.zeros((num_labels, num_classes))
  45. labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
  46. return labels_one_hot
  47. def extract_labels(filename, one_hot=False):
  48. """Extract the labels into a 1D uint8 numpy array [index]."""
  49. print('Extracting', filename)
  50. with gzip.open(filename) as bytestream:
  51. magic = _read32(bytestream)
  52. if magic != 2049:
  53. raise ValueError(
  54. 'Invalid magic number %d in MNIST label file: %s' %
  55. (magic, filename))
  56. num_items = _read32(bytestream)
  57. buf = bytestream.read(num_items)
  58. labels = numpy.frombuffer(buf, dtype=numpy.uint8)
  59. if one_hot:
  60. return dense_to_one_hot(labels)
  61. return labels
  62. class DataSet(object):
  63. def __init__(self, images, labels, fake_data=False):
  64. if fake_data:
  65. self._num_examples = 10000
  66. else:
  67. assert images.shape[0] == labels.shape[0], (
  68. "images.shape: %s labels.shape: %s" % (images.shape,
  69. labels.shape))
  70. self._num_examples = images.shape[0]
  71. # Convert shape from [num examples, rows, columns, depth]
  72. # to [num examples, rows*columns] (assuming depth == 1)
  73. assert images.shape[3] == 1
  74. images = images.reshape(images.shape[0],
  75. images.shape[1] * images.shape[2])
  76. # Convert from [0, 255] -> [0.0, 1.0].
  77. images = images.astype(numpy.float32)
  78. images = numpy.multiply(images, 1.0 / 255.0)
  79. self._images = images
  80. self._labels = labels
  81. self._epochs_completed = 0
  82. self._index_in_epoch = 0
  83. @property
  84. def images(self):
  85. return self._images
  86. @property
  87. def labels(self):
  88. return self._labels
  89. @property
  90. def num_examples(self):
  91. return self._num_examples
  92. @property
  93. def epochs_completed(self):
  94. return self._epochs_completed
  95. def next_batch(self, batch_size, fake_data=False):
  96. """Return the next `batch_size` examples from this data set."""
  97. if fake_data:
  98. fake_image = [1.0 for _ in xrange(784)]
  99. fake_label = 0
  100. return [fake_image for _ in xrange(batch_size)], [
  101. fake_label for _ in xrange(batch_size)]
  102. start = self._index_in_epoch
  103. self._index_in_epoch += batch_size
  104. if self._index_in_epoch > self._num_examples:
  105. # Finished epoch
  106. self._epochs_completed += 1
  107. # Shuffle the data
  108. perm = numpy.arange(self._num_examples)
  109. numpy.random.shuffle(perm)
  110. self._images = self._images[perm]
  111. self._labels = self._labels[perm]
  112. # Start next epoch
  113. start = 0
  114. self._index_in_epoch = batch_size
  115. assert batch_size <= self._num_examples
  116. end = self._index_in_epoch
  117. return self._images[start:end], self._labels[start:end]
  118. def read_data_sets(train_dir, fake_data=False, one_hot=False):
  119. class DataSets(object):
  120. pass
  121. data_sets = DataSets()
  122. if fake_data:
  123. data_sets.train = DataSet([], [], fake_data=True)
  124. data_sets.validation = DataSet([], [], fake_data=True)
  125. data_sets.test = DataSet([], [], fake_data=True)
  126. return data_sets
  127. TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
  128. TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
  129. TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
  130. TEST_LABELS = 't10k-labels-idx1-ubyte.gz'
  131. VALIDATION_SIZE = 5000
  132. local_file = maybe_download(TRAIN_IMAGES, train_dir)
  133. train_images = extract_images(local_file)
  134. local_file = maybe_download(TRAIN_LABELS, train_dir)
  135. train_labels = extract_labels(local_file, one_hot=one_hot)
  136. local_file = maybe_download(TEST_IMAGES, train_dir)
  137. test_images = extract_images(local_file)
  138. local_file = maybe_download(TEST_LABELS, train_dir)
  139. test_labels = extract_labels(local_file, one_hot=one_hot)
  140. validation_images = train_images[:VALIDATION_SIZE]
  141. validation_labels = train_labels[:VALIDATION_SIZE]
  142. train_images = train_images[VALIDATION_SIZE:]
  143. train_labels = train_labels[VALIDATION_SIZE:]
  144. data_sets.train = DataSet(train_images, train_labels)
  145. data_sets.validation = DataSet(validation_images, validation_labels)
  146. data_sets.test = DataSet(test_images, test_labels)
  147. return data_sets