-
Notifications
You must be signed in to change notification settings - Fork 3
/
data_utils.py
175 lines (140 loc) · 6.34 KB
/
data_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
import numpy as np
import os
from tensorflow.keras.preprocessing import image
import copy
import random
import tensorflow as tf
import pandas as pd
import tensorflow as tf
from tensorflow.keras import backend as K
AUTOTUNE = tf.data.experimental.AUTOTUNE
def generate_ids(data_files: str, label_files = '', bin_by_sequence=True, inference=False):
data_list = []
labels_list = []
sequence_ids = sorted(os.listdir(data_files))
label_ids = [x + ".txt" for x in sequence_ids]
for sequence, label in zip(sequence_ids, label_ids):
samples = sorted(os.listdir(os.path.join(data_files, sequence)))
if inference == False:
labels = pd.read_csv(os.path.join(label_files,label),
delimiter=',',
skiprows=0,
names=('id','x','y','z'),
dtype={'id':str})
labels.set_index('id', inplace=True)
targets_list = []
images = []
for sample in samples:
sample_name = os.path.splitext(sample)[0]
sample_id = sequence + "_" + sample_name
images.append(os.path.join(data_files, sequence, sample))
if inference == False:
targets_list.append(labels.loc[[sample_name]].values[0])
data_list.append(images)
if inference ==False:
labels_list.append(targets_list)
if bin_by_sequence==False:
flat_data_list = [item for sublist in data_list for item in sublist]
flat_labels_list = [item for sublist in labels_list for item in sublist]
return flat_data_list, flat_labels_list
return data_list, labels_list
def to_supervised(train, labels='', n_input=50, n_out=5, inference=False):
X, y = list(), list()
for i in range(len(train)):
data = train[i]
in_start = 0
# step over the entire history one time step at a time
for _ in range(len(data)):
# define the end of the input sequence
in_end = in_start + n_input
out_end = in_end + n_out
# ensure we have enough data for this instance
lbls = []
if out_end <= len(data):
X.append(data[in_start:in_end])
if inference == False:
lbls = labels[i][in_end:out_end]
y.append(lbls)
# move along one time step
in_start += 1
return np.array(X), np.array(y)
def euclidean_distance(y_true, y_pred):
"""
Compute average euclidean distance
:param y_true: list of ground truth labels
:param y_pred: list of predicted labels
:return: euclidean distance
"""
return K.mean(K.sqrt(K.sum(K.square(y_true - y_pred), axis=1, keepdims=True)))
def distributed_euclidean_distance(y_true, y_pred):
"""
Compute average euclidean distance for distributed strategy training
:param y_true: list of ground truth labels
:param y_pred: list of predicted labels
:return: euclidean distance
"""
per_example_loss = K.sqrt(K.sum(K.square(y_true - y_pred), axis=1, keepdims=True))
return tf.nn.compute_average_loss(per_example_loss)
@tf.function
def load_and_preprocess_image(path):
"""
Loads and normalizes an image
:param path: path to image file
:return: normalized image tensor
"""
image = tf.io.read_file(path)
image = tf.image.decode_png(image, channels=1)
image = tf.image.convert_image_dtype(image, tf.float32)
# image = tf.image.resize(image, [HEIGHT, WIDTH])
image /= 255.0
return image
def load_sequence(seq):
imgs = tf.map_fn(
load_and_preprocess_image, seq, dtype=tf.float32, parallel_iterations=10)
return imgs
def configure_for_performance(ds, buffer_size=1000, batch_size=16, enable_cache = False, shuffle=True, repeat=True):
if enable_cache == True:
ds = ds.cache()
if shuffle == True:
ds = ds.shuffle(buffer_size=buffer_size, reshuffle_each_iteration=True)
ds = ds.batch(batch_size)
if repeat == True:
ds = ds.repeat()
ds = ds.prefetch(buffer_size=AUTOTUNE)
return ds
def prepare_dataset(x, y, sequence=False, buffer_size=1000, batch_size=16, enable_cache=False, inference=False):
images_dataset = tf.data.Dataset.from_tensor_slices(x)
if inference == False:
labels_dataset = tf.data.Dataset.from_tensor_slices(y)
if sequence == True:
images_dataset = images_dataset.map(load_sequence, num_parallel_calls=AUTOTUNE)
else:
images_dataset = images_dataset.map(load_and_preprocess_image, num_parallel_calls=AUTOTUNE)
if inference == False:
dataset = tf.data.Dataset.zip((images_dataset, labels_dataset))
else:
dataset = images_dataset
dataset = configure_for_performance(dataset,
buffer_size=buffer_size,
batch_size=batch_size,
enable_cache = enable_cache,
shuffle = not inference,
repeat = not inference)
return dataset
def get_dataset(base_path, sequence=False, buffer_size=1000, batch_size=16, inference=False, seq_input_length=50):
data_path = os.path.join(base_path, 'sequences')
labels_path = os.path.join(base_path, 'labels')
n_out = 0 if inference else 5
data_paths_list, labels_list = generate_ids( data_path, labels_path, bin_by_sequence=sequence, inference=inference)
print(len(data_paths_list))
if sequence == True:
x, y = to_supervised(data_paths_list, labels_list, n_input=seq_input_length, n_out=n_out, inference=inference)
print(len(x))
dataset = prepare_dataset(x, y, sequence=True, buffer_size=buffer_size, batch_size = batch_size, enable_cache=False, inference=inference)
samples = len(x)
else:
dataset = prepare_dataset(data_paths_list, labels_list, sequence=False, buffer_size=buffer_size, batch_size = batch_size, enable_cache=True)
samples = len(data_paths_list)
if inference == True:
samples = x
return (dataset, samples)