templates for students

This commit is contained in:
hojula committed 2025-10-13 20:10:54 +02:00
commit 0de2233d62
6 files changed
+1051

No files matched your search

+153
View File
@@ -0,0 +1,153 @@
# 🍎 UROB HW3 - Fruit Image Analysis
This repository contains the code for the third homework assignment of the **UROB course at CTU**. The task involves training a neural network to:
- 🏷️ **Classify** images of fruits into 30 different categories
- 🎨 **Segment** fruits with pixel-level masks
- 🔍 **Learn** meaningful image embeddings
---
## 📁 Repository Structure
```
hw3_students/
├── confs/ # Configuration files for the project
├── data/ # Directory to store datasets (create after downloading)
├── model.py # Neural network architecture definition
├── train.py # Model training script
├── train_job.sbatch # SLURM job script for cluster training
├── README.md # Project documentation
└── requirements.txt # Python dependencies
```
> 💡 **Note:** For cluster training details, see the [Course Page](https://urob-ctu.github.io/docs/)
---
## 🚀 Getting Started
### 1️⃣ Clone the repository
```bash
git clone git@github.com:urob-ctu/hw3-cnns.git
```
### 2️⃣ Set up your environment
Create a virtual environment and install dependencies:
```bash
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
```
### 3️⃣ Download the dataset
Download the dataset and place it in the `data/` directory: [Dataset Link](https://drive.google.com/file/d/1cnD0vsuPSM-lkV4zqCxvXYihuvc6s7PF/view?usp=sharing)
### 4️⃣ Configure your experiment
Modify the configuration file in `confs/config.yml` as needed.
### 5️⃣ Train the model
- Define your model in `model.py`
- Fill the missing lines in `train.py`
- Run the training script:
```bash
python train.py
```
### 6️⃣ (Optional) Use SLURM cluster
If using a SLURM cluster, submit the job using:
```bash
sbatch train_job.sbatch
```
---
## ✅ Your Tasks
1. 🏗️ **Implement** the neural network architecture in `model.py`
- must be named `MyModel` and accept `output_size` as an argument (output_size should be 30 for 30 fruit classes)
- `forward` method must return three outputs:
- class logits (shape: `[batch_size, 30]`)
- segmentation mask (shape: `[batch_size, 1, 64, 64]`)
- image embeddings (shape: `[batch_size, embedding_dim]`)
- `get_embedding` method must return single output:
- image embeddings (shape: `[batch_size, embedding_dim]`)
2. 🔄 **Complete** the training loop in `train.py` (look for ‼️‼️‼️‼️)
3. ⚙️ **Tune** hyperparameters in `confs/config.yml` for optimal performance
---
## 📊 Evaluation
### 🎯 Basic Evaluation (10 points)
This homework is worth **10 points**, distributed as follows:
| Task | Metric | Threshold | Points |
|------|--------|-----------|--------|
| **🍊 Fruit Classification** | Accuracy | 80% | 1 pt |
| | | 85% | 2 pts |
| **🎨 Segmentation Mask** | Mean IoU | 75% | 1 pt |
| | | 80% | 2 pts |
| | | 85% | 3 pts |
| **📈 Image Embeddings (ROC)** | AUC | 0.80 | 1 pt |
| | | 0.85 | 2 pts |
| **🎯 Image Embeddings (TPR)** | TPR @ 5% FPR | 0.75 | 1 pt |
| | | 0.80 | 2 pts |
| | | 0.85 | 3 pts |
### 🏆 Tournament Evaluation (up to +5 bonus points)
In addition to the basic evaluation, there will be a **tournament-style evaluation** where models are ranked based on their performance across all four tasks.
**Scoring System:**
- Your final score is determined by the **sum of ranks** in each task
- **Lower total rank = Better score**
- In case of a tie, the model with the **earlier submission time** ranks higher
**Bonus Points:**
- 🥇 **Winner:** +5 points
- 🥈 **2nd place:** +4 points
- 🥉 **3rd place:** +3 points
- 🏅 **Top 10:** +2 points
- 🎖️ **Top 20:** +1 point
> **Maximum Score:** 15 points (10 from basic evaluation + 5 from tournament)
---
## 📦 Submission
Submit your code as a **zip file** containing:
- ✅ `model.py` - Your neural network architecture
- ✅ `train.py` - Your training script
- ✅ `weights.pth` - Trained model weights (state_dict)
> **Loading format:** Weights are loaded using:
> ```python
> model.load_state_dict(torch.load(weights_path, map_location=torch.device('cpu')))
> ```
---
## 🚫 Important Policies
### 🤖 Pretrained Models Policy
❌ You are **not allowed** to use any pretrained models or transfer learning techniques.
✅ All models **must be trained from scratch** using the provided dataset and your training code that you submit.
### 📝 Plagiarism Policy
✅ You are **strongly encouraged** to discuss ideas and approaches with your peers.
⚠️ However, the code you submit **must be your own work**.
❌ Copying code from others is **strictly prohibited** and will result in a **zero score** for the assignment.
---
<div align="center">
**Good luck! 🍀**
**In case of any questions, feel free to write me at hlavsja3@fel.cvut.cz and I will ask my LLM🔮**
</div>
+10
View File
@@ -0,0 +1,10 @@
data_dir: "Data/"
batch_size: ❓
learning_rate: ❓
num_epochs: ❓
random_seed: 42
num_folds: ❓
output_dim: 30
cache_images: ❓
image_size: [64, 64]
validate_every: ❓
+51
View File
@@ -0,0 +1,51 @@
import torch
import torch.nn as nn
import numpy as np
class MyModel(torch.nn.Module):
"""
MyModel is a custom neural network model for image classification and segmentation and vectorization.
"""
def __init__(self, output_size=30):
"""Initialize the model.
Args:
input_size (int): Size of the input features.
hidden_size (int): Size of the hidden layers.
output_size (int): Size of the output layer (number of classes).
"""
super(MyModel, self).__init__()
self.backbone = # ‼️‼️‼️‼️ Define your backbone ‼️‼️‼️‼️
self.species_classifier = # ‼️‼️‼️‼️ Define you classifier ‼️‼️‼️‼️
self.segmentation_head = # ‼️‼️‼️‼️ Define your segmentation head ‼️‼️‼️‼️
def forward(self, x):
"""Forward pass for the model.
Args:
x (torch.Tensor): Input tensor.
Returns:
tuple: (species, masks, embeddings)
species (torch.Tensor): The species classification logits.
masks (torch.Tensor): The segmentation masks.
embeddings (torch.Tensor): The feature embeddings.
"""
# ‼️‼️‼️‼️ Define the forward pass ‼️‼️‼️‼️
return species, masks, embeddings
def get_embedding(self, x):
"""Get the feature embeddings from the model.
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: The feature embeddings.
"""
# ‼️‼️‼️‼️ Implement the embedding extraction ‼️‼️‼️‼️
return embeddings
+76
View File
@@ -0,0 +1,76 @@
absl-py==2.3.1
appnope==0.1.4
asttokens==3.0.0
certifi==2025.8.3
charset-normalizer==3.4.3
comm==0.2.3
contourpy==1.3.3
cycler==0.12.1
debugpy==1.8.16
decorator==5.2.1
executing==2.2.0
filelock==3.18.0
fonttools==4.59.0
fsspec==2025.7.0
grpcio==1.74.0
idna==3.10
ipykernel==6.30.1
ipython==9.4.0
ipython_pygments_lexers==1.1.1
jedi==0.19.2
Jinja2==3.1.6
joblib==1.5.1
jupyter_client==8.6.3
jupyter_core==5.8.1
kiwisolver==1.4.8
Markdown==3.8.2
MarkupSafe==3.0.2
matplotlib==3.10.3
matplotlib-inline==0.1.7
mpmath==1.3.0
nest-asyncio==1.6.0
networkx==3.5
numpy==2.2.6
opencv-python==4.12.0.88
packaging==25.0
pandas==2.3.2
parso==0.8.5
pexpect==4.9.0
pillow==11.3.0
platformdirs==4.4.0
polars==1.33.1
prompt_toolkit==3.0.51
protobuf==6.32.0
psutil==7.0.0
ptyprocess==0.7.0
pure_eval==0.2.3
Pygments==2.19.2
pyparsing==3.2.3
python-dateutil==2.9.0.post0
pytz==2025.2
PyYAML==6.0.2
pyzmq==27.0.2
requests==2.32.5
scikit-learn==1.7.1
scipy==1.16.1
seaborn==0.13.2
setuptools==80.9.0
six==1.17.0
stack-data==0.6.3
sympy==1.14.0
tensorboard==2.20.0
tensorboard-data-server==0.7.2
threadpoolctl==3.6.0
torch==2.7.1
torchaudio==2.7.1
torchvision==0.22.1
tornado==6.5.2
tqdm==4.67.1
traitlets==5.14.3
typing_extensions==4.14.1
tzdata==2025.2
ultralytics==8.3.203
ultralytics-thop==2.0.17
urllib3==2.5.0
wcwidth==0.2.13
Werkzeug==3.1.3
+744
View File
@@ -0,0 +1,744 @@
import os
import sys
import torch
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader, Dataset, Subset
from sklearn.model_selection import StratifiedKFold, train_test_split
import yaml
from collections import Counter
import logging
from datetime import datetime
from model import MyModel
import platform
from PIL import Image
from tqdm import tqdm
from sklearn.metrics import roc_curve, auc
from torch.utils.tensorboard import SummaryWriter
def get_device():
"""Get the device to be used for training.
Returns:
torch.device: The device to be used (CPU or GPU).
"""
if torch.cuda.is_available():
return torch.device("cuda")
elif torch.backends.mps.is_available() and platform.system() == "Darwin":
return torch.device("mps") # Metal backend for Mac
else:
return torch.device("cpu")
class FruitDataset(Dataset):
"""Fruit dataset used for training.
Args:
Dataset (_type_): _description_
"""
def __init__(self, data_dir, config):
self.data_dir = # ‼️‼️‼️‼️ directory with your data ‼️‼️‼️‼️
self.images = # ‼️‼️‼️‼️ list of image file paths ‼️‼️‼️‼️
self.masks = # ‼️‼️‼️‼️ list of mask file paths ‼️‼️‼️‼️
# ‼️‼️‼️‼️ list of metadata for each image (fruit name) ‼️‼️‼️‼️
self.metadata =
# ‼️‼️‼️‼️ list of labels for each image (fruit name but numbered) ‼️‼️‼️‼️
self.labels =
self.config = config # loaded yaml config
self.loaded_images = {} # ‼️‼️‼️‼️ To store loaded images if caching is enabled ‼️‼️‼️‼️
def __len__(self): # ‼️‼️‼️‼️
"""Return the total number of samples in the dataset.
"""
# ‼️‼️‼️‼️ TODO ‼️‼️‼️‼️
def __getitem__(self, idx): # ‼️‼️‼️‼️
"""Get a sample from the dataset.
Args:
idx (int): Index of the sample to retrieve.
Returns:
tuple: (image, mask, metadata, label, idx)
image (torch.Tensor): The image tensor.
mask (torch.Tensor): The mask tensor.
metadata (dict): The metadata for the sample (fruit name).
label (torch.Tensor): The label tensor (fruit name but numbered)
idx (int): The index of the sample.
"""
# ‼️‼️‼️‼️ TODO ‼️‼️‼️‼️
return image, mask, metadata, label, idx
def setup_experiment_dir(config):
"""
Create experiment directory with timestamp and setup logging
Returns the experiment directory path and tensorboard writer
"""
# Create timestamp for the experiment
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
exp_name = f"experiment_{timestamp}"
# Create experiment directory
exp_dir = os.path.join("experiments", exp_name)
os.makedirs(exp_dir, exist_ok=True)
# Create subdirectories
os.makedirs(os.path.join(exp_dir, "logs"), exist_ok=True)
os.makedirs(os.path.join(exp_dir, "models"), exist_ok=True)
os.makedirs(os.path.join(exp_dir, "results"), exist_ok=True)
os.makedirs(os.path.join(exp_dir, "tensorboard"), exist_ok=True)
# Copy config file to experiment directory
config_save_path = os.path.join(exp_dir, "config.yml")
with open(config_save_path, 'w') as f:
yaml.dump(config, f, default_flow_style=False)
# Setup TensorBoard writer
tb_dir = os.path.join(exp_dir, "tensorboard")
writer = SummaryWriter(tb_dir)
# Setup logging
log_file = os.path.join(exp_dir, "logs", "experiment.log")
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
logger.info(f"Experiment started: {exp_name}")
logger.info(f"Experiment directory: {exp_dir}")
logger.info(f"Config saved to: {config_save_path}")
logger.info(f"TensorBoard logs: {tb_dir}")
return exp_dir, logger, writer
def print_fruit_distribution(train_idx, val_idx, labels, logger):
"""Print the distribution of fruit classes in the training and validation sets.
Args:
train_idx (list): Indices of the training samples.
val_idx (list): Indices of the validation samples.
labels (list): List of labels for each sample.
logger (logging.Logger): Logger instance for logging.
"""
train_labels = [labels[i] for i in train_idx]
val_labels = [labels[i] for i in val_idx]
train_counts = Counter(train_labels)
val_counts = Counter(val_labels)
logger.info("Training set distribution:")
for fruit, count in sorted(train_counts.items()):
logger.info(f" {fruit}: {count} samples")
logger.info("Validation set distribution:")
for fruit, count in sorted(val_counts.items()):
logger.info(f" {fruit}: {count} samples")
def compute_seg_metrics(pred, target, class_idx):
"""Compute segmentation metrics for a specific class.
Args:
pred (torch.Tensor): Predicted segmentation map.
target (torch.Tensor): Ground truth segmentation map.
class_idx (int): Class index to compute metrics for.
Returns:
tuple: (precision, recall, iou)
"""
pred = pred == class_idx
target = target == class_idx
TP = (pred & target).sum()
FP = (pred & ~target).sum()
FN = (~pred & target).sum()
iou = TP / (TP + FP + FN) if TP + FP + FN > 0 else 0
precision = TP / (TP + FP) if TP + FP > 0 else 0
recall = TP / (TP + FN) if TP + FN > 0 else 0
return precision, recall, iou
def compute_embedding_bank(dataset, model):
"""
Compute embeddings for all samples in the dataset and store them in an embedding bank.
Returns: embedding_bank (tensor), labels (list)
"""
device = get_device()
model.eval()
# Pre-allocate tensors for efficiency
dataset_size = 1969
embedding_dim = None # Will be determined from first batch
all_embeddings = None
all_labels = torch.zeros(dataset_size, dtype=torch.long, device=device)
dataloader = DataLoader(dataset, batch_size=32, shuffle=False)
labels_found = set()
with torch.no_grad():
for batch_idx, (images, _, metadata, labels, idxs) in enumerate(tqdm(dataloader, desc="Computing embeddings")):
images = images.to(device)
batch_embeddings = model.get_embedding(images)
# Initialize embedding tensor on first batch
if all_embeddings is None:
embedding_dim = batch_embeddings.shape[1]
all_embeddings = torch.full(
(dataset_size, embedding_dim), float('nan'), device=device)
# Convert indices to tensor if needed and move to device
if not torch.is_tensor(idxs):
idxs = torch.tensor(idxs, device=device)
else:
idxs = idxs.to(device)
# Move labels to device for assignment
labels = labels.to(device)
labels_found.update(labels.cpu().numpy())
# Vectorized assignment - no loops!
all_embeddings[idxs] = batch_embeddings
all_labels[idxs] = labels
# Convert labels to list for compatibility
all_labels = all_labels.tolist()
different_labels = set(all_labels)
return all_embeddings, all_labels
def create_triplets_batch(anchor_embeddings, anchor_labels, anchor_idxs,
embedding_bank, all_labels, hard_percentage=0.2):
"""
Create triplets from a batch of anchors using percentage-based hard mining.
Args:
anchor_embeddings: Batch of anchor embeddings [batch_size, embedding_dim]
anchor_labels: Labels for anchors [batch_size]
anchor_idxs: Indices of anchor samples in dataset [batch_size]
embedding_bank: All embeddings in the dataset [dataset_size, embedding_dim]
all_labels: All labels in the dataset [dataset_size]
hard_percentage: Percentage of hardest positives and negatives to sample from
Returns:
triplets: List of (anchor_idx, positive_idx, negative_idx) tuples
"""
batch_size = anchor_embeddings.size(0)
triplets = []
# Create label-to-indices mapping for efficient lookup
label_to_indices = {}
for idx, label in enumerate(all_labels):
label_to_indices.setdefault(label, []).append(idx)
for i in range(batch_size):
anchor_idx = anchor_idxs[i].item()
anchor_embedding = anchor_embeddings[i].unsqueeze(
0) # [1, embedding_dim]
anchor_label = anchor_labels[i].item()
# Positive and negative candidates
positive_candidates = [
idx for idx in label_to_indices[anchor_label] if idx != anchor_idx]
negative_candidates = [idx for lbl, idxs in label_to_indices.items(
) if lbl != anchor_label for idx in idxs]
if len(positive_candidates) == 0 or len(negative_candidates) == 0:
continue
# filter nan - get valid mask for entire embedding bank
valid_mask = ~torch.isnan(embedding_bank).any(dim=1)
# Convert candidates to tensors for vectorized operations
pos_candidates_tensor = torch.tensor(
positive_candidates, device=embedding_bank.device)
neg_candidates_tensor = torch.tensor(
negative_candidates, device=embedding_bank.device)
# Filter using vectorized operations instead of loops
valid_pos_mask = valid_mask[pos_candidates_tensor]
valid_neg_mask = valid_mask[neg_candidates_tensor]
valid_positive_candidates = pos_candidates_tensor[valid_pos_mask]
valid_negative_candidates = neg_candidates_tensor[valid_neg_mask]
if len(valid_positive_candidates) == 0 or len(valid_negative_candidates) == 0:
continue
# Compute similarities using only valid candidates
pos_embeds = embedding_bank[valid_positive_candidates]
neg_embeds = embedding_bank[valid_negative_candidates]
pos_sims = torch.nn.functional.cosine_similarity(
anchor_embedding, pos_embeds, dim=1)
neg_sims = torch.nn.functional.cosine_similarity(
anchor_embedding, neg_embeds, dim=1)
# Select same count based on smaller pool of valid candidates
pos_count = max(
1, int(len(valid_positive_candidates) * hard_percentage))
neg_count = max(
1, int(len(valid_negative_candidates) * hard_percentage))
num_to_sample = min(pos_count, neg_count)
# Hard positive: least similar (harder to distinguish)
_, hard_pos_indices = torch.topk(
pos_sims, num_to_sample, largest=False)
positive_idx = valid_positive_candidates[hard_pos_indices]
# Hard negative: most similar (harder to separate)
_, hard_neg_indices = torch.topk(neg_sims, num_to_sample, largest=True)
negative_idx = valid_negative_candidates[hard_neg_indices]
for j in range(num_to_sample):
# Append triplet (anchor_idx, positive_idx, negative_idx)
triplets.append(
(anchor_embeddings[i], embedding_bank[positive_idx[j]], embedding_bank[negative_idx[j]]))
return triplets
def compute_triplet_loss(triplets, margin=1.0): # ‼️‼️‼️‼️
"""Compute triplet loss for a batch of triplets.
Args:
triplets (list): List of triplets (anchor, positive, negative).
margin (float, optional): Margin for the triplet loss. Defaults to 1.0.
Returns:
torch.Tensor: Computed triplet loss.
"""
# ‼️‼️‼️‼️ TODO ‼️‼️‼️‼️
return loss
def compute_roc_metrics(model, dataset, target_fpr=0.05, embedding_bank=None, all_labels=None):
"""
Vectorized ROC computation for embedding-based similarity - only uses valid (non-NaN) embeddings.
Args:
model: Trained model
dataset: Dataset to evaluate on
target_fpr: Target false positive rate (default: 0.05)
embedding_bank: Pre-computed embedding bank [N, D] (optional, will compute if None)
all_labels: Corresponding labels [N] (optional, will compute if None)
Returns:
roc_auc: Area under ROC curve
tpr_at_fpr: True positive rate at target FPR
fpr_values: Array of FPR values
tpr_values: Array of TPR values
thresholds: Array of threshold values
"""
device = get_device()
# Convert to tensor and remove rows with NaNs
embedding_bank = embedding_bank.to(device)
# rint random embedding
all_labels = torch.tensor(all_labels, device=device)
valid_mask = ~torch.isnan(embedding_bank).any(dim=1)
embedding_bank = embedding_bank[valid_mask]
all_labels = all_labels[valid_mask]
# Normalize for cosine similarity
E = torch.nn.functional.normalize(embedding_bank, dim=1) # (N_valid, D)
# Cosine similarity matrix
S = E @ E.T # (N_valid, N_valid)
# Label comparison matrix
same_class = (all_labels[:, None] == all_labels[None, :])
# Mask: upper triangle without diagonal (to avoid self-pairs and duplicates)
N = E.shape[0]
mask = torch.triu(torch.ones(N, N, device=device,
dtype=torch.bool), diagonal=1)
# Select valid similarity scores and labels
y_true = same_class[mask].cpu().numpy().astype(int)
y_scores = S[mask].cpu().numpy()
# Compute ROC and AUC
fpr_values, tpr_values, thresholds = roc_curve(y_true, y_scores)
roc_auc = auc(fpr_values, tpr_values)
# Interpolate TPR at given FPR
tpr_at_fpr = float(np.interp(target_fpr, fpr_values, tpr_values)) if len(
fpr_values) > 1 else 0.0
return roc_auc, tpr_at_fpr, fpr_values, tpr_values, thresholds
def run_fold(train_loader, val_loader, config, fold_num, exp_dir, logger, model, writer):
"""Train and validate for a single fold.
Args:
train_loader (DataLoader): DataLoader for the training set.
val_loader (DataLoader): DataLoader for the validation set.
config (dict): Configuration dictionary.
fold_num (int): Current fold number.
exp_dir (str): Experiment directory path.
logger (logging.Logger): Logger instance.
model (nn.Module): Model to train and evaluate.
Returns:
float: Best validation score achieved during training.
"""
logger.info(f"Training fold {fold_num}...")
best_val_score = 0.0
species_criterion = # ‼️‼️‼️‼️ Define your criterion ‼️‼️‼️‼️
mask_criterion = # ‼️‼️‼️‼️ Define your criterion ‼️‼️‼️‼️
optimizer = # ‼️‼️‼️‼️ Define your optimizer ‼️‼️‼️‼️
fold_dir = os.path.join(exp_dir, "models", f"fold_{fold_num}")
os.makedirs(fold_dir, exist_ok=True)
# Compute initial embedding bank once before training
logger.info("Computing initial embedding bank...")
# ‼️‼️‼️‼️ Compute embedding bank before training for the training set ‼️‼️‼️‼️
embedding_bank, all_labels =
# ‼️‼️‼️‼️ Compute embedding bank for validation set ‼️‼️‼️‼️
embedding_bank_val, all_labels_val =
for epoch in range(config['num_epochs']):
trn_loss = 0.0
train_correct = 0
train_total = 0
# ‼️‼️‼️‼️ SET MODEL TO TRAIN MODE ‼️‼️‼️‼️
# Training loop with tqdm progress bar
train_pbar = tqdm(train_loader, desc=f"Fold {fold_num} - Epoch {epoch + 1}/{config['num_epochs']} [Train]",
leave=False, unit="batch")
for batch_idx, (images, masks, metadata, labels, idxs) in enumerate(train_pbar):
# ‼️‼️‼️‼️ ZERO GRAD! ‼️‼️‼️‼️
outputs, masks_pred, embeddings = # ‼️‼️‼️‼️ make predictions ‼️‼️‼️‼️
# update embedding bank with current batch
all_embeddings = embeddings.detach()
if not torch.is_tensor(idxs):
idxs = torch.tensor(idxs, device=images.device)
else:
idxs = idxs.to(images.device)
embedding_bank[idxs] = all_embeddings
# Classification loss
classification_loss = # ‼️‼️‼️‼️ compute species loss ‼️‼️‼️‼️
# Segmentation loss - ensure both tensors are float32 and same shape
segmentation_loss = # ‼️‼️‼️‼️ compute mask loss ‼️‼️‼️‼️
# triplet loss
triplets = # ‼️‼️‼️‼️ create triplets ‼️‼️‼️‼️
if len(triplets) > 0:
triplet_loss = # ‼️‼️‼️‼️ compute triplet loss ‼️‼️‼️‼️
else:
triplet_loss = torch.tensor(0.0, device=images.device)
# Combine losses with weights
loss = # ‼️‼️‼️‼️ compute combined loss ‼️‼️‼️‼️
# Check for invalid loss values
if torch.isnan(loss) or torch.isinf(loss):
logger.warning(f"Invalid loss detected: {loss.item()}")
continue
# ‼️‼️‼️‼️ BACKPROPAGATE AND MAKE OPTIMIZER STEP ‼️‼️‼️‼️
batch_loss = loss.item()
trn_loss += batch_loss
# Calculate training accuracy (add this section for TensorBoard logging)
# ‼️‼️‼️‼️ Students: calculate predictions from outputs and compare with labels ‼️‼️‼️‼️
# predictions = outputs.argmax(dim=1)
# train_correct += (predictions == labels).sum().item()
# train_total += labels.size(0)
# Update progress bar with current batch loss and average loss
avg_loss = trn_loss / (batch_idx + 1)
train_pbar.set_postfix({
'Batch Loss': f'{batch_loss:.4f}',
'Avg Loss': f'{avg_loss:.4f}',
'Class Loss': f'{classification_loss.item():.4f}',
'Seg Loss': f'{segmentation_loss.item():.4f}',
'Triplet Loss': f'{triplet_loss.item():.4f}'
})
trn_loss /= len(train_loader)
train_accuracy = train_correct / train_total if train_total > 0 else 0.0
# Log training metrics to TensorBoard
global_step = epoch * len(train_loader) + len(train_loader)
writer.add_scalar(
f'Loss/Train_Total_Fold{fold_num}', trn_loss, global_step)
writer.add_scalar(
f'Accuracy/Train_Fold{fold_num}', train_accuracy, global_step)
logger.info(f"Epoch {epoch + 1}/{config['num_epochs']}, "
f"Train Loss: {trn_loss:.4f}, Train Accuracy: {train_accuracy:.4f}")
if (epoch + 1) % config['validate_every'] == 0:
# validate the model
# ‼️‼️‼️‼️ SET MODEL TO VALIDATION MODE ‼️‼️‼️‼️
val_loss = 0.0
correct = 0
total = 0
# Validation loop with tqdm progress bar
val_pbar = tqdm(val_loader, desc=f"Fold {fold_num} - Epoch {epoch + 1}/{config['num_epochs']} [Val]",
leave=False, unit="batch")
precision1, recall1, iou1 = [], [], []
precision2, recall2, iou2 = [], [], []
with torch.no_grad():
for batch_idx, (images, masks, metadata, labels, idxs) in enumerate(val_pbar):
outputs, masks_pred, embeddings = model(images)
# Update embedding bank with current batch
all_embeddings = embeddings.detach()
if not torch.is_tensor(idxs):
idxs = torch.tensor(idxs, device=images.device)
else:
idxs = idxs.to(images.device)
embedding_bank_val[idxs] = all_embeddings
# Classification loss
classification_loss = # ‼️‼️‼️‼️ compute species loss ‼️‼️‼️‼️
# Segmentation loss
segmentation_loss = # ‼️‼️‼️‼️ compute mask loss ‼️‼️‼️‼️
# triplet loss using updated embedding bank
triplets = # ‼️‼️‼️‼️ create triplets ‼️‼️‼️‼️
if len(triplets) > 0:
triplet_loss = # ‼️‼️‼️‼️ compute triplet loss ‼️‼️‼️‼️
else:
triplet_loss = torch.tensor(0.0, device=images.device)
# Combined loss
loss = # ‼️‼️‼️‼️ compute combined loss ‼️‼️‼️‼️
batch_loss = loss.item()
val_loss += batch_loss
predictions = outputs.argmax(dim=1)
batch_correct = (predictions == labels).sum().item()
correct += batch_correct
total += labels.size(0)
# Update progress bar with current batch loss and accuracy
avg_val_loss = val_loss / (batch_idx + 1)
current_acc = correct / total if total > 0 else 0
# Convert predictions to binary for IoU calculation
masks_pred_binary = torch.sigmoid(masks_pred) > 0.5
p1, r1, i1 = compute_seg_metrics(
masks_pred_binary.float(), masks, class_idx=1)
p2, r2, i2 = compute_seg_metrics(
masks_pred_binary.float(), masks, class_idx=0)
precision1.append(p1.item())
recall1.append(r1.item())
iou1.append(i1.item())
precision2.append(p2.item())
recall2.append(r2.item())
iou2.append(i2.item())
val_pbar.set_postfix({
'Batch Loss': f'{batch_loss:.4f}',
'Avg Loss': f'{avg_val_loss:.4f}',
'Accuracy': f'{current_acc:.4f}',
'Class Loss': f'{classification_loss.item():.4f}',
'Seg Loss': f'{segmentation_loss.item():.4f}',
})
# Calculate average validation loss and metrics
roc, tpr_at_fpr, fpr_values, tpr_values, thresholds = compute_roc_metrics(
model, val_loader.dataset, target_fpr=config.get(
'target_fpr', 0.05),
embedding_bank=embedding_bank_val, all_labels=all_labels_val)
val_loss /= len(val_loader)
val_score = correct / total
# Log all validation metrics to TensorBoard
global_step = epoch * len(train_loader) + len(train_loader)
writer.add_scalar(
f'Loss/Val_Total_Fold{fold_num}', val_loss, global_step)
writer.add_scalar(
f'Accuracy/Val_Fold{fold_num}', val_score, global_step)
# IoU metrics
writer.add_scalar(
f'IoU/Val_Class1_Fold{fold_num}', np.mean(iou1), global_step)
writer.add_scalar(
f'IoU/Val_Class0_Fold{fold_num}', np.mean(iou2), global_step)
# Precision metrics
writer.add_scalar(
f'Precision/Val_Class1_Fold{fold_num}', np.mean(precision1), global_step)
writer.add_scalar(
f'Precision/Val_Class0_Fold{fold_num}', np.mean(precision2), global_step)
# Recall metrics
writer.add_scalar(
f'Recall/Val_Class1_Fold{fold_num}', np.mean(recall1), global_step)
writer.add_scalar(
f'Recall/Val_Class0_Fold{fold_num}', np.mean(recall2), global_step)
# ROC metrics
writer.add_scalar(f'ROC/AUC_Fold{fold_num}', roc, global_step)
writer.add_scalar(
f'ROC/TPR_at_{config.get("target_fpr", 0.05)}_FPR_Fold{fold_num}', tpr_at_fpr, global_step)
logger.info(f"Validation Loss: {val_loss:.4f}, "
f"Validation Accuracy: {val_score:.4f}, "
f"Validation IoU: {np.mean(iou1):.4f} (class 1), "
f"{np.mean(iou2):.4f} (class 0), "
f"Validation Precision: {np.mean(precision1):.4f} (class 1), "
f"{np.mean(precision2):.4f} (class 0), "
f"Validation Recall: {np.mean(recall1):.4f} (class 1), "
f"{np.mean(recall2):.4f} (class 0), "
f"ROC AUC: {roc:.4f}, "
f"TPR at {config.get('target_fpr', 0.05)} FPR: {tpr_at_fpr:.4f}")
if val_score > best_val_score:
best_val_score = val_score
# Save the best model
model_path = os.path.join(fold_dir, "best_model.pth")
torch.save(model.state_dict(), model_path)
return best_val_score
def main():
config_path = "confs/config.yml"
with open(config_path, 'r') as file:
config = yaml.safe_load(file)
# Setup experiment directory and logging
exp_dir, logger, writer = setup_experiment_dir(config)
# Log configuration
logger.info("Configuration:")
for key, value in config.items():
logger.info(f" {key}: {value}")
dataset = FruitDataset(data_dir=config['data_dir'], config=config)
labels = [dataset.metadata[i] for i in range(len(dataset))]
fold_results = []
# Count samples per fruit type
fruit_counts = Counter(labels)
logger.info(f"Total samples in dataset: {len(dataset)}")
logger.info("Fruit distribution in dataset:")
for fruit, count in sorted(fruit_counts.items()):
logger.info(f" {fruit}: {count} samples")
# Handle single fold as 80-20 split vs multi-fold cross-validation
if config['num_folds'] == 1:
logger.info("Using 80-20 train-validation split (single fold)")
train_idx, val_idx = train_test_split(
range(len(dataset)),
test_size=0.2,
stratify=labels,
random_state=config['random_seed']
)
splits = [(train_idx, val_idx)]
else:
skf = StratifiedKFold(n_splits=config['num_folds'],
shuffle=True, random_state=config['random_seed'])
logger.info(
f"Starting {config['num_folds']}-fold stratified cross-validation")
splits = list(skf.split(range(len(dataset)), labels))
for fold, (train_idx, val_idx) in enumerate(splits):
logger.info(f"\n{'='*50}")
if config['num_folds'] == 1:
logger.info(f"Single fold (80-20 split)")
else:
logger.info(f"Fold {fold + 1}/{config['num_folds']}")
logger.info(
f"Train samples: {len(train_idx)}, Validation samples: {len(val_idx)}")
# Check distribution in this fold
print_fruit_distribution(train_idx, val_idx, labels, logger)
train_subset = Subset(dataset, train_idx)
val_subset = Subset(dataset, val_idx)
# Create data loaders for train and validation
train_loader = DataLoader(
train_subset, batch_size=config['batch_size'], shuffle=True)
val_loader = DataLoader(
val_subset, batch_size=config['batch_size'], shuffle=False)
# Training loop for current fold
input_dim = 786432
model = MyModel(input_size=input_dim,
hidden_size=128, output_size=config['output_dim'])
model.to(torch.device(get_device()))
fold_result = run_fold(
train_loader, val_loader, config, fold + 1, exp_dir, logger, model, writer)
fold_results.append(fold_result)
# Print overall results
logger.info("\n" + "="*50)
if config['num_folds'] == 1:
logger.info("Single fold (80-20 split) Results:")
logger.info(f"Validation Score: {fold_results[0]:.4f}")
else:
logger.info(
f"{config['num_folds']}-Fold Stratified Cross-Validation Results:")
for i, result in enumerate(fold_results):
logger.info(f"Fold {i+1}: {result:.4f}")
# Calculate and print average performance
if fold_results and isinstance(fold_results[0], (int, float)):
if config['num_folds'] == 1:
logger.info(f"Final Validation Score: {fold_results[0]:.4f}")
else:
avg_result = np.mean(fold_results)
std_result = np.std(fold_results)
logger.info(f"\nAverage: {avg_result:.4f} ± {std_result:.4f}")
# Save final results
results_file = os.path.join(exp_dir, "results", "final_results.txt")
with open(results_file, 'w') as f:
if config['num_folds'] == 1:
f.write("Single fold (80-20 split) Results:\n")
f.write(f"Validation Score: {fold_results[0]:.4f}\n")
else:
f.write(
f"{config['num_folds']}-Fold Stratified Cross-Validation Results:\n")
for i, result in enumerate(fold_results):
f.write(f"Fold {i+1}: {result:.4f}\n")
f.write(f"\nAverage: {avg_result:.4f} ± {std_result:.4f}\n")
logger.info(f"Results saved to: {results_file}")
logger.info(f"Experiment completed. All files saved in: {exp_dir}")
# Close TensorBoard writer
writer.close()
logger.info(
f"TensorBoard logs saved to: {os.path.join(exp_dir, 'tensorboard')}")
if __name__ == "__main__":
main()
+17
View File
@@ -0,0 +1,17 @@
#!/bin/bash
#SBATCH --job-name=trn
#SBATCH --partition=fast
#SBATCH --gres=gpu:1
#SBATCH --time=04:00:00
#SBATCH --output=logs/%x-%j.out
#SBATCH --error=logs/%x-%j.err
# Load required modules
ml matplotlib/3.9.2-gfbf-2024a
ml PyTorch/2.7.1-foss-2024a-CUDA-12.6.0
ml scikit-learn/1.5.2-gfbf-2024a
ml tqdm/4.67.1-GCCcore-14.2.0
ml tensorboard/2.18.0-gfbf-2024a
# Run the training script
python /home.nfs/{your_fel_username}/{path_to_your_dir}/train.py