Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch augmentations on and off in the config. #282

Merged
merged 2 commits into from
Oct 1, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 15 additions & 14 deletions plugins/models/efficientnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
from deepprofiler.learning.model import DeepProfilerModel
from deepprofiler.imaging.augmentations import AugmentationLayer

tf.compat.v1.disable_v2_behavior()
#tf.compat.v1.disable_v2_behavior()
#tf.config.run_functions_eagerly(False)


class ModelClass(DeepProfilerModel):
Expand Down Expand Up @@ -33,7 +34,7 @@ def get_model(self, config, input_image=None, weights=None, include_top=False):
error_msg = str(num_layers) + " conv_blocks not in " + SM
assert num_layers in supported_models.keys(), error_msg

if self.is_training and weights is None:
if self.is_training and weights is None and self.config["train"]['model'].get('augmentations') is True:
input_image = AugmentationLayer()(input_image)

model = supported_models[num_layers](
Expand All @@ -53,8 +54,7 @@ def define_model(self, config, dset):

optimizer = tf.compat.v1.keras.optimizers.SGD(lr=config["train"]["model"]["params"]["learning_rate"], momentum=0.9,
nesterov=True)
#loss_func = "categorical_crossentropy"
loss_func = tf.compat.v1.keras.losses.CategoricalCrossentropy(label_smoothing=0.2)
loss_func = tf.compat.v1.keras.losses.CategoricalCrossentropy(label_smoothing=0.2) # TODO:parameterize?

if self.is_training is False and "use_pretrained_input_size" in config["profile"].keys():
input_tensor = tf.compat.v1.keras.layers.Input(
Expand All @@ -65,39 +65,40 @@ def define_model(self, config, dset):
input_shape = (
config["dataset"]["locations"]["box_size"], # height
config["dataset"]["locations"]["box_size"], # width
len(config["dataset"]["images"][
"channels"]) # channels
len(config["dataset"]["images"]["channels"]) # channels
)
input_image = tf.compat.v1.keras.layers.Input(input_shape)
model = self.get_model(config, input_image=input_image)
features = tf.compat.v1.keras.layers.GlobalAveragePooling2D(name="pool5")(model.layers[-1].output)
# 2. Create an output embedding for each target
class_outputs = []

y = tf.compat.v1.keras.layers.Dense(config["num_classes"], activation="softmax", name="ClassProb")(features)
y = tf.compat.v1.keras.layers.Dense(len(dset.targets[0].values), activation="softmax", name="ClassProb")(features)
class_outputs.append(y)

# 4. Create and compile model
model = tf.compat.v1.keras.models.Model(inputs=input_image, outputs=class_outputs)


## Added weight decay following tricks reported in:
## https://github.com/keras-team/keras/issues/2717
regularizer = tf.compat.v1.keras.regularizers.l2(0.00001)
for layer in model.layers:
if hasattr(layer, "kernel_regularizer"):
setattr(layer, "kernel_regularizer", regularizer)

model = tf.compat.v1.keras.models.model_from_json(
model.to_json(),
{'AugmentationLayer': AugmentationLayer}
)
if self.config["train"]["model"].get("augmentations") is True:
model = tf.compat.v1.keras.models.model_from_json(
model.to_json(),
{'AugmentationLayer': AugmentationLayer}
)
else:
model = tf.compat.v1.keras.models.model_from_json(model.to_json())

return model, optimizer, loss_func

def copy_pretrained_weights(self):
base_model = self.get_model(self.config, weights="imagenet")
lshift = self.is_training # Shift one layer to accommodate the AugmentationLayer
lshift = self.feature_model.layers[1].name == 'augmentation_layer' # Shift one layer to accommodate the AugmentationLayer

# => Transfer all weights except conv1.1
total_layers = len(base_model.layers)
Expand All @@ -114,7 +115,7 @@ def copy_pretrained_weights(self):

for i in range(new_weights.shape[2]):
j = i % available_channels
new_weights[:,:,i,:] = weights[0][:,:,j,:]
new_weights[:, :, i, :] = weights[0][:, :, j, :]

weights_array = [new_weights]
if len(weights) > 1:
Expand Down
24 changes: 14 additions & 10 deletions plugins/models/resnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def get_model(self, config, input_image=None, weights=None, pooling=None, includ
num_layers = config["train"]["model"]["params"]["conv_blocks"]
error_msg = str(num_layers) + " conv_blocks not in " + SM
assert num_layers in supported_models.keys(), error_msg
if self.is_training and weights is None:
if self.is_training and weights is None and self.config["train"]['model'].get('augmentations') is True:
input_image = AugmentationLayer()(input_image)
if pooling is not None:
model = supported_models[num_layers](input_tensor=input_image, pooling=pooling, include_top=include_top,
Expand Down Expand Up @@ -92,26 +92,30 @@ def define_model(self, config, dset):
if hasattr(layer, "kernel_regularizer"):
setattr(layer, "kernel_regularizer", regularizer)

model = tf.compat.v1.keras.models.model_from_json(
model.to_json(),
{'AugmentationLayer': AugmentationLayer}
)
if self.config["train"]["model"].get("augmentations") is True:
model = tf.compat.v1.keras.models.model_from_json(
model.to_json(),
{'AugmentationLayer': AugmentationLayer}
)
else:
model = tf.compat.v1.keras.models.model_from_json(model.to_json())


return model, optimizer, loss_func


## Support for ImageNet initialization
def copy_pretrained_weights(self):
base_model = self.get_model(self.config, weights="imagenet")
lshift = int(self.is_training) # Shift one layer to accommodate the AugmentationLayer
lshift = self.feature_model.layers[1].name == 'augmentation_layer' # Shift one layer to accommodate the AugmentationLayer

# => Transfer all weights except conv1.1
total_layers = len(base_model.layers)
for i in range(3,total_layers):
for i in range(3, total_layers):
if len(base_model.layers[i].weights) > 0:
print("Setting pre-trained weights: {:.2f}%".format((i/total_layers)*100), end="\r")
self.feature_model.layers[i + lshift].set_weights(base_model.layers[i].get_weights())

# => Replicate filters of first layer as needed
weights = base_model.layers[2].get_weights()
available_channels = weights[0].shape[2]
Expand All @@ -120,10 +124,10 @@ def copy_pretrained_weights(self):

for i in range(new_weights.shape[2]):
j = i % available_channels
new_weights[:,:,i,:] = weights[0][:,:,j,:]
new_weights[:, :, i, :] = weights[0][:, :, j, :]

weights_array = [new_weights]
if len(weights) > 1:
if len(weights) > 1:
weights_array += weights[1:]

self.feature_model.layers[2 + lshift].set_weights(weights_array)
Expand Down
1 change: 1 addition & 0 deletions tests/files/config/test.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
},
"model": {
"name": "cnn",
"augmentations": false,
"crop_generator": "crop_generator",
"metrics": ["accuracy"],
"epochs": 5,
Expand Down