-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathtrain.py
244 lines (202 loc) · 8.01 KB
/
train.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"""
Created on Tue Dec 10 19:46:17 2019
@author: Adnene Boumessouer
"""
import os
import argparse
import tensorflow as tf
from tensorflow import keras
from autoencoder.autoencoder import AutoEncoder
from processing.preprocessing import Preprocessor
from processing.utils import printProgressBar as printProgressBar
from processing import utils
from processing import postprocessing
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
"""
Valid combinations for input arguments for architecture, color_mode and loss:
+----------------+----------------+
| Model Architecture |
+----------------+----------------+
| mvtecCAE | ResnetCAE |
| baselineCAE | |
| inceptionCAE | |
========================+================+================+
|| | | |
|| grayscale | ssim, l2 | ssim, l2 |
Color || | | |
Mode ----------------+----------------+----------------+
|| | | |
|| RGB | mssim, l2 | mssim, l2 |
|| | | |
--------+---------------+----------------+----------------+
"""
def check_arguments(architecture, color_mode, loss):
if loss == "mssim" and color_mode == "grayscale":
raise ValueError("MSSIM works only with rgb images")
if loss == "ssim" and color_mode == "rgb":
raise ValueError("SSIM works only with grayscale images")
return
def main(args):
# get parsed arguments from user
input_dir = args.input_dir
architecture = args.architecture
color_mode = args.color
loss = args.loss
batch_size = args.batch
# check arguments
check_arguments(architecture, color_mode, loss)
# get autoencoder
autoencoder = AutoEncoder(input_dir, architecture, color_mode, loss, batch_size)
# load data as generators that yield batches of preprocessed images
preprocessor = Preprocessor(
input_directory=input_dir,
rescale=autoencoder.rescale,
shape=autoencoder.shape,
color_mode=autoencoder.color_mode,
preprocessing_function=autoencoder.preprocessing_function,
)
train_generator = preprocessor.get_train_generator(
batch_size=autoencoder.batch_size, shuffle=True
)
validation_generator = preprocessor.get_val_generator(
batch_size=autoencoder.batch_size, shuffle=True
)
# find best learning rates for training
autoencoder.find_lr_opt(train_generator, validation_generator)
# train
autoencoder.fit(lr_opt=autoencoder.lr_opt)
# save model
autoencoder.save()
if args.inspect:
# -------------- INSPECTING VALIDATION IMAGES --------------
logger.info("generating inspection plots of validation images...")
# create a directory to save inspection plots
inspection_val_dir = os.path.join(autoencoder.save_dir, "inspection_val")
if not os.path.isdir(inspection_val_dir):
os.makedirs(inspection_val_dir)
inspection_val_generator = preprocessor.get_val_generator(
batch_size=autoencoder.learner.val_data.samples, shuffle=False
)
imgs_val_input = inspection_val_generator.next()[0]
filenames_val = inspection_val_generator.filenames
# get reconstructed images (i.e predictions) on validation dataset
logger.info("reconstructing validation images...")
imgs_val_pred = autoencoder.model.predict(imgs_val_input)
# instantiate TensorImages object to compute validation resmaps
tensor_val = postprocessing.TensorImages(
imgs_input=imgs_val_input,
imgs_pred=imgs_val_pred,
vmin=autoencoder.vmin,
vmax=autoencoder.vmax,
method=autoencoder.loss,
dtype="float64",
filenames=filenames_val,
)
# generate and save inspection validation plots
tensor_val.generate_inspection_plots(
group="validation", save_dir=inspection_val_dir
)
# -------------- INSPECTING TEST IMAGES --------------
logger.info("generating inspection plots of test images...")
# create a directory to save inspection plots
inspection_test_dir = os.path.join(autoencoder.save_dir, "inspection_test")
if not os.path.isdir(inspection_test_dir):
os.makedirs(inspection_test_dir)
nb_test_images = preprocessor.get_total_number_test_images()
inspection_test_generator = preprocessor.get_test_generator(
batch_size=nb_test_images, shuffle=False
)
imgs_test_input = inspection_test_generator.next()[0]
filenames_test = inspection_test_generator.filenames
# get reconstructed images (i.e predictions) on validation dataset
logger.info("reconstructing test images...")
imgs_test_pred = autoencoder.model.predict(imgs_test_input)
# instantiate TensorImages object to compute test resmaps
tensor_test = postprocessing.TensorImages(
imgs_input=imgs_test_input,
imgs_pred=imgs_test_pred,
vmin=autoencoder.vmin,
vmax=autoencoder.vmax,
method=autoencoder.loss,
dtype="float64",
filenames=filenames_test,
)
# generate and save inspection test plots
tensor_test.generate_inspection_plots(
group="test", save_dir=inspection_test_dir
)
logger.info("done.")
return
if __name__ == "__main__":
# create parser
parser = argparse.ArgumentParser(
description="Train an AutoEncoder on an image dataset.",
epilog="Example usage: python3 train.py -d mvtec/capsule -a mvtec2 -b 8 -l ssim -c grayscale",
)
parser.add_argument(
"-d",
"--input-dir",
type=str,
required=True,
metavar="",
help="directory containing training images",
)
parser.add_argument(
"-a",
"--architecture",
type=str,
required=False,
metavar="",
choices=["mvtecCAE", "baselineCAE", "inceptionCAE", "resnetCAE", "skipCAE"],
default="mvtec2",
help="architecture of the model to use for training: 'mvtecCAE', 'baselineCAE', 'inceptionCAE', 'resnetCAE' or 'skipCAE'",
)
parser.add_argument(
"-c",
"--color",
type=str,
required=False,
metavar="",
choices=["rgb", "grayscale"],
default="grayscale",
help="color mode for preprocessing images before training: 'rgb' or 'grayscale'",
)
parser.add_argument(
"-l",
"--loss",
type=str,
required=False,
metavar="",
choices=["mssim", "ssim", "l2"],
default="ssim",
help="loss function to use for training: 'mssim', 'ssim' or 'l2'",
)
parser.add_argument(
"-b",
"--batch",
type=int,
required=False,
metavar="",
default=8,
help="batch size to use for training",
)
parser.add_argument(
"-i",
"--inspect",
action="store_true",
help="generate inspection plots after training",
)
args = parser.parse_args()
if tf.test.is_gpu_available():
logger.info("GPU was detected...")
else:
logger.info("No GPU was detected. CNNs can be very slow without a GPU...")
logger.info("Tensorflow version: {} ...".format(tf.__version__))
logger.info("Keras version: {} ...".format(keras.__version__))
main(args)
# Examples of commands to initiate training with mvtec architecture
# python3 train.py -d mvtec/capsule -a mvtecCAE -b 8 -l ssim -c grayscale --inspect
# python3 train.py -d mvtec/hazelnut -a resnetCAE -b 8 -l mssim -c rgb --inspect
# python3 train.py -d mvtec/pill -a inceptionCAE -b 8 -l mssim -c rgb --inspect