input_data.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. # Copyright 2015 Google Inc. 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."""
  16. from __future__ import absolute_import
  17. from __future__ import division
  18. from __future__ import print_function
  19. #from mnist_demo import *
  20. import os
  21. import gzip
  22. import os
  23. import tempfile
  24. import numpy
  25. from six.moves import urllib
  26. from six.moves import xrange # pylint: disable=redefined-builtin
  27. import tensorflow as tf
  28. SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
  29. def maybe_download(filename, work_directory):
  30. """Download the data from Yann's website, unless it's already here."""
  31. filepath = os.path.join(work_directory, filename)
  32. print(filepath)
  33. # if not tf.gfile.Exists(filepath):
  34. # with tempfile.NamedTemporaryFile() as tmpfile:
  35. # temp_file_name = tmpfile.name
  36. # urllib.request.urlretrieve(SOURCE_URL + filename, temp_file_name)
  37. # tf.gfile.Copy(temp_file_name, filepath)
  38. # with tf.gfile.GFile(filepath) as f:
  39. # size = f.Size()
  40. # print('Successfully downloaded', filename, size, 'bytes.')
  41. return filepath
  42. def _read32(bytestream):
  43. dt = numpy.dtype(numpy.uint32).newbyteorder('>')
  44. return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
  45. def extract_images(filename):
  46. """Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
  47. print('Extracting', filename)
  48. with open(filename, 'rb') as f, gzip.GzipFile(fileobj=f) as bytestream:
  49. magic = _read32(bytestream)
  50. if magic != 2051:
  51. raise ValueError(
  52. 'Invalid magic number %d in MNIST image file: %s' %
  53. (magic, filename))
  54. num_images = _read32(bytestream)
  55. rows = _read32(bytestream)
  56. cols = _read32(bytestream)
  57. buf = bytestream.read(rows * cols * num_images)
  58. data = numpy.frombuffer(buf, dtype=numpy.uint8)
  59. data = data.reshape(num_images, rows, cols, 1)
  60. return data
  61. def dense_to_one_hot(labels_dense, num_classes):
  62. #print(labels_dense.shape)
  63. #print(labels_dense)
  64. """Convert class labels from scalars to one-hot vectors."""
  65. num_labels = labels_dense.shape[0]
  66. #print(num_labels)
  67. index_offset = numpy.arange(num_labels) * num_classes
  68. #print(index_offset)
  69. labels_one_hot = numpy.zeros((num_labels, num_classes))
  70. #print(labels_one_hot.shape)
  71. #print(labels_one_hot)
  72. #print(labels_dense.shape)
  73. labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
  74. #print(labels_one_hot.shape)
  75. return labels_one_hot
  76. def extract_labels(filename, one_hot=False, num_classes=10):
  77. """Extract the labels into a 1D uint8 numpy array [index]."""
  78. print('Extracting', filename)
  79. # with tf.gfile.Open(filename, 'rb') as f, gzip.GzipFile(fileobj=f) as bytestream:
  80. with open(filename, 'rb') as f, gzip.GzipFile(fileobj=f) as bytestream:
  81. magic = _read32(bytestream)
  82. if magic != 2049:
  83. raise ValueError(
  84. 'Invalid magic number %d in MNIST label file: %s' %
  85. (magic, filename))
  86. num_items = _read32(bytestream)
  87. buf = bytestream.read(num_items)
  88. labels = numpy.frombuffer(buf, dtype=numpy.uint8)
  89. if one_hot:
  90. return dense_to_one_hot(labels, num_classes)
  91. return labels
  92. class DataSet(object):
  93. def __init__(self, images, labels, fake_data=False, one_hot=False,
  94. dtype=tf.float32):
  95. """Construct a DataSet.
  96. one_hot arg is used only if fake_data is true. `dtype` can be either
  97. `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
  98. `[0, 1]`.
  99. """
  100. dtype = tf.as_dtype(dtype).base_dtype
  101. if dtype not in (tf.uint8, tf.float32):
  102. raise TypeError('Invalid image dtype %r, expected uint8 or float32' %
  103. dtype)
  104. if fake_data:
  105. self._num_examples = 10000
  106. self.one_hot = one_hot
  107. else:
  108. assert images.shape[0] == labels.shape[0], (
  109. 'images.shape: %s labels.shape: %s' % (images.shape,
  110. labels.shape))
  111. self._num_examples = images.shape[0]
  112. # Convert shape from [num examples, rows, columns, depth]
  113. # to [num examples, rows*columns] (assuming depth == 1)
  114. assert images.shape[3] == 1
  115. images = images.reshape(images.shape[0],
  116. images.shape[1] * images.shape[2])
  117. if dtype == tf.float32:
  118. # Convert from [0, 255] -> [0.0, 1.0].
  119. images = images.astype(numpy.float32)
  120. images = numpy.multiply(images, 1.0 / 255.0)
  121. self._images = images
  122. self._labels = labels
  123. self._epochs_completed = 0
  124. self._index_in_epoch = 0
  125. @property
  126. def images(self):
  127. return self._images
  128. @property
  129. def labels(self):
  130. return self._labels
  131. @property
  132. def num_examples(self):
  133. return self._num_examples
  134. @property
  135. def epochs_completed(self):
  136. return self._epochs_completed
  137. def next_batch(self, batch_size, fake_data=False):
  138. """Return the next `batch_size` examples from this data set."""
  139. if fake_data:
  140. fake_image = [1] * 784
  141. if self.one_hot:
  142. fake_label = [1] + [0] * 9
  143. else:
  144. fake_label = 0
  145. return [fake_image for _ in xrange(batch_size)], [
  146. fake_label for _ in xrange(batch_size)]
  147. start = self._index_in_epoch
  148. self._index_in_epoch += batch_size
  149. if self._index_in_epoch > self._num_examples:
  150. # Finished epoch
  151. self._epochs_completed += 1
  152. # Shuffle the data
  153. perm = numpy.arange(self._num_examples)
  154. numpy.random.shuffle(perm)
  155. self._images = self._images[perm]
  156. self._labels = self._labels[perm]
  157. # Start next epoch
  158. start = 0
  159. self._index_in_epoch = batch_size
  160. assert batch_size <= self._num_examples
  161. end = self._index_in_epoch
  162. # print(self._images[start])
  163. return self._images[start:end], self._labels[start:end]
  164. def read_data_sets(train_dir, fake_data=False, one_hot=False, dtype=tf.float32):
  165. class DataSets(object):
  166. pass
  167. data_sets = DataSets()
  168. if fake_data:
  169. def fake():
  170. return DataSet([], [], fake_data=True, one_hot=one_hot, dtype=dtype)
  171. data_sets.train = fake()
  172. data_sets.validation = fake()
  173. data_sets.test = fake()
  174. return data_sets
  175. TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
  176. TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
  177. TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
  178. TEST_LABELS = 't10k-labels-idx1-ubyte.gz'
  179. VALIDATION_SIZE = 5000
  180. local_file = maybe_download(TRAIN_IMAGES, train_dir)
  181. train_images = extract_images(local_file)
  182. local_file = maybe_download(TRAIN_LABELS, train_dir)
  183. train_labels = extract_labels(local_file, one_hot=one_hot)
  184. local_file = maybe_download(TEST_IMAGES, train_dir)
  185. test_images = extract_images(local_file)
  186. local_file = maybe_download(TEST_LABELS, train_dir)
  187. test_labels = extract_labels(local_file, one_hot=one_hot)
  188. validation_images = train_images[:VALIDATION_SIZE]
  189. validation_labels = train_labels[:VALIDATION_SIZE]
  190. train_images = train_images[VALIDATION_SIZE:]
  191. train_labels = train_labels[VALIDATION_SIZE:]
  192. data_sets.train = DataSet(train_images, train_labels, dtype=dtype)
  193. data_sets.validation = DataSet(validation_images, validation_labels,dtype=dtype)
  194. test_images = test_images[VALIDATION_SIZE:]
  195. test_labels = test_labels[VALIDATION_SIZE:]
  196. data_sets.test = DataSet(test_images, test_labels, dtype=dtype)
  197. data_sets.validation = DataSet(validation_images, validation_labels,dtype=dtype)
  198. #print(test_images[3][15]);
  199. #print(len(test_images[0][0]));
  200. # print (len(test_images))
  201. # if(files==null) return
  202. # test_images1,test_labels1=GetImage(files)
  203. # # print(((test_images1[0])))
  204. # # test_images=array(test_images1)
  205. # # test_labels=array(test_labels1)
  206. # # print (test_labels[0])
  207. # # test_images_demo=empty(1)
  208. # # test_images_demo.append(test_images1)
  209. # # print(shape((test_images1)))
  210. # data_sets.test = DataSet(test_images1, test_labels1, dtype=dtype)
  211. return data_sets