Instructions to use haresh2792005/MFAF-Net with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MediaPipe
How to use haresh2792005/MFAF-Net with MediaPipe:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Download train_mfaf_net.py from haresh2792005/MFAF-Net: direct link, hf CLI and curl.
- Browser
- Download file 21.4 kB
-
https://huggingface.co/haresh2792005/MFAF-Net/resolve/main/train_mfaf_net.py
- Command line
-
hf download hf://haresh2792005/MFAF-Net/train_mfaf_net.py
-
curl -L -o train_mfaf_net.py https://huggingface.co/haresh2792005/MFAF-Net/resolve/main/train_mfaf_net.py
21.4 kB
| """ | |
| train_mfaf_net.py — End-to-End Training & Evaluation Script for MFAF-Net | |
| Trains the Multimodal Facial Analysis and Feature-guided Network (MFAFNetModel) | |
| on the uploaded `complete_plasticSurgery_dataset` (supporting procedure folders | |
| such as eyebrow, eyelid, eyes, facelit, facial, nose, as well as before/after pairs | |
| and optional CSV/XLSX patient metadata). | |
| Outputs: | |
| - models/mfaf_net_best.pt (best PyTorch model checkpoint) | |
| - models/training_history.json (epoch-by-epoch metrics & summary) | |
| - static/results/training_curves.png (conference-paper training/val curves) | |
| Usage: | |
| python train_mfaf_net.py | |
| python train_mfaf_net.py --epochs 40 --batch-size 16 | |
| """ | |
| import os | |
| import json | |
| import time | |
| import argparse | |
| import numpy as np | |
| import cv2 | |
| import matplotlib | |
| matplotlib.use('Agg') | |
| import matplotlib.pyplot as plt | |
| import torch | |
| import torch.nn as nn | |
| from torch.utils.data import TensorDataset, DataLoader | |
| from mfaf_net.dataset_loader import DatasetLoader, SUPPORTED_PROCEDURES | |
| from mfaf_net.module1_feature_extraction import ( | |
| FaceLandmarkExtractor, | |
| compute_measurements, | |
| ) | |
| from mfaf_net.module2_patient_analysis import analyze_patient, PROCEDURES | |
| from mfaf_net.module4_simulation import _apply_displacements, _piecewise_affine_warp | |
| from mfaf_net.model_arch import ( | |
| MFAFNetModel, | |
| DEFAULT_MODELS_DIR, | |
| DEFAULT_CHECKPOINT_PATH, | |
| prepare_model_inputs, | |
| ) | |
| from skimage.metrics import structural_similarity, peak_signal_noise_ratio | |
| def _extract_landmarks_and_measurements(image_bgr: np.ndarray, extractor: FaceLandmarkExtractor) -> tuple: | |
| """Extract 468 landmarks and anthropometric measurements from a BGR image.""" | |
| landmarks = extractor.extract(image_bgr) | |
| if landmarks is None: | |
| return None, None | |
| return landmarks, compute_measurements(landmarks) | |
| def _build_metadata_lookup(meta_rows: list) -> dict: | |
| """Index optional metadata spreadsheet rows by image filename.""" | |
| lookup = {} | |
| for row in meta_rows: | |
| if not isinstance(row, dict): | |
| continue | |
| for key in ('image', 'image_path', 'filename', 'file', 'BeforeImage', 'before_image', 'id', 'PatientID'): | |
| val = row.get(key) | |
| if val: | |
| stem = os.path.splitext(os.path.basename(str(val)))[0].lower() | |
| lookup[stem] = row | |
| lookup[os.path.basename(str(val)).lower()] = row | |
| return lookup | |
| def build_training_samples(data_dir: str, max_samples: int = 0) -> dict: | |
| """ | |
| Scan the dataset directory, extract MediaPipe 468-point landmarks, | |
| pair them with patient metadata, and build tensors for training. | |
| """ | |
| loader = DatasetLoader(data_dir) | |
| if not loader.exists(): | |
| raise FileNotFoundError( | |
| f"Dataset directory not found at '{loader.data_dir}'. " | |
| "Ensure complete_plasticSurgery_dataset is placed inside 'data/'." | |
| ) | |
| stats = loader.get_stats() | |
| print(f"Dataset root: {stats['data_root']}") | |
| print(f"Total images: {stats['total_images']}") | |
| print(f"Total pairs: {stats['total_pairs']}") | |
| print(f"Categories found: {list(stats['by_procedure'].keys())}") | |
| all_items = loader.get_all_images() | |
| meta_lookup = _build_metadata_lookup(loader.get_metadata()) | |
| samples_to_process = [] | |
| paired_before_paths = set() | |
| paired_all_paths = set() | |
| for proc in SUPPORTED_PROCEDURES: | |
| for b_path, a_path in loader.get_pairs(procedure=proc): | |
| paired_before_paths.add(b_path) | |
| paired_all_paths.add(b_path) | |
| paired_all_paths.add(a_path) | |
| samples_to_process.append({'before': b_path, 'after': a_path, 'procedure': proc}) | |
| for item in all_items: | |
| if item['path'] not in paired_all_paths: | |
| samples_to_process.append({ | |
| 'before': item['path'], | |
| 'after': None, | |
| 'procedure': item['procedure'], | |
| 'raw_category': item.get('raw_category', item['procedure']), | |
| }) | |
| if not samples_to_process: | |
| raise RuntimeError( | |
| "No recognizable procedure images found. Expected folders such as " | |
| "eyebrow, eyelid, eyes, facelit, facial, nose inside data/." | |
| ) | |
| if max_samples > 0: | |
| samples_to_process = samples_to_process[:max_samples] | |
| print(f"\nExtracting facial landmarks from {len(samples_to_process)} samples...") | |
| X_lm, X_meas, X_pf, Y_delta, Y_proc, val_image_paths, val_after_paths = [], [], [], [], [], [], [] | |
| skipped = 0 | |
| paired_targets = 0 | |
| prior_targets = 0 | |
| proc_counts = {p: 0 for p in PROCEDURES} | |
| with FaceLandmarkExtractor(min_detection_confidence=0.45) as face_mesh: | |
| for idx, entry in enumerate(samples_to_process, 1): | |
| img_path = entry['before'] | |
| proc = entry['procedure'] | |
| img = cv2.imread(img_path) | |
| if img is None: | |
| skipped += 1 | |
| continue | |
| h, w = img.shape[:2] | |
| lm_before, meas = _extract_landmarks_and_measurements(img, face_mesh) | |
| if lm_before is None: | |
| skipped += 1 | |
| continue | |
| # Lookup or default patient metadata | |
| fname = os.path.basename(img_path).lower() | |
| stem = os.path.splitext(fname)[0] | |
| row = meta_lookup.get(fname) or meta_lookup.get(stem) or {} | |
| age = str(row.get('age', row.get('Age', 30))) | |
| sex = str(row.get('sex', row.get('Sex', 'Female'))) | |
| skin = str(row.get('skin_type', row.get('Fitzpatrick', 'III'))) | |
| tx_hist = str(row.get('treatment_history', row.get('TreatmentHistory', '0'))) | |
| m2 = analyze_patient( | |
| age=age, | |
| sex=sex, | |
| skin_type=skin, | |
| procedure=proc, | |
| treatment_history=tx_hist, | |
| ) | |
| pf = m2['feature_vector'] | |
| # Target displacement: real paired landmarks if available, else anatomical prior | |
| lm_after = None | |
| if entry['after']: | |
| after_img = cv2.imread(entry['after']) | |
| if after_img is not None: | |
| if after_img.shape[:2] != (h, w): | |
| after_img = cv2.resize(after_img, (w, h)) | |
| lm_after, _ = _extract_landmarks_and_measurements(after_img, face_mesh) | |
| if lm_after is not None: | |
| delta_px = lm_after - lm_before | |
| paired_targets += 1 | |
| else: | |
| dst_prior = _apply_displacements(lm_before, proc, h, w, patient_features=pf) | |
| delta_px = dst_prior - lm_before | |
| prior_targets += 1 | |
| delta_norm = np.zeros_like(delta_px, dtype=np.float32) | |
| delta_norm[:, 0] = np.clip(delta_px[:, 0] / max(float(w), 1.0), -0.08, 0.08) | |
| delta_norm[:, 1] = np.clip(delta_px[:, 1] / max(float(h), 1.0), -0.08, 0.08) | |
| lm_norm, meas_norm, pf_vec, proc_idx = prepare_model_inputs( | |
| lm_before, meas, pf, proc, h, w | |
| ) | |
| X_lm.append(lm_norm) | |
| X_meas.append(meas_norm) | |
| X_pf.append(pf_vec) | |
| Y_delta.append(delta_norm) | |
| Y_proc.append(proc_idx) | |
| val_image_paths.append(img_path) | |
| val_after_paths.append(entry['after']) | |
| proc_counts[proc] = proc_counts.get(proc, 0) + 1 | |
| if idx % 25 == 0 or idx == len(samples_to_process): | |
| print(f" Processed {idx}/{len(samples_to_process)} images (usable={len(X_lm)}, skipped={skipped})") | |
| if len(X_lm) < 4: | |
| raise RuntimeError( | |
| f"Only {len(X_lm)} usable face images detected (skipped={skipped}). " | |
| "Ensure frontal face images are present in your dataset." | |
| ) | |
| return { | |
| 'X_lm': np.asarray(X_lm, dtype=np.float32), | |
| 'X_meas': np.asarray(X_meas, dtype=np.float32), | |
| 'X_pf': np.asarray(X_pf, dtype=np.float32), | |
| 'Y_delta': np.asarray(Y_delta, dtype=np.float32), | |
| 'Y_proc': np.asarray(Y_proc, dtype=np.int64), | |
| 'image_paths': val_image_paths, | |
| 'after_paths': val_after_paths, | |
| 'proc_counts': proc_counts, | |
| 'paired_targets': paired_targets, | |
| 'prior_targets': prior_targets, | |
| 'skipped': skipped, | |
| } | |
| def _save_training_curves(history: dict, output_paths: list): | |
| """Generate publication-ready training & validation loss/accuracy plots.""" | |
| epochs = list(range(1, len(history['train_loss']) + 1)) | |
| fig, axes = plt.subplots(1, 2, figsize=(12, 4.8)) | |
| fig.suptitle('MFAF-Net Training & Validation Performance', fontsize=13, fontweight='bold') | |
| axes[0].plot(epochs, history['train_loss'], label='Train Loss', color='#2563eb', linewidth=2) | |
| axes[0].plot(epochs, history['val_loss'], label='Val Loss', color='#ef4444', linewidth=2, linestyle='--') | |
| axes[0].set_title('Multimodal Loss Convergence') | |
| axes[0].set_xlabel('Epoch') | |
| axes[0].set_ylabel('Combined Loss') | |
| axes[0].grid(alpha=0.25) | |
| axes[0].legend() | |
| axes[1].plot(epochs, [a * 100 for a in history['train_acc']], label='Train Acc (%)', color='#10b981', linewidth=2) | |
| axes[1].plot(epochs, [a * 100 for a in history['val_acc']], label='Val Acc (%)', color='#f59e0b', linewidth=2, linestyle='--') | |
| axes[1].set_title('Procedure Recognition Accuracy') | |
| axes[1].set_xlabel('Epoch') | |
| axes[1].set_ylabel('Accuracy (%)') | |
| axes[1].set_ylim(0, 105) | |
| axes[1].grid(alpha=0.25) | |
| axes[1].legend() | |
| plt.tight_layout() | |
| for p in output_paths: | |
| os.makedirs(os.path.dirname(p), exist_ok=True) | |
| plt.savefig(p, dpi=140, bbox_inches='tight') | |
| plt.close(fig) | |
| def evaluate_simulation_quality(model: MFAFNetModel, data: dict, val_indices: np.ndarray, max_eval: int = 12) -> dict: | |
| """Run end-to-end warping on validation images and compare vs Before & real After.""" | |
| model.eval() | |
| ssims, psnrs, maes, changed_pcts = [], [], [], [] | |
| after_ssims, after_psnrs, after_maes = [], [], [] | |
| after_paths = data.get('after_paths', [None] * len(data['image_paths'])) | |
| eval_subset = val_indices[:max_eval] | |
| with FaceLandmarkExtractor(min_detection_confidence=0.45) as fm: | |
| for idx in eval_subset: | |
| img_path = data['image_paths'][idx] | |
| img = cv2.imread(img_path) | |
| if img is None: | |
| continue | |
| h, w = img.shape[:2] | |
| lm, _ = _extract_landmarks_and_measurements(img, fm) | |
| if lm is None: | |
| continue | |
| with torch.no_grad(): | |
| t_lm = torch.from_numpy(data['X_lm'][idx]).unsqueeze(0) | |
| t_meas = torch.from_numpy(data['X_meas'][idx]).unsqueeze(0) | |
| t_pf = torch.from_numpy(data['X_pf'][idx]).unsqueeze(0) | |
| t_proc = torch.tensor([int(data['Y_proc'][idx])], dtype=torch.long) | |
| delta, _, _ = model(t_lm, t_meas, t_pf, t_proc) | |
| delta_np = delta.squeeze(0).numpy() | |
| dst = lm.copy() | |
| dst[:, 0] = np.clip(dst[:, 0] + delta_np[:, 0] * w, 0, w - 1) | |
| dst[:, 1] = np.clip(dst[:, 1] + delta_np[:, 1] * h, 0, h - 1) | |
| proc_name = PROCEDURES[int(data['Y_proc'][idx])] | |
| sim = _piecewise_affine_warp(img, lm, dst, procedure=proc_name) | |
| diff = cv2.absdiff(img, sim) | |
| orig_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) | |
| sim_rgb = cv2.cvtColor(sim, cv2.COLOR_BGR2RGB) | |
| ssims.append(float(structural_similarity(orig_rgb, sim_rgb, channel_axis=2, data_range=255))) | |
| psnrs.append(float(peak_signal_noise_ratio(orig_rgb, sim_rgb, data_range=255))) | |
| maes.append(float(np.mean(diff.astype(np.float32)))) | |
| changed_pcts.append(float(np.any(diff > 15, axis=2).mean() * 100.0)) | |
| a_path = after_paths[idx] | |
| if a_path and os.path.isfile(a_path): | |
| after_img = cv2.imread(a_path) | |
| if after_img is not None: | |
| if after_img.shape[:2] != (h, w): | |
| after_img = cv2.resize(after_img, (w, h)) | |
| after_rgb = cv2.cvtColor(after_img, cv2.COLOR_BGR2RGB) | |
| diff_after = cv2.absdiff(after_img, sim) | |
| after_ssims.append(float(structural_similarity(after_rgb, sim_rgb, channel_axis=2, data_range=255))) | |
| after_psnrs.append(float(peak_signal_noise_ratio(after_rgb, sim_rgb, data_range=255))) | |
| after_maes.append(float(np.mean(diff_after.astype(np.float32)))) | |
| if not ssims: | |
| return {} | |
| out = { | |
| 'eval_samples': len(ssims), | |
| 'mean_ssim': round(float(np.mean(ssims)), 4), | |
| 'mean_psnr': round(float(np.mean(psnrs)), 2), | |
| 'mean_mae': round(float(np.mean(maes)), 4), | |
| 'mean_changed_pixel_pct': round(float(np.mean(changed_pcts)), 2), | |
| } | |
| if after_ssims: | |
| out['vs_after_eval_samples'] = len(after_ssims) | |
| out['vs_after_ssim'] = round(float(np.mean(after_ssims)), 4) | |
| out['vs_after_psnr'] = round(float(np.mean(after_psnrs)), 2) | |
| out['vs_after_mae'] = round(float(np.mean(after_maes)), 4) | |
| return out | |
| def train(data_dir: str = 'data', epochs: int = 35, batch_size: int = 16, lr: float = 1e-3, max_samples: int = 0): | |
| print("=" * 70) | |
| print(" MFAF-Net: Multimodal Training Pipeline") | |
| print("=" * 70) | |
| t0 = time.time() | |
| torch.manual_seed(42) | |
| np.random.seed(42) | |
| data = build_training_samples(data_dir=data_dir, max_samples=max_samples) | |
| n_total = len(data['X_lm']) | |
| # Stratified-style shuffle split (80% train, 20% val) | |
| indices = np.arange(n_total) | |
| np.random.shuffle(indices) | |
| val_size = max(1, int(0.2 * n_total)) | |
| val_idx = indices[:val_size] | |
| train_idx = indices[val_size:] if n_total > 1 else indices | |
| train_ds = TensorDataset( | |
| torch.from_numpy(data['X_lm'][train_idx]), | |
| torch.from_numpy(data['X_meas'][train_idx]), | |
| torch.from_numpy(data['X_pf'][train_idx]), | |
| torch.from_numpy(data['Y_delta'][train_idx]), | |
| torch.from_numpy(data['Y_proc'][train_idx]), | |
| ) | |
| val_ds = TensorDataset( | |
| torch.from_numpy(data['X_lm'][val_idx]), | |
| torch.from_numpy(data['X_meas'][val_idx]), | |
| torch.from_numpy(data['X_pf'][val_idx]), | |
| torch.from_numpy(data['Y_delta'][val_idx]), | |
| torch.from_numpy(data['Y_proc'][val_idx]), | |
| ) | |
| train_loader = DataLoader(train_ds, batch_size=min(batch_size, len(train_ds)), shuffle=True) | |
| val_loader = DataLoader(val_ds, batch_size=min(batch_size, len(val_ds)), shuffle=False) | |
| model = MFAFNetModel(hidden_dim=256, max_shift=0.08) | |
| optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=1e-4) | |
| scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs) | |
| loss_disp_fn = nn.SmoothL1Loss(beta=0.01) | |
| loss_cls_fn = nn.CrossEntropyLoss() | |
| history = {'train_loss': [], 'val_loss': [], 'train_acc': [], 'val_acc': [], 'val_disp_mse': []} | |
| best_val_loss = float('inf') | |
| os.makedirs(DEFAULT_MODELS_DIR, exist_ok=True) | |
| print(f"\nTraining MFAFNetModel on {len(train_ds)} train / {len(val_ds)} val samples for {epochs} epochs...\n") | |
| for epoch in range(1, epochs + 1): | |
| model.train() | |
| tr_loss, tr_correct, tr_count = 0.0, 0, 0 | |
| for b_lm, b_meas, b_pf, b_delta, b_proc in train_loader: | |
| optimizer.zero_grad() | |
| pred_delta, pred_logits, _ = model(b_lm, b_meas, b_pf, b_proc) | |
| loss_d = loss_disp_fn(pred_delta, b_delta) | |
| loss_c = loss_cls_fn(pred_logits, b_proc) | |
| loss = 100.0 * loss_d + 0.5 * loss_c | |
| loss.backward() | |
| optimizer.step() | |
| bs = b_lm.size(0) | |
| tr_loss += loss.item() * bs | |
| tr_correct += (pred_logits.argmax(dim=1) == b_proc).sum().item() | |
| tr_count += bs | |
| scheduler.step() | |
| model.eval() | |
| va_loss, va_disp_mse, va_correct, va_count = 0.0, 0.0, 0, 0 | |
| with torch.no_grad(): | |
| for b_lm, b_meas, b_pf, b_delta, b_proc in val_loader: | |
| pred_delta, pred_logits, _ = model(b_lm, b_meas, b_pf, b_proc) | |
| loss_d = loss_disp_fn(pred_delta, b_delta) | |
| loss_c = loss_cls_fn(pred_logits, b_proc) | |
| loss = 100.0 * loss_d + 0.5 * loss_c | |
| bs = b_lm.size(0) | |
| va_loss += loss.item() * bs | |
| va_disp_mse += torch.mean((pred_delta - b_delta) ** 2).item() * bs | |
| va_correct += (pred_logits.argmax(dim=1) == b_proc).sum().item() | |
| va_count += bs | |
| avg_tr_loss = tr_loss / max(tr_count, 1) | |
| avg_va_loss = va_loss / max(va_count, 1) | |
| avg_tr_acc = tr_correct / max(tr_count, 1) | |
| avg_va_acc = va_correct / max(va_count, 1) | |
| avg_va_mse = va_disp_mse / max(va_count, 1) | |
| history['train_loss'].append(round(avg_tr_loss, 5)) | |
| history['val_loss'].append(round(avg_va_loss, 5)) | |
| history['train_acc'].append(round(avg_tr_acc, 4)) | |
| history['val_acc'].append(round(avg_va_acc, 4)) | |
| history['val_disp_mse'].append(round(avg_va_mse, 7)) | |
| if avg_va_loss < best_val_loss: | |
| best_val_loss = avg_va_loss | |
| torch.save( | |
| { | |
| 'model_state_dict': model.state_dict(), | |
| 'hidden_dim': 256, | |
| 'max_shift': 0.08, | |
| 'metadata': { | |
| 'epoch': epoch, | |
| 'best_val_loss': round(best_val_loss, 5), | |
| 'val_acc': round(avg_va_acc, 4), | |
| 'train_samples': len(train_ds), | |
| 'val_samples': len(val_ds), | |
| 'proc_counts': data['proc_counts'], | |
| 'paired_targets': data['paired_targets'], | |
| 'prior_targets': data['prior_targets'], | |
| }, | |
| }, | |
| DEFAULT_CHECKPOINT_PATH, | |
| ) | |
| if epoch == 1 or epoch % 5 == 0 or epoch == epochs: | |
| print( | |
| f"Epoch {epoch:02d}/{epochs} | " | |
| f"Train Loss: {avg_tr_loss:.4f} (Acc: {avg_tr_acc*100:.1f}%) | " | |
| f"Val Loss: {avg_va_loss:.4f} (Acc: {avg_va_acc*100:.1f}%)" | |
| ) | |
| # Reload best weights and evaluate image quality metrics | |
| best_payload = torch.load(DEFAULT_CHECKPOINT_PATH, map_location='cpu', weights_only=False) | |
| model.load_state_dict(best_payload['model_state_dict']) | |
| sim_eval = evaluate_simulation_quality(model, data, val_idx, max_eval=12) | |
| elapsed = round(time.time() - t0, 2) | |
| summary = { | |
| 'checkpoint_path': DEFAULT_CHECKPOINT_PATH, | |
| 'training_time_sec': elapsed, | |
| 'total_usable_samples': n_total, | |
| 'skipped_samples': data['skipped'], | |
| 'proc_counts': data['proc_counts'], | |
| 'paired_targets': data['paired_targets'], | |
| 'prior_targets': data['prior_targets'], | |
| 'best_val_loss': round(best_val_loss, 5), | |
| 'final_val_acc_pct': round(history['val_acc'][-1] * 100.0, 2), | |
| 'simulation_evaluation': sim_eval, | |
| 'history': history, | |
| } | |
| hist_path = os.path.join(DEFAULT_MODELS_DIR, 'training_history.json') | |
| with open(hist_path, 'w', encoding='utf-8') as f: | |
| json.dump(summary, f, indent=2) | |
| curves_paths = [ | |
| os.path.join(DEFAULT_MODELS_DIR, 'training_curves.png'), | |
| os.path.join(os.path.dirname(DEFAULT_MODELS_DIR), 'static', 'results', 'training_curves.png'), | |
| ] | |
| _save_training_curves(history, curves_paths) | |
| print("\n" + "=" * 70) | |
| print(" Training Complete!") | |
| print("=" * 70) | |
| print(f" Checkpoint saved: {DEFAULT_CHECKPOINT_PATH}") | |
| print(f" History saved: {hist_path}") | |
| print(f" Training curves: {curves_paths[1]}") | |
| print(f" Paired Targets Used: {data['paired_targets']} (Prior fallback: {data['prior_targets']})") | |
| print(f" Best Val Loss: {best_val_loss:.5f}") | |
| if sim_eval: | |
| print(f" Val vs Before SSIM: {sim_eval['mean_ssim']} | PSNR: {sim_eval['mean_psnr']} dB | MAE: {sim_eval['mean_mae']}") | |
| if 'vs_after_ssim' in sim_eval: | |
| print( | |
| f" Val vs After SSIM: {sim_eval['vs_after_ssim']} | " | |
| f"PSNR: {sim_eval['vs_after_psnr']} dB | MAE: {sim_eval['vs_after_mae']} " | |
| f"(n={sim_eval['vs_after_eval_samples']})" | |
| ) | |
| print(" Start the web app (`python run.py`) to use the trained model automatically.") | |
| print("=" * 70) | |
| if __name__ == '__main__': | |
| parser = argparse.ArgumentParser(description='Train MFAF-Net on complete_plasticSurgery_dataset') | |
| parser.add_argument('--data-dir', default='data', help='Path to dataset root (default: data)') | |
| parser.add_argument('--epochs', type=int, default=35, help='Training epochs (default: 35)') | |
| parser.add_argument('--batch-size', type=int, default=16, help='Batch size (default: 16)') | |
| parser.add_argument('--lr', type=float, default=1e-3, help='Learning rate (default: 1e-3)') | |
| parser.add_argument('--max-samples', type=int, default=0, help='Limit total samples (0 = all)') | |
| args = parser.parse_args() | |
| train( | |
| data_dir=args.data_dir, | |
| epochs=args.epochs, | |
| batch_size=args.batch_size, | |
| lr=args.lr, | |
| max_samples=args.max_samples, | |
| ) | |