Update fomo_utils.py
Browse files- fomo_utils.py +18 -4
fomo_utils.py
CHANGED
|
@@ -220,8 +220,13 @@ def build_fomo_model(input_size, num_classes, alpha=0.35):
|
|
| 220 |
target_size = input_size // 8
|
| 221 |
cut_layer = None
|
| 222 |
for layer in base.layers:
|
| 223 |
-
|
| 224 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
cut_layer = layer
|
| 226 |
if cut_layer is None:
|
| 227 |
raise ValueError(f"Could not find a layer with spatial size {target_size} in MobileNetV2.")
|
|
@@ -234,6 +239,15 @@ def build_fomo_model(input_size, num_classes, alpha=0.35):
|
|
| 234 |
return tf.keras.Model(inputs, outputs, name="fomo")
|
| 235 |
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
def weighted_sparse_ce(background_weight):
|
| 238 |
def loss_fn(y_true, y_pred):
|
| 239 |
y_true = tf.cast(y_true, tf.int32)
|
|
@@ -260,9 +274,9 @@ class LogCallback(tf.keras.callbacks.Callback):
|
|
| 260 |
self.log_lines.append(line)
|
| 261 |
|
| 262 |
|
| 263 |
-
def train_model(model, train_ds, val_ds, epochs, learning_rate, background_weight, log_lines):
|
| 264 |
model.compile(
|
| 265 |
-
optimizer=
|
| 266 |
loss=weighted_sparse_ce(background_weight),
|
| 267 |
metrics=["accuracy"],
|
| 268 |
)
|
|
|
|
| 220 |
target_size = input_size // 8
|
| 221 |
cut_layer = None
|
| 222 |
for layer in base.layers:
|
| 223 |
+
try:
|
| 224 |
+
shape = layer.output.shape
|
| 225 |
+
except AttributeError:
|
| 226 |
+
continue
|
| 227 |
+
if shape is None or len(shape) != 4:
|
| 228 |
+
continue
|
| 229 |
+
if shape[1] == target_size:
|
| 230 |
cut_layer = layer
|
| 231 |
if cut_layer is None:
|
| 232 |
raise ValueError(f"Could not find a layer with spatial size {target_size} in MobileNetV2.")
|
|
|
|
| 239 |
return tf.keras.Model(inputs, outputs, name="fomo")
|
| 240 |
|
| 241 |
|
| 242 |
+
def get_optimizer(name, learning_rate):
|
| 243 |
+
name = (name or "adamw").lower()
|
| 244 |
+
if name == "adamw":
|
| 245 |
+
return tf.keras.optimizers.AdamW(learning_rate=learning_rate, weight_decay=1e-4)
|
| 246 |
+
if name == "sgd":
|
| 247 |
+
return tf.keras.optimizers.SGD(learning_rate=learning_rate, momentum=0.9)
|
| 248 |
+
return tf.keras.optimizers.Adam(learning_rate=learning_rate)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
def weighted_sparse_ce(background_weight):
|
| 252 |
def loss_fn(y_true, y_pred):
|
| 253 |
y_true = tf.cast(y_true, tf.int32)
|
|
|
|
| 274 |
self.log_lines.append(line)
|
| 275 |
|
| 276 |
|
| 277 |
+
def train_model(model, train_ds, val_ds, epochs, learning_rate, background_weight, log_lines, optimizer_name="adamw"):
|
| 278 |
model.compile(
|
| 279 |
+
optimizer=get_optimizer(optimizer_name, learning_rate),
|
| 280 |
loss=weighted_sparse_ce(background_weight),
|
| 281 |
metrics=["accuracy"],
|
| 282 |
)
|