-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
205 lines (158 loc) · 6.83 KB
/
utils.py
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import os
import scipy
import numpy as np
import tensorflow as tf
def load_mnist(batch_size, is_training=True):
path = os.path.join('data', 'mnist')
if is_training:
fd = open(os.path.join(path, 'train-images-idx3-ubyte'))
loaded = np.fromfile(file=fd, dtype=np.uint8)
trainX = loaded[16:].reshape((60000, 28, 28, 1)).astype(np.float32)
fd = open(os.path.join(path, 'train-labels-idx1-ubyte'))
loaded = np.fromfile(file=fd, dtype=np.uint8)
trainY = loaded[8:].reshape((60000)).astype(np.int32)
trX = trainX[:55000] / 255.
trY = trainY[:55000]
valX = trainX[55000:, ] / 255.
valY = trainY[55000:]
num_tr_batch = 55000 // batch_size
num_val_batch = 5000 // batch_size
return trX, trY, num_tr_batch, valX, valY, num_val_batch
else:
fd = open(os.path.join(path, 't10k-images-idx3-ubyte'))
loaded = np.fromfile(file=fd, dtype=np.uint8)
teX = loaded[16:].reshape((10000, 28, 28, 1)).astype(np.float)
fd = open(os.path.join(path, 't10k-labels-idx1-ubyte'))
loaded = np.fromfile(file=fd, dtype=np.uint8)
teY = loaded[8:].reshape((10000)).astype(np.int32)
num_te_batch = 10000 // batch_size
return teX / 255., teY, num_te_batch
def load_fashion_mnist(batch_size, is_training=True):
path = os.path.join('data', 'fashion-mnist')
if is_training:
fd = open(os.path.join(path, 'train-images-idx3-ubyte'))
loaded = np.fromfile(file=fd, dtype=np.uint8)
trainX = loaded[16:].reshape((60000, 28, 28, 1)).astype(np.float32)
fd = open(os.path.join(path, 'train-labels-idx1-ubyte'))
loaded = np.fromfile(file=fd, dtype=np.uint8)
trainY = loaded[8:].reshape((60000)).astype(np.int32)
trX = trainX[:55000] / 255.
trY = trainY[:55000]
valX = trainX[55000:, ] / 255.
valY = trainY[55000:]
num_tr_batch = 55000 // batch_size
num_val_batch = 5000 // batch_size
return trX, trY, num_tr_batch, valX, valY, num_val_batch
else:
fd = open(os.path.join(path, 't10k-images-idx3-ubyte'))
loaded = np.fromfile(file=fd, dtype=np.uint8)
teX = loaded[16:].reshape((10000, 28, 28, 1)).astype(np.float)
fd = open(os.path.join(path, 't10k-labels-idx1-ubyte'))
loaded = np.fromfile(file=fd, dtype=np.uint8)
teY = loaded[8:].reshape((10000)).astype(np.int32)
num_te_batch = 10000 // batch_size
return teX / 255., teY, num_te_batch
def load_cifar10(batch_size, is_training=True):
path = os.path.join('data', 'cifar10')
path = os.path.join(path, 'cifar-10-batches-bin')
if is_training:
trainX = []
trainY = []
for i in range(1, 6):
fd = open(os.path.join(path, 'data_batch_{}.bin'.format(i)))
loaded = np.fromfile(file=fd, dtype=np.uint8)
train = loaded.reshape((10000, -1))
trainX.append(train[:, 1:].reshape((-1, 3, 32, 32)).transpose(0, 2, 3, 1))
trainY.append(train[:, 0])
trainX = np.array(trainX).reshape((-1, 32, 32, 3)).astype(np.float32)
trainY = np.array(trainY).reshape((-1,)).astype(np.int32)
trX = trainX[:45000] / 255.
trY = trainY[:45000]
valX = trainX[45000:, ] / 255.
valY = trainY[45000:]
num_tr_batch = 45000 // batch_size
num_val_batch = 5000 // batch_size
return trX, trY, num_tr_batch, valX, valY, num_val_batch
else:
fd = open(os.path.join(path, 'test_batch.bin'))
loaded = np.fromfile(file=fd, dtype=np.uint8)
test = loaded.reshape((10000, -1))
teX = test[:, 1:].reshape((-1, 3, 32, 32)).transpose(0, 2, 3, 1).astype(np.float)
teY = test[:, 0].reshape((-1,)).astype(np.int32)
num_te_batch = 10000 // batch_size
return teX / 255., teY, num_te_batch
def load_data(dataset, batch_size, is_training=True, one_hot=False):
if dataset == 'mnist':
return load_mnist(batch_size, is_training)
elif dataset == 'fashion-mnist':
return load_fashion_mnist(batch_size, is_training)
elif dataset == 'cifar10':
return load_cifar10(batch_size, is_training)
else:
raise Exception('Invalid dataset, please check the name of dataset:', dataset)
def get_batch_data(dataset, batch_size, num_threads):
if dataset == 'mnist':
trX, trY, num_tr_batch, valX, valY, num_val_batch = load_mnist(batch_size, is_training=True)
elif dataset == 'fashion-mnist':
trX, trY, num_tr_batch, valX, valY, num_val_batch = load_fashion_mnist(batch_size, is_training=True)
elif dataset == 'cifar10':
trX, trY, num_tr_batch, valX, valY, num_val_batch = load_cifar10(batch_size, is_training=True)
data_queues = tf.train.slice_input_producer([trX, trY])
X, Y = tf.train.shuffle_batch(data_queues, num_threads=num_threads,
batch_size=batch_size,
capacity=batch_size * 64,
min_after_dequeue=batch_size * 32,
allow_smaller_final_batch=False)
return(X, Y)
def rgb_to_gray(images):
images = 0.299 * images[:, :, :, 0] + 0.587 * images[:, :, :, 1] + 0.114 * images[:, :, :, 2]
return images[:, :, :, np.newaxis]
def save_images(imgs, size, path):
'''
Args:
imgs: [batch_size, image_height, image_width]
size: a list with tow int elements, [image_height, image_width]
path: the path to save images
'''
imgs = (imgs + 1.) / 2 # inverse_transform
return(scipy.misc.imsave(path, mergeImgs(imgs, size)))
def mergeImgs(images, size):
h, w = images.shape[1], images.shape[2]
imgs = np.zeros((h * size[0], w * size[1], 3))
for idx, image in enumerate(images):
i = idx % size[1]
j = idx // size[1]
imgs[j * h:j * h + h, i * w:i * w + w, :] = image
return imgs
def quantize(input, bits=8):
def S(bits):
return 2.0 ** (bits - 1)
def C(x, bits):
if bits > 15 or bits == 1:
delta = 0.
else:
delta = 1. / S(bits)
MAX = +1 - delta
MIN = -1 + delta
return tf.clip_by_value(x, MIN, MAX)
def Q(x, bits):
if bits > 15:
return x
elif bits == 1: # BNN
return tf.sign(x)
else:
SCALE = S(bits)
return tf.round(x * SCALE) / SCALE
return Q(C(input, bits), bits)
# For version compatibility
def reduce_sum(input_tensor, axis=None, keepdims=False):
try:
return tf.reduce_sum(input_tensor, axis=axis, keepdims=keepdims)
except:
return tf.reduce_sum(input_tensor, axis=axis, keep_dims=keepdims)
# For version compatibility
def softmax(logits, axis=None):
try:
return tf.nn.softmax(logits, axis=axis)
except:
return tf.nn.softmax(logits, dim=axis)