Uh oh!
There was an error while loading. Please reload this page.
forked from nlintz/TensorFlow-Tutorials
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput_data.py
More file actions
Latest commit
executable file
·164 lines (144 loc) · 6.08 KB
/
Copy pathinput_data.py
File metadata and controls
executable file
·164 lines (144 loc) · 6.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#!/usr/bin/env python
"""Functions for downloading and reading MNIST data."""
importgzip
importos
fromsix.moves.urllib.requestimporturlretrieve
importnumpy
SOURCE_URL='http://yann.lecun.com/exdb/mnist/'
defmaybe_download(filename, work_directory):
"""Download the data from Yann's website, unless it's already here."""
ifnotos.path.exists(work_directory):
os.mkdir(work_directory)
filepath=os.path.join(work_directory, filename)
ifnotos.path.exists(filepath):
filepath, _=urlretrieve(SOURCE_URL+filename, filepath)
statinfo=os.stat(filepath)
print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
returnfilepath
def_read32(bytestream):
dt=numpy.dtype(numpy.uint32).newbyteorder('>')
returnnumpy.frombuffer(bytestream.read(4), dtype=dt)
defextract_images(filename):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
print('Extracting', filename)
withgzip.open(filename) asbytestream:
magic=_read32(bytestream)
ifmagic!=2051:
raiseValueError(
'Invalid magic number %d in MNIST image file: %s'%
(magic, filename))
num_images=_read32(bytestream)
rows=_read32(bytestream)
cols=_read32(bytestream)
buf=bytestream.read(rows*cols*num_images)
data=numpy.frombuffer(buf, dtype=numpy.uint8)
data=data.reshape(num_images, rows, cols, 1)
returndata
defdense_to_one_hot(labels_dense, num_classes=10):
"""Convert class labels from scalars to one-hot vectors."""
num_labels=labels_dense.shape[0]
index_offset=numpy.arange(num_labels) *num_classes
labels_one_hot=numpy.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset+labels_dense.ravel()] =1
returnlabels_one_hot
defextract_labels(filename, one_hot=False):
"""Extract the labels into a 1D uint8 numpy array [index]."""
print('Extracting', filename)
withgzip.open(filename) asbytestream:
magic=_read32(bytestream)
ifmagic!=2049:
raiseValueError(
'Invalid magic number %d in MNIST label file: %s'%
(magic, filename))
num_items=_read32(bytestream)
buf=bytestream.read(num_items)
labels=numpy.frombuffer(buf, dtype=numpy.uint8)
ifone_hot:
returndense_to_one_hot(labels)
returnlabels
classDataSet(object):
def__init__(self, images, labels, fake_data=False):
iffake_data:
self._num_examples=10000
else:
assertimages.shape[0] ==labels.shape[0], (
"images.shape: %s labels.shape: %s"% (images.shape,
labels.shape))
self._num_examples=images.shape[0]
# Convert shape from [num examples, rows, columns, depth]
# to [num examples, rows*columns] (assuming depth == 1)
assertimages.shape[3] ==1
images=images.reshape(images.shape[0],
images.shape[1] *images.shape[2])
# Convert from [0, 255] -> [0.0, 1.0].
images=images.astype(numpy.float32)
images=numpy.multiply(images, 1.0/255.0)
self._images=images
self._labels=labels
self._epochs_completed=0
self._index_in_epoch=0
@property
defimages(self):
returnself._images
@property
deflabels(self):
returnself._labels
@property
defnum_examples(self):
returnself._num_examples
@property
defepochs_completed(self):
returnself._epochs_completed
defnext_batch(self, batch_size, fake_data=False):
"""Return the next `batch_size` examples from this data set."""
iffake_data:
fake_image= [1.0for_inxrange(784)]
fake_label=0
return [fake_imagefor_inxrange(batch_size)], [
fake_labelfor_inxrange(batch_size)]
start=self._index_in_epoch
self._index_in_epoch+=batch_size
ifself._index_in_epoch>self._num_examples:
# Finished epoch
self._epochs_completed+=1
# Shuffle the data
perm=numpy.arange(self._num_examples)
numpy.random.shuffle(perm)
self._images=self._images[perm]
self._labels=self._labels[perm]
# Start next epoch
start=0
self._index_in_epoch=batch_size
assertbatch_size<=self._num_examples
end=self._index_in_epoch
returnself._images[start:end], self._labels[start:end]
defread_data_sets(train_dir, fake_data=False, one_hot=False):
classDataSets(object):
pass
data_sets=DataSets()
iffake_data:
data_sets.train=DataSet([], [], fake_data=True)
data_sets.validation=DataSet([], [], fake_data=True)
data_sets.test=DataSet([], [], fake_data=True)
returndata_sets
TRAIN_IMAGES='train-images-idx3-ubyte.gz'
TRAIN_LABELS='train-labels-idx1-ubyte.gz'
TEST_IMAGES='t10k-images-idx3-ubyte.gz'
TEST_LABELS='t10k-labels-idx1-ubyte.gz'
VALIDATION_SIZE=5000
local_file=maybe_download(TRAIN_IMAGES, train_dir)
train_images=extract_images(local_file)
local_file=maybe_download(TRAIN_LABELS, train_dir)
train_labels=extract_labels(local_file, one_hot=one_hot)
local_file=maybe_download(TEST_IMAGES, train_dir)
test_images=extract_images(local_file)
local_file=maybe_download(TEST_LABELS, train_dir)
test_labels=extract_labels(local_file, one_hot=one_hot)
validation_images=train_images[:VALIDATION_SIZE]
validation_labels=train_labels[:VALIDATION_SIZE]
train_images=train_images[VALIDATION_SIZE:]
train_labels=train_labels[VALIDATION_SIZE:]
data_sets.train=DataSet(train_images, train_labels)
data_sets.validation=DataSet(validation_images, validation_labels)
data_sets.test=DataSet(test_images, test_labels)
returndata_sets