-
Notifications
You must be signed in to change notification settings - Fork 0
/
supcon_semibalanced_ViT.py
356 lines (332 loc) · 10.8 KB
/
supcon_semibalanced_ViT.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
"""Supervised contrastive learning using two CNN encoder types image data, with balanced batching."""
import csv
import os
import tensorflow as tf
from functions import (
custom_data_generator,
find_optimal_threshold,
SupervisedContrastiveLoss,
add_metrics,
add_projection_head,
create_classifier_imgs_only,
create_data_augmentation_module,
create_vit_encoder,
)
# Weights should be loaded from pretext task.
# Image width, batch size
image_width = 224
batch_size = 16
# Data directories
trainDataDir = "D:/HAM10000/train/"
validDataDir = "D:/HAM10000/valid/"
testDataDir = "D:/HAM10000/test/"
# Create balanced training and validation datasets
train_generator = custom_data_generator(
data_dir=trainDataDir,
batch_size=batch_size,
class_0_ratio=0.75,
image_width=image_width,
)
validation_generator = custom_data_generator(
data_dir=validDataDir,
batch_size=batch_size,
class_0_ratio=0.75,
image_width=image_width,
)
# Calculate the number of steps per epoch and validation steps
train_steps_per_epoch = len(os.listdir(os.path.join(trainDataDir, "0"))) + len(
os.listdir(os.path.join(trainDataDir, "1"))
)
val_steps = len(os.listdir(os.path.join(validDataDir, "0"))) + len(
os.listdir(os.path.join(validDataDir, "1"))
)
# Unbalanced test and validation datasets
# Create an ImageDataGenerator for testing data (don't need balanced test sets)
test_datagen = tf.keras.preprocessing.image.ImageDataGenerator()
test_ds = test_datagen.flow_from_directory(
testDataDir,
target_size=(image_width, image_width),
batch_size=batch_size,
class_mode="binary",
shuffle=False,
)
# To select the optimal threshold we will also create a data generator
valid_datagen_unbalanced = tf.keras.preprocessing.image.ImageDataGenerator()
valid_ds_unbalanced = valid_datagen_unbalanced.flow_from_directory(
validDataDir,
target_size=(image_width, image_width),
batch_size=batch_size,
class_mode="binary",
shuffle=False,
)
# ------------------------------------------------------
# Modelling
# ------------------------------------------------------
# --- Hyperparameter configuration ---
input_shape = (image_width, image_width, 3)
learning_rate = 0.001
weight_decay = 0.0001
num_epochs = 100
image_size = 224
# Size of the patches to be extract from the input images
patch_size = 14
num_patches = (image_size // patch_size) ** 2
projection_dim = 64
num_heads = 4
# Size of the transformer layers
transformer_units = [
projection_dim * 2,
projection_dim,
]
transformer_layers = 8
# Size of the dense layers of the final classifier
representation_units = 2048
optimiser = tf.keras.optimizers.Adam(learning_rate=learning_rate)
# Classifer
hiddenUnits = 512
dropoutRate = 0.1
numEpochs = 100
projectionUnits = 128
temperature = 0.1
# Shared functions
# Early stopping on validation loss
callback_EarlyStopping = tf.keras.callbacks.EarlyStopping(
monitor="val_loss", patience=5, restore_best_weights=True
)
# Image augmentation
data_aug = create_data_augmentation_module(RandomRotationAmount=0.5)
# ---------------------------------------------------------------------------------
# Baseline classification models using images only
# ---------------------------------------------------------------------------------
print("\nBaseline ViT classification model.\n")
# Setup encoder
encoder = create_vit_encoder(
data_augmentation=data_aug,
patch_size=patch_size,
num_patches=num_patches,
projection_dim=projection_dim,
transformer_layers=transformer_layers,
num_heads=num_heads,
transformer_units=transformer_units,
input_shape=input_shape,
encoder_name="ViT_encoder",
representation_units=representation_units,
load_weights=True,
weight_location="supcon_malignant_repo/saved_models/encoder_weights_ViT_MSE.h5",
)
encoder.summary()
# Setup classifier
classifier = create_classifier_imgs_only(
encoder_module=encoder,
model_name="ViT_baseline_classifier",
input_shape=input_shape,
hidden_units=hiddenUnits,
dropout_rate=dropoutRate,
optimizer=optimiser,
trainable=True,
)
classifier.summary()
# Define all the callbacks
# Logging
callback_CSVLogger = tf.keras.callbacks.CSVLogger(
"supcon_malignant_repo/CSVLogger/train_baseline_ViT.csv"
)
# Training
history = classifier.fit(
train_generator,
steps_per_epoch=train_steps_per_epoch // batch_size,
epochs=numEpochs,
validation_data=validation_generator,
validation_steps=val_steps // batch_size,
callbacks=[callback_EarlyStopping, callback_CSVLogger],
verbose=2,
)
# Evaluate
print("Evaluate on test data")
csv_file = "supcon_malignant_repo/CSVLogger/test_baseline_ViT.csv"
test_predictions, optimal_threshold, test_metrics, valid_metrics = find_optimal_threshold(
classifier=classifier, valid_dataset=valid_ds_unbalanced, test_dataset=test_ds
)
with open(csv_file, mode="w", newline="") as file:
fieldnames = [
"Threshold",
"AUC",
"Accuracy",
"Precision",
"Recall",
"Specificity",
"F1",
]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow(
{
"Threshold": optimal_threshold,
"AUC": test_metrics["auc"],
"Accuracy": test_metrics["accuracy"],
"Precision": test_metrics["precision"],
"Recall": test_metrics["recall"],
"Specificity": test_metrics["specificity"],
"F1": test_metrics["f1"],
}
)
# Evaluate on validation data
with open(csv_file.replace("test", "valid"), mode="w", newline="") as file:
fieldnames = [
"Threshold",
"AUC",
"Accuracy",
"Precision",
"Recall",
"Specificity",
"F1",
]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow(
{
"Threshold": optimal_threshold,
"AUC": valid_metrics["auc"],
"Accuracy": valid_metrics["accuracy"],
"Precision": valid_metrics["precision"],
"Recall": valid_metrics["recall"],
"Specificity": valid_metrics["specificity"],
"F1": valid_metrics["f1"],
}
)
# -----------------------------------------------------------------------------------
# Supervised contrastive learning model with images only
# -----------------------------------------------------------------------------------
print("\nSupervised contrastive learning classification model using ViT.\n")
# Pre-train the encoder
encoder = create_vit_encoder(
data_augmentation=data_aug,
patch_size=patch_size,
num_patches=num_patches,
projection_dim=projection_dim,
transformer_layers=transformer_layers,
num_heads=num_heads,
transformer_units=transformer_units,
input_shape=input_shape,
encoder_name="ViT_encoder_supcon",
representation_units=representation_units,
load_weights=True,
weight_location="supcon_malignant_repo/saved_models/encoder_weights_ViT_MSE.h5",
)
encoder.summary()
# Add projection head
encoder_with_projection_head = add_projection_head(
encoder_module=encoder,
model_name="ViT_encoder_with_projection_head",
input_shape=input_shape,
projection_units=projectionUnits,
)
encoder_with_projection_head.compile(
optimizer=optimiser,
loss=SupervisedContrastiveLoss(temperature),
)
encoder_with_projection_head.summary()
# Logging
callback_CSVLogger = tf.keras.callbacks.CSVLogger(
"supcon_malignant_repo/CSVLogger/supcon_pretrained_encoder_ViT.csv"
)
# Pre-training encoder
history = encoder_with_projection_head.fit(
train_generator,
steps_per_epoch=train_steps_per_epoch // batch_size,
epochs=numEpochs,
validation_data=validation_generator,
validation_steps=val_steps // batch_size,
callbacks=[callback_EarlyStopping, callback_CSVLogger],
verbose=2,
)
# Train the classifier with the frozen encoder
classifier = create_classifier_imgs_only(
encoder_module=encoder,
model_name="supcon_classifier_ViT_frozen_encoder",
input_shape=input_shape,
hidden_units=hiddenUnits,
dropout_rate=dropoutRate,
optimizer=optimiser,
trainable=False,
)
classifier.summary()
# Logging
callback_CSVLogger = tf.keras.callbacks.CSVLogger(
"supcon_malignant_repo/CSVLogger/supcon_encoder_ViT.csv"
)
# Train the classifier with the frozen encoder
history = classifier.fit(
train_generator,
steps_per_epoch=train_steps_per_epoch // batch_size,
epochs=numEpochs,
validation_data=validation_generator,
validation_steps=val_steps // batch_size,
callbacks=[callback_EarlyStopping, callback_CSVLogger],
verbose=2,
)
# Evaluate
print("Evaluate on test data")
test_predictions, optimal_threshold, test_metrics, valid_metrics = find_optimal_threshold(
classifier=classifier, valid_dataset=valid_ds_unbalanced, test_dataset=test_ds
)
csv_file = "supcon_malignant_repo/CSVLogger/test_supcon_ViT.csv"
with open(csv_file, mode="w", newline="") as file:
fieldnames = [
"Threshold",
"AUC",
"Accuracy",
"Precision",
"Recall",
"Specificity",
"F1",
]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow(
{
"Threshold": optimal_threshold,
"AUC": test_metrics["auc"],
"Accuracy": test_metrics["accuracy"],
"Precision": test_metrics["precision"],
"Recall": test_metrics["recall"],
"Specificity": test_metrics["specificity"],
"F1": test_metrics["f1"],
}
)
# Evaluate on validation data
with open(csv_file.replace("test", "valid"), mode="w", newline="") as file:
fieldnames = [
"Threshold",
"AUC",
"Accuracy",
"Precision",
"Recall",
"Specificity",
"F1",
]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writeheader()
writer.writerow(
{
"Threshold": optimal_threshold,
"AUC": valid_metrics["auc"],
"Accuracy": valid_metrics["accuracy"],
"Precision": valid_metrics["precision"],
"Recall": valid_metrics["recall"],
"Specificity": valid_metrics["specificity"],
"F1": valid_metrics["f1"],
}
)
# -----------------------------------------------------------------------------------
# Adding metrics
# -----------------------------------------------------------------------------------
# Add metrics to csv file
add_metrics(
hist_filelocation="supcon_malignant_repo/CSVLogger/supcon_encoder_ViT.csv",
saved_name="supcon_malignant_repo/CSVLogger/supcon_encoder_ViT_added_metrics.csv",
)
add_metrics(
hist_filelocation="supcon_malignant_repo/CSVLogger/train_baseline_ViT.csv",
saved_name="supcon_malignant_repo/CSVLogger/train_baseline_ViT_added_metrics.csv",
)