-
Notifications
You must be signed in to change notification settings - Fork 80
/
dataset_utils.py
122 lines (99 loc) · 3.76 KB
/
dataset_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
import tensorflow as tf
import os, sys, pickle
import numpy as np
from scipy import linalg
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_bool('aug_trans', False, "")
tf.app.flags.DEFINE_bool('aug_flip', False, "")
def unpickle(file):
fp = open(file, 'rb')
if sys.version_info.major == 2:
data = pickle.load(fp)
elif sys.version_info.major == 3:
data = pickle.load(fp, encoding='latin-1')
fp.close()
return data
def ZCA(data, reg=1e-6):
mean = np.mean(data, axis=0)
mdata = data - mean
sigma = np.dot(mdata.T, mdata) / mdata.shape[0]
U, S, V = linalg.svd(sigma)
components = np.dot(np.dot(U, np.diag(1 / np.sqrt(S) + reg)), U.T)
whiten = np.dot(data - mean, components.T)
return components, mean, whiten
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def convert_images_and_labels(images, labels, filepath):
num_examples = labels.shape[0]
if images.shape[0] != num_examples:
raise ValueError("Images size %d does not match label size %d." %
(images.shape[0], num_examples))
print('Writing', filepath)
writer = tf.python_io.TFRecordWriter(filepath)
for index in range(num_examples):
image = images[index].tolist()
image_feature = tf.train.Feature(float_list=tf.train.FloatList(value=image))
example = tf.train.Example(features=tf.train.Features(feature={
'height': _int64_feature(32),
'width': _int64_feature(32),
'depth': _int64_feature(3),
'label': _int64_feature(int(labels[index])),
'image': image_feature}))
writer.write(example.SerializeToString())
writer.close()
def read(filename_queue):
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
# Defaults are not specified since both keys are required.
features={
'image': tf.FixedLenFeature([3072], tf.float32),
'label': tf.FixedLenFeature([], tf.int64),
})
# Convert label from a scalar uint8 tensor to an int32 scalar.
image = features['image']
image = tf.reshape(image, [32, 32, 3])
label = tf.one_hot(tf.cast(features['label'], tf.int32), 10)
return image, label
def generate_batch(
example,
min_queue_examples,
batch_size, shuffle):
"""
Arg:
list of tensors.
"""
num_preprocess_threads = 1
if shuffle:
ret = tf.train.shuffle_batch(
example,
batch_size=batch_size,
num_threads=num_preprocess_threads,
capacity=min_queue_examples + 3 * batch_size,
min_after_dequeue=min_queue_examples)
else:
ret = tf.train.batch(
example,
batch_size=batch_size,
num_threads=num_preprocess_threads,
allow_smaller_final_batch=True,
capacity=min_queue_examples + 3 * batch_size)
return ret
def transform(image):
image = tf.reshape(image, [32, 32, 3])
if FLAGS.aug_trans or FLAGS.aug_flip:
print("augmentation")
if FLAGS.aug_trans:
image = tf.pad(image, [[2, 2], [2, 2], [0, 0]])
image = tf.random_crop(image, [32, 32, 3])
if FLAGS.aug_flip:
image = tf.image.random_flip_left_right(image)
return image
def generate_filename_queue(filenames, data_dir, num_epochs=None):
print("filenames in queue:", filenames)
for i in range(len(filenames)):
filenames[i] = os.path.join(data_dir, filenames[i])
return tf.train.string_input_producer(filenames, num_epochs=num_epochs)