-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_LCL_GCL.py
236 lines (189 loc) · 9.58 KB
/
train_LCL_GCL.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
from LCL_GCL_module import global_enc_proj, local_enc_proj
from sklearn.model_selection import KFold, StratifiedKFold
from sklearn.model_selection import train_test_split
from Losses import *
from LCOL_GCOL_loader import DCMDataFrameIterator
save_dir = '/FastData/'
##### Encoder Projector weights ###
def get_model_nameA(k):
return 'SupCon_ord'+str(k)+'.h5'
def get_model_nameC(k):
return 'Local_SupCon+dist_' + str(k) + '.h5'
### Regression Network/ To check individual performance of Glbobal Module######
def get_model_nameB(k):
return 'SupCon_ord_Class+_'+str(k)+'.h5'
def get_model_nameD(k):
return 'Local_SupCon+dist_Class' + str(k) + '.h5'
# augmentation parameters
train_augmentation_parameters = dict(
rotation_range=15,
shear_range=0.05,
width_shift_range=0.05,
height_shift_range=0.05,
fill_mode='constant',
cval=0)
test_augmentation_parameters = dict(
rescale=0.0,
)
# training parameters
BATCH_SIZE = 16
CLASS_MODE = 'raw'
COLOR_MODE = 'rgb'
TARGET_SIZE = (320, 320)
SEED = 7
train_consts = {
'seed': SEED,
'batch_size': BATCH_SIZE,
'class_mode': CLASS_MODE,
'color_mode': COLOR_MODE,
'target_size': TARGET_SIZE,
'subset': 'training'
}
test_consts = {
'batch_size': 1, # should be 1 in testing
'class_mode': CLASS_MODE,
'color_mode': COLOR_MODE,
'target_size': TARGET_SIZE, # resize input images
'shuffle': False
}
############### Train GLobal Contrastive Learning Module #######################
fold_var = 1
Kkfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=3)
for train_index, val_index in Kkfold.split(np.zeros(1914),Y):
train_df = df.iloc[train_index]
test_df = df.iloc[val_index]
train_df, valid_df = train_test_split(train_df, test_size=0.2)
train_data_generator = DCMDataFrameIterator(dataframe=train_df,
x_col='fileName',
y_col='labels',
image_data_generator=train_augmenter,
**train_consts, shuffle = True)
valid_data_generator = DCMDataFrameIterator(dataframe=valid_df,
x_col='fileName',
y_col='labels',
image_data_generator=test_augmenter,
**test_consts)
test_generator = DCMDataFrameIterator(dataframe=test_df,
x_col='fileName',
y_col='labels',
image_data_generator=test_augmenter,
**test_consts)
filenames = test_generator.filenames
nb_samples = len(filenames)
###################### Global COntarstive Module Training ################
model = global_enc_proj()
model.compile(optimizer=optimizers.RMSprop(learning_rate=3e-4),
loss=SupervisedContrastiveLoss(temperature=0.2), )
checkpoint = keras.callbacks.ModelCheckpoint(save_dir + get_model_nameA(fold_var),
monitor='loss', verbose=1,
save_best_only=True, mode='min')
reduce_lr = keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.5,
patience=7, min_lr=1e-7)
es = keras.callbacks.EarlyStopping(monitor='loss', patience=15)
history = model.fit(train_data_generator,
epochs=200,
verbose=2, callbacks=[checkpoint,reduce_lr,es ]
)
################ Regression Module ##########################
model.load_weights(save_dir+get_model_nameA(fold_var))
mC = tf.keras.Model(inputs = model.input, outputs = model.layers[-4].output) ### Discard Projection Layers
mC.trainable = False
in_fea = mC.output
features = Dense(1280, activation="relu",)(in_fea)
features = Dropout(0.4)(features)
features = Dense(128, activation="relu",)(features)
features = Dropout(0.2)(features)
outputs = Dense(1, activation="linear")(features)
model1 = keras.Model(inputs=mC.input, outputs=outputs)
for i, w in enumerate(model1.weights):
split_name = w.name.split('/')
new_name = split_name[0] + '_' + str(i) + '/' + split_name[1] + '_' + str(i)
model1.weights[i]._handle_name = new_name
model1.compile(
optimizer=optimizers.RMSprop(learning_rate=3e-4),
loss=root_mean_squared_error,
metrics='mean_squared_error',
)
reduce_lr = keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5,
patience=10, min_lr=1e-7)
checkpoint = keras.callbacks.ModelCheckpoint(save_dir + get_model_nameB(fold_var),
monitor='val_loss', verbose=1,
save_best_only=True, mode='min')
es = keras.callbacks.EarlyStopping(monitor='val_loss', patience=20)
callbacks_list = [reduce_lr, es, checkpoint]
# callbacks_list = [reduce_lr,es]
history = model1.fit(train_data_generator,
validation_data=valid_data_generator,
epochs=75,
verbose=2, callbacks=callbacks_list
)
fold_var += 1
######## Train Local Contrastive Block #############
fold_var = 1
Kkfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=3)
for train_index, val_index in Kkfold.split(np.zeros(1914), Y):
train_df = df.iloc[train_index]
test_df = df.iloc[val_index]
train_df, valid_df = train_test_split(df, test_size=0.2)
train_data_generator = DCMDataFrameIterator(dataframe=train_df,
x_col='fileName',
y_col='labels',
image_data_generator=train_augmenter,
**train_consts, shuffle=True)
valid_data_generator = DCMDataFrameIterator(dataframe=valid_df,
x_col='fileName',
y_col='labels',
image_data_generator=test_augmenter,
**test_consts)
test_generator = DCMDataFrameIterator(dataframe=test_df,
x_col='fileName',
y_col='labels',
image_data_generator=test_augmenter,
**test_consts)
filenames = test_generator.filenames
model = local_enc_proj()
###################### Local COntarstive Module Training ################
model.compile(optimizer=optimizers.RMSprop(learning_rate=3e-4),
loss=SupervisedContrastiveLoss(temperature=0.2), )
checkpoint = keras.callbacks.ModelCheckpoint(save_dir + get_model_nameC(fold_var),
monitor='loss', verbose=1,
save_best_only=True, mode='min')
reduce_lr = keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.5,
patience=7, min_lr=1e-7)
es = keras.callbacks.EarlyStopping(monitor='loss', patience=15)
history = model.fit(train_data_generator,
epochs=200,
verbose=2, callbacks=[checkpoint,reduce_lr,es ]
)
################### Regression Network #################
model.load_weights(save_dir + get_model_nameC(fold_var))
mC = tf.keras.Model(inputs=model.input, outputs=model.layers[-4].output)
in_fea = mC.output
features = Dense(1280, activation="relu", name='d_1')(in_fea)
features = Dropout(0.4)(features)
features = Dense(128, activation="relu", name='d_2')(features)
features = Dropout(0.2)(features)
outputs = Dense(1, activation="linear", name='final_output')(features)
model1 = keras.Model(inputs=mC.input, outputs=outputs)
for i, w in enumerate(model1.weights):
split_name = w.name.split('/')
new_name = split_name[0] + '_' + str(i) + '/' + split_name[1] + '_' + str(i)
model1.weights[i]._handle_name = new_name
model1.compile(
optimizer=optimizers.RMSprop(learning_rate=3e-4),
loss=root_mean_squared_error,
metrics='mean_squared_error',
)
reduce_lr = keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5,
patience=10, min_lr=1e-7)
checkpoint = keras.callbacks.ModelCheckpoint(save_dir + get_model_nameD(fold_var),
monitor='val_loss', verbose=1,
save_best_only=True, mode='min')
es = keras.callbacks.EarlyStopping(monitor='val_loss', patience=20)
callbacks_list = [reduce_lr, es, checkpoint]
history = model1.fit(train_data_generator,
validation_data=valid_data_generator,
epochs=75,
verbose=2, callbacks=callbacks_list
)
fold_var += 1