idk
This commit is contained in:
1 parent
c870ec0961
commit
368aa71658
7 files changed
+328
-99
No files matched your search
@@ -39,38 +39,68 @@ class FruitDataset(Dataset):
|
||||
"""
|
||||
|
||||
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 ‼️‼️‼️‼️
|
||||
self.data_dir = data_dir
|
||||
self.config = config
|
||||
self.image_size = tuple(config["image_size"]) # (64, 64)
|
||||
|
||||
def __len__(self): # ‼️‼️‼️‼️
|
||||
self.images = []
|
||||
self.masks = []
|
||||
self.metadata = []
|
||||
|
||||
for fruit in sorted(os.listdir(data_dir)):
|
||||
fruit_dir = os.path.join(data_dir, fruit)
|
||||
if not os.path.isdir(fruit_dir):
|
||||
continue
|
||||
img_dir = os.path.join(fruit_dir, "Images")
|
||||
mask_dir = os.path.join(fruit_dir, "Mask")
|
||||
|
||||
masks_by_stem = {os.path.splitext(f)[0]: f for f in os.listdir(mask_dir)}
|
||||
|
||||
for img_name in sorted(os.listdir(img_dir)):
|
||||
stem = os.path.splitext(img_name)[0]
|
||||
mask_name = masks_by_stem.get(stem) or masks_by_stem.get(stem + "_mask")
|
||||
if mask_name is None:
|
||||
raise FileNotFoundError(f"No mask found for {img_dir}/{img_name}")
|
||||
self.images.append(os.path.join(img_dir, img_name))
|
||||
self.masks.append(os.path.join(mask_dir, mask_name))
|
||||
self.metadata.append(fruit)
|
||||
|
||||
self.class_names = sorted(set(self.metadata))
|
||||
self.class_to_idx = {name: i for i, name in enumerate(self.class_names)}
|
||||
self.labels = [self.class_to_idx[name] for name in self.metadata]
|
||||
|
||||
self.loaded_images = {}
|
||||
|
||||
def _load(self, idx):
|
||||
image = Image.open(self.images[idx]).convert("RGB")
|
||||
image = image.resize(self.image_size, Image.BILINEAR)
|
||||
image = np.asarray(image, dtype=np.float32) / 255.0
|
||||
image = (image - 0.5) / 0.5 # normalizace okolo nuly
|
||||
image = torch.from_numpy(image).permute(2, 0, 1)
|
||||
|
||||
|
||||
mask = Image.open(self.masks[idx]).convert("L")
|
||||
mask = mask.resize(self.image_size, Image.NEAREST)
|
||||
mask = np.asarray(mask)
|
||||
mask = mask > (mask.max() / 2)
|
||||
mask = torch.from_numpy(mask).float().unsqueeze(0)
|
||||
return image, mask
|
||||
|
||||
def __len__(self):
|
||||
"""Return the total number of samples in the dataset.
|
||||
"""
|
||||
# ‼️‼️‼️‼️ TODO ‼️‼️‼️‼️
|
||||
return len(self.images)
|
||||
|
||||
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 ‼️‼️‼️‼️
|
||||
def __getitem__(self, idx):
|
||||
if idx in self.loaded_images:
|
||||
image, mask = self.loaded_images[idx]
|
||||
else:
|
||||
image, mask = self._load(idx)
|
||||
if self.config.get("cache_images", False):
|
||||
self.loaded_images[idx] = (image, mask)
|
||||
|
||||
metadata = self.metadata[idx]
|
||||
label = torch.tensor(self.labels[idx], dtype=torch.long)
|
||||
return image, mask, metadata, label, idx
|
||||
|
||||
|
||||
@@ -397,18 +427,18 @@ def run_fold(train_loader, val_loader, config, fold_num, exp_dir, logger, model,
|
||||
"""
|
||||
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 ‼️‼️‼️‼️
|
||||
species_criterion = None # ‼️‼️‼️‼️ Define your criterion ‼️‼️‼️‼️
|
||||
mask_criterion = None # ‼️‼️‼️‼️ Define your criterion ‼️‼️‼️‼️
|
||||
optimizer = None # ‼️‼️‼️‼️ 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 =
|
||||
embedding_bank, all_labels = None, None # ‼️ TODO ‼️
|
||||
# ‼️‼️‼️‼️ Compute embedding bank for validation set ‼️‼️‼️‼️
|
||||
embedding_bank_val, all_labels_val =
|
||||
embedding_bank_val, all_labels_val = None, None # ‼️ TODO ‼️
|
||||
|
||||
for epoch in range(config['num_epochs']):
|
||||
trn_loss = 0.0
|
||||
@@ -424,7 +454,7 @@ def run_fold(train_loader, val_loader, config, fold_num, exp_dir, logger, model,
|
||||
|
||||
# ‼️‼️‼️‼️ ZERO GRAD! ‼️‼️‼️‼️
|
||||
|
||||
outputs, masks_pred, embeddings = # ‼️‼️‼️‼️ make predictions ‼️‼️‼️‼️
|
||||
outputs, masks_pred, embeddings = None # ‼️‼️‼️‼️ make predictions ‼️‼️‼️‼️
|
||||
|
||||
# update embedding bank with current batch
|
||||
all_embeddings = embeddings.detach()
|
||||
@@ -435,21 +465,21 @@ def run_fold(train_loader, val_loader, config, fold_num, exp_dir, logger, model,
|
||||
embedding_bank[idxs] = all_embeddings
|
||||
|
||||
# Classification loss
|
||||
classification_loss = # ‼️‼️‼️‼️ compute species loss ‼️‼️‼️‼️
|
||||
classification_loss = None # ‼️‼️‼️‼️ compute species loss ‼️‼️‼️‼️
|
||||
|
||||
# Segmentation loss - ensure both tensors are float32 and same shape
|
||||
segmentation_loss = # ‼️‼️‼️‼️ compute mask loss ‼️‼️‼️‼️
|
||||
segmentation_loss = None # ‼️‼️‼️‼️ compute mask loss ‼️‼️‼️‼️
|
||||
|
||||
# triplet loss
|
||||
triplets = # ‼️‼️‼️‼️ create triplets ‼️‼️‼️‼️
|
||||
triplets = None # ‼️‼️‼️‼️ create triplets ‼️‼️‼️‼️
|
||||
|
||||
if len(triplets) > 0:
|
||||
triplet_loss = # ‼️‼️‼️‼️ compute triplet loss ‼️‼️‼️‼️
|
||||
triplet_loss = None # ‼️‼️‼️‼️ compute triplet loss ‼️‼️‼️‼️
|
||||
else:
|
||||
triplet_loss = torch.tensor(0.0, device=images.device)
|
||||
|
||||
# Combine losses with weights
|
||||
loss = # ‼️‼️‼️‼️ compute combined loss ‼️‼️‼️‼️
|
||||
loss = None # ‼️‼️‼️‼️ compute combined loss ‼️‼️‼️‼️
|
||||
|
||||
# Check for invalid loss values
|
||||
if torch.isnan(loss) or torch.isinf(loss):
|
||||
@@ -517,20 +547,20 @@ def run_fold(train_loader, val_loader, config, fold_num, exp_dir, logger, model,
|
||||
|
||||
# Classification loss
|
||||
|
||||
classification_loss = # ‼️‼️‼️‼️ compute species loss ‼️‼️‼️‼️
|
||||
classification_loss = None # ‼️‼️‼️‼️ compute species loss ‼️‼️‼️‼️
|
||||
|
||||
# Segmentation loss
|
||||
segmentation_loss = # ‼️‼️‼️‼️ compute mask loss ‼️‼️‼️‼️
|
||||
segmentation_loss = None # ‼️‼️‼️‼️ compute mask loss ‼️‼️‼️‼️
|
||||
# triplet loss using updated embedding bank
|
||||
triplets = # ‼️‼️‼️‼️ create triplets ‼️‼️‼️‼️
|
||||
triplets = None # ‼️‼️‼️‼️ create triplets ‼️‼️‼️‼️
|
||||
|
||||
if len(triplets) > 0:
|
||||
triplet_loss = # ‼️‼️‼️‼️ compute triplet loss ‼️‼️‼️‼️
|
||||
triplet_loss = None # ‼️‼️‼️‼️ compute triplet loss ‼️‼️‼️‼️
|
||||
else:
|
||||
triplet_loss = torch.tensor(0.0, device=images.device)
|
||||
|
||||
# Combined loss
|
||||
loss = # ‼️‼️‼️‼️ compute combined loss ‼️‼️‼️‼️
|
||||
loss = None # ‼️‼️‼️‼️ compute combined loss ‼️‼️‼️‼️
|
||||
|
||||
batch_loss = loss.item()
|
||||
val_loss += batch_loss
|
||||
|
||||
Reference in new issue
Block a user