duyle2408 commited on
Commit
8cf6522
·
verified ·
1 Parent(s): 9fcbc4a

Upload 16 files

Browse files
milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc CHANGED
Binary files a/milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc and b/milk10k_effb2_metadata/__pycache__/training.cpython-314.pyc differ
 
milk10k_effb2_metadata/training.py CHANGED
@@ -114,7 +114,7 @@ def save_checkpoint(
114
  optimizer: torch.optim.Optimizer,
115
  epoch: int,
116
  phase: str,
117
- best_val_loss: float,
118
  class_names: list[str],
119
  label_to_idx: dict[str, int],
120
  metadata_spec: dict[str, Any],
@@ -126,7 +126,7 @@ def save_checkpoint(
126
  "phase": phase,
127
  "model_state": model.state_dict(),
128
  "optimizer_state": optimizer.state_dict(),
129
- "best_val_loss": best_val_loss,
130
  "class_names": class_names,
131
  "label_to_idx": label_to_idx,
132
  "metadata_spec": metadata_spec,
@@ -151,15 +151,15 @@ def train_phase(
151
  metadata_spec: dict[str, Any],
152
  output_dir: Path,
153
  history: list[dict[str, Any]],
154
- best_val_loss: float,
155
  ) -> tuple[int, float]:
156
  if num_epochs <= 0:
157
- return start_epoch, best_val_loss
158
 
159
  encoders_trainable = phase == "finetune"
160
  set_encoder_trainable(model, encoders_trainable)
161
  optimizer = build_optimizer(model, args, encoders_trainable)
162
- scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="min", factor=0.2, patience=2)
163
  scaler = GradScaler("cuda", enabled=args.amp and device.type == "cuda")
164
  use_amp = args.amp and device.type == "cuda"
165
  patience_count = 0
@@ -171,7 +171,7 @@ def train_phase(
171
  criterion.set_epoch(epoch)
172
  train_stats = run_epoch(model, train_loader, criterion, device, optimizer, scaler, use_amp)
173
  val_stats = run_epoch(model, val_loader, criterion, device)
174
- scheduler.step(val_stats["loss"])
175
  row = {
176
  "phase": phase,
177
  "epoch": epoch,
@@ -188,8 +188,8 @@ def train_phase(
188
  f"val_f1={val_stats['f1_macro']:.4f} val_top3={val_stats['top3_accuracy']:.4f}"
189
  )
190
 
191
- if val_stats["loss"] < best_val_loss:
192
- best_val_loss = val_stats["loss"]
193
  patience_count = 0
194
  save_checkpoint(
195
  output_dir / "best.pt",
@@ -197,7 +197,7 @@ def train_phase(
197
  optimizer,
198
  epoch,
199
  phase,
200
- best_val_loss,
201
  class_names,
202
  label_to_idx,
203
  metadata_spec,
@@ -209,7 +209,7 @@ def train_phase(
209
  print(f"Early stopping {phase} at epoch {epoch}")
210
  break
211
 
212
- return start_epoch + num_epochs, best_val_loss
213
 
214
 
215
  def build_model(
@@ -317,7 +317,7 @@ def run_training_split(
317
  print("Note: --class-weight is ignored for --loss milk_lt because milk_lt uses effective-number alpha.")
318
 
319
  history: list[dict[str, Any]] = []
320
- epoch, best_val_loss = train_phase(
321
  "freeze",
322
  args.freeze_epochs,
323
  1,
@@ -332,9 +332,9 @@ def run_training_split(
332
  metadata_spec,
333
  output_dir,
334
  history,
335
- float("inf"),
336
  )
337
- epoch, best_val_loss = train_phase(
338
  "finetune",
339
  args.finetune_epochs,
340
  epoch,
@@ -349,7 +349,7 @@ def run_training_split(
349
  metadata_spec,
350
  output_dir,
351
  history,
352
- best_val_loss,
353
  )
354
 
355
  best_path = output_dir / "best.pt"
@@ -358,14 +358,14 @@ def run_training_split(
358
  model.load_state_dict(checkpoint["model_state"])
359
  y_true, y_prob = predict(model, val_loader, device)
360
  metrics, per_class_df, cm = compute_metrics(y_true, y_prob, class_names)
361
- metrics = {"best_val_loss": float(best_val_loss), **metrics}
362
  with open(output_dir / "metrics.json", "w", encoding="utf-8") as f:
363
  json.dump(json_safe(metrics), f, indent=2)
364
  pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(output_dir / "confusion_matrix.csv")
365
  per_class_df.to_csv(output_dir / "per_class_metrics.csv", index=False)
366
  save_predictions(val_df, y_true, y_prob, class_names, output_dir)
367
  print(
368
- f"Done: best_val_loss={best_val_loss:.4f}, "
369
  f"val_acc={metrics['accuracy']:.4f}, balanced_acc={metrics['balanced_accuracy']:.4f}, "
370
  f"f1_macro={metrics['f1_macro']:.4f}, top3={metrics['top3_accuracy']:.4f}, "
371
  f"auc_macro={metrics['roc_auc_macro_ovr']}"
@@ -429,7 +429,7 @@ def train_kfold(
429
 
430
  def save_kfold_summary(fold_metrics: list[dict[str, Any]], output_dir: Path) -> None:
431
  summary_keys = [
432
- "best_val_loss",
433
  "accuracy",
434
  "balanced_accuracy",
435
  "f1_macro",
 
114
  optimizer: torch.optim.Optimizer,
115
  epoch: int,
116
  phase: str,
117
+ best_val_f1: float,
118
  class_names: list[str],
119
  label_to_idx: dict[str, int],
120
  metadata_spec: dict[str, Any],
 
126
  "phase": phase,
127
  "model_state": model.state_dict(),
128
  "optimizer_state": optimizer.state_dict(),
129
+ "best_val_f1_macro": best_val_f1,
130
  "class_names": class_names,
131
  "label_to_idx": label_to_idx,
132
  "metadata_spec": metadata_spec,
 
151
  metadata_spec: dict[str, Any],
152
  output_dir: Path,
153
  history: list[dict[str, Any]],
154
+ best_val_f1: float,
155
  ) -> tuple[int, float]:
156
  if num_epochs <= 0:
157
+ return start_epoch, best_val_f1
158
 
159
  encoders_trainable = phase == "finetune"
160
  set_encoder_trainable(model, encoders_trainable)
161
  optimizer = build_optimizer(model, args, encoders_trainable)
162
+ scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode="max", factor=0.2, patience=2)
163
  scaler = GradScaler("cuda", enabled=args.amp and device.type == "cuda")
164
  use_amp = args.amp and device.type == "cuda"
165
  patience_count = 0
 
171
  criterion.set_epoch(epoch)
172
  train_stats = run_epoch(model, train_loader, criterion, device, optimizer, scaler, use_amp)
173
  val_stats = run_epoch(model, val_loader, criterion, device)
174
+ scheduler.step(val_stats["f1_macro"])
175
  row = {
176
  "phase": phase,
177
  "epoch": epoch,
 
188
  f"val_f1={val_stats['f1_macro']:.4f} val_top3={val_stats['top3_accuracy']:.4f}"
189
  )
190
 
191
+ if val_stats["f1_macro"] > best_val_f1:
192
+ best_val_f1 = val_stats["f1_macro"]
193
  patience_count = 0
194
  save_checkpoint(
195
  output_dir / "best.pt",
 
197
  optimizer,
198
  epoch,
199
  phase,
200
+ best_val_f1,
201
  class_names,
202
  label_to_idx,
203
  metadata_spec,
 
209
  print(f"Early stopping {phase} at epoch {epoch}")
210
  break
211
 
212
+ return epoch + 1, best_val_f1
213
 
214
 
215
  def build_model(
 
317
  print("Note: --class-weight is ignored for --loss milk_lt because milk_lt uses effective-number alpha.")
318
 
319
  history: list[dict[str, Any]] = []
320
+ epoch, best_val_f1 = train_phase(
321
  "freeze",
322
  args.freeze_epochs,
323
  1,
 
332
  metadata_spec,
333
  output_dir,
334
  history,
335
+ float("-inf"),
336
  )
337
+ epoch, best_val_f1 = train_phase(
338
  "finetune",
339
  args.finetune_epochs,
340
  epoch,
 
349
  metadata_spec,
350
  output_dir,
351
  history,
352
+ best_val_f1,
353
  )
354
 
355
  best_path = output_dir / "best.pt"
 
358
  model.load_state_dict(checkpoint["model_state"])
359
  y_true, y_prob = predict(model, val_loader, device)
360
  metrics, per_class_df, cm = compute_metrics(y_true, y_prob, class_names)
361
+ metrics = {"best_val_f1_macro": float(best_val_f1), **metrics}
362
  with open(output_dir / "metrics.json", "w", encoding="utf-8") as f:
363
  json.dump(json_safe(metrics), f, indent=2)
364
  pd.DataFrame(cm, index=class_names, columns=class_names).to_csv(output_dir / "confusion_matrix.csv")
365
  per_class_df.to_csv(output_dir / "per_class_metrics.csv", index=False)
366
  save_predictions(val_df, y_true, y_prob, class_names, output_dir)
367
  print(
368
+ f"Done: best_val_f1_macro={best_val_f1:.4f}, "
369
  f"val_acc={metrics['accuracy']:.4f}, balanced_acc={metrics['balanced_accuracy']:.4f}, "
370
  f"f1_macro={metrics['f1_macro']:.4f}, top3={metrics['top3_accuracy']:.4f}, "
371
  f"auc_macro={metrics['roc_auc_macro_ovr']}"
 
429
 
430
  def save_kfold_summary(fold_metrics: list[dict[str, Any]], output_dir: Path) -> None:
431
  summary_keys = [
432
+ "best_val_f1_macro",
433
  "accuracy",
434
  "balanced_accuracy",
435
  "f1_macro",