-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomCallbacks.py
190 lines (159 loc) · 6.68 KB
/
CustomCallbacks.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
import io
import warnings
import PIL
import PIL.Image
import numpy as np
import tensorflow as tf
from keras.callbacks import Callback
from ModelConfig import *
from Huffman import huffman_coding
class PredictCallback(Callback):
def __init__(self, generator):
self.generator = generator
def on_epoch_end(self, epoch, logs={}):
imgs = self.generator[0][0]
img = PIL.Image.fromarray(np.uint8(imgs[0] * 255))
img.show()
imgs = self.model.predict(imgs)
img = PIL.Image.fromarray(np.uint8(imgs[0] * 255))
img.show()
class HuffmanCallback(Callback):
def __init__(self, data):
self.data = data
def on_epoch_begin(self, epoch, logs={}):
codes = self.model.predict(self.data)[0]
codes = np.reshape(
codes, (codes.shape[0], codes.shape[1] * codes.shape[2] * codes.shape[3]))
codes = codes.astype(np.int64)
compression_rate = []
for idx in range(codes.shape[0]):
mapping, original_size, compressed_size = huffman_coding(
codes[idx])
compression_rate += [compressed_size / original_size]
print("[huffman] average compression rate : {}".format(
np.mean(compression_rate)))
class EncoderCheckpoint(Callback):
""" Same as ModelCheckpoint but for encoder
"""
def __init__(self, filepath, monitor='val_loss', verbose=0,
save_best_only=False, save_weights_only=False,
mode='auto', period=1):
super(EncoderCheckpoint, self).__init__()
self.monitor = monitor
self.verbose = verbose
self.filepath = filepath
self.save_best_only = save_best_only
self.save_weights_only = save_weights_only
self.period = period
self.epochs_since_last_save = 0
if mode not in ['auto', 'min', 'max']:
warnings.warn('EncoderCheckpoint mode %s is unknown, '
'fallback to auto mode.' % (mode),
RuntimeWarning)
mode = 'auto'
if mode == 'min':
self.monitor_op = np.less
self.best = np.Inf
elif mode == 'max':
self.monitor_op = np.greater
self.best = -np.Inf
else:
if 'acc' in self.monitor or self.monitor.startswith('fmeasure'):
self.monitor_op = np.greater
self.best = -np.Inf
else:
self.monitor_op = np.less
self.best = np.Inf
def on_epoch_end(self, epoch, logs=None):
logs = logs or {}
self.epochs_since_last_save += 1
if self.epochs_since_last_save >= self.period:
self.epochs_since_last_save = 0
filepath = self.filepath.format(epoch=epoch + 1, **logs)
if self.save_best_only:
current = logs.get(self.monitor)
if current is None:
warnings.warn('Can save best model only with %s available, '
'skipping.' % (self.monitor), RuntimeWarning)
else:
if self.monitor_op(current, self.best):
if self.verbose > 0:
print('\nEpoch %05d: %s improved from %0.5f to %0.5f,'
' saving model to %s'
% (epoch + 1, self.monitor, self.best,
current, filepath))
self.best = current
if self.save_weights_only:
self.model.save_weights(filepath, overwrite=True)
# self.model.layers[1].save_weights(filepath, overwrite=True)
else:
# self.model.layers[1].save(filepath, overwrite=True)
self.model.save(filepath, overwrite=True)
else:
if self.verbose > 0:
print('\nEpoch %05d: %s did not improve' %
(epoch + 1, self.monitor))
else:
if self.verbose > 0:
print('\nEpoch %05d: saving model to %s' %
(epoch + 1, filepath))
if self.save_weights_only:
# self.model.layers[1].save_weights(filepath, overwrite=True)
self.model.save_weights(filepath, overwrite=True)
else:
self.model.save(filepath, overwrite=True)
# self.model.layers[1].save(filepath, overwrite=True)
def make_image(tensor):
height, width, channel = tensor.shape
image = PIL.Image.fromarray(tensor)
output = io.BytesIO()
image.save(output, format='PNG')
image_string = output.getvalue()
output.close()
return tf.Summary.Image(height=height,
width=width,
colorspace=channel,
encoded_image_string=image_string)
def image_to_input(path):
img = PIL.Image.open(path)
img_img = img.resize(img_input_shape[0:2], PIL.Image.ANTIALIAS)
img = np.asarray(img_img) / 255
img = img.reshape(1, *img_input_shape)
return img
def output_to_tf_img(output):
output = np.uint8(output * 255)
output = output.reshape(*img_input_shape)
output_img = make_image(output)
# return tf.summary.image("Reconstruction", output)
return output_img
class TensorBoardImage(Callback):
def __init__(self, tag, test_list, logs_path, save_img=False, exp_path=None):
super().__init__()
self.tag = tag
self.logs_path = logs_path
self.test_list = test_list
self.exp_path = exp_path
self.save_img = save_img
def on_epoch_end(self, epoch, logs=None):
summaries = []
for idx, img_name in enumerate(self.test_list[:10]):
path = dataset_path + "/" + test_dir + "/" + img_name
input = image_to_input(path)
output = self.model.predict(input)[1]
output_img = output_to_tf_img(output)
if self.save_img:
img = PIL.Image.fromarray(np.uint8(output[0] * 255))
file_name = img_name.split('.')[0] + "_" + str(epoch) + ".png"
img.save(self.exp_path + "/" + file_name)
summary = tf.Summary.Value(
tag=self.tag + "_" + str(img_name), image=output_img)
summaries.append(summary)
big_sum = tf.Summary(value=summaries)
writer = tf.summary.FileWriter(self.logs_path)
writer.add_summary(big_sum, epoch)
# function for learning scheduler
def schedule(epoch):
if epoch < 50:
return 1e-4
else:
return 5e-5