as a super advanced machine learning software engineer help me fix this error
i use this method and my data are located correctly
export XVIEW3_DIR=/Volumes/Crucial/
for example
this folder in error is located
"Volumes/Crucial/data/full/train/2f53eb6658f5d979t"
please check all the models that load the data
[DEBUG] Number of heads instantiated: 2
[DEBUG] Head 0 type: <class 'xview3.centernet.models.heads.decoupled_head.DecoupledHeadGroupNormLateShuffle'>
[DEBUG] Head 1 type: <class 'xview3.centernet.models.heads.yolo_head.YOLOHead'>
[2024-10-04 18:20:05,208][timm.models._builder][INFO] - Loading pretrained weights from Hugging Face hub (timm/efficientnetv2_rw_s.ra2_in1k)
[2024-10-04 18:20:05,662][timm.models._hub][INFO] - [timm/efficientnetv2_rw_s.ra2_in1k] Safe alternative available for 'pytorch_model.bin' (as 'model.safetensors'). Loading weights using safetensors.
[2024-10-04 18:20:05,882][timm.models._builder][WARNING] - Unexpected keys (bn2.bias, bn2.num_batches_tracked, bn2.running_mean, bn2.running_var, bn2.weight, classifier.bias, classifier.weight, conv_head.weight) found while loading pretrained weights. This may be expected if model is being adapted.
[2024-10-04 18:20:06,125][timm.models._builder][INFO] - Loading pretrained weights from Hugging Face hub (timm/efficientnetv2_rw_s.ra2_in1k)
[2024-10-04 18:20:06,551][timm.models._hub][INFO] - [timm/efficientnetv2_rw_s.ra2_in1k] Safe alternative available for 'pytorch_model.bin' (as 'model.safetensors'). Loading weights using safetensors.
[2024-10-04 18:20:06,562][timm.models._builder][INFO] - Converted input conv conv_stem pretrained weights from 3 to 2 channel(s)
[2024-10-04 18:20:06,578][timm.models._builder][WARNING] - Unexpected keys (bn2.bias, bn2.num_batches_tracked, bn2.running_mean, bn2.running_var, bn2.weight, classifier.bias, classifier.weight, conv_head.weight) found while loading pretrained weights. This may be expected if model is being adapted.
[2024-10-04 18:20:06,579][xview3.centernet.models.centernet_unet][INFO] - Adjusted encoder's first conv layer 'initial_conv' to have 2 input channels.
[2024-10-04 18:20:11,977][main][INFO] - Total parameters in the model: {'total': 263815591, 'trainable': 263815591, 'encoder': 21657072, 'decoder': 14193536}
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel2.py", line 683, in
main()
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/main.py", line 94, in decorated_main
_run_hydra(
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/utils.py", line 394, in _run_hydra
_run_app(
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/utils.py", line 457, in _run_app
run_and_report(
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/utils.py", line 220, in run_and_report
return func()
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/utils.py", line 458, in
lambda: hydra.run(
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/_internal/hydra.py", line 119, in run
ret = run_job(
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/hydra/core/utils.py", line 186, in run_job
ret.return_value = task_function(task_cfg)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel2.py", line 679, in main
pipeline.train()
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel2.py", line 441, in train
self.optimizer, self.scheduler, optimizer_callbacks, self.scaler = self.build_optimizer(self.model, train_loader)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel2.py", line 388, in build_optimizer
scaler = torch.amp.GradScaler(enabled=optimizer_config.get("fp16", False)) if device != TorchDevice.CPU_DEVICE else None
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/amp/grad_scaler.py", line 132, in init
warnings.warn(
File "/opt/anaconda3/envs/sam3/lib/python3.9/warnings.py", line 109, in _showwarnmsg
sw(msg.message, msg.category, msg.filename, msg.lineno,
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel2.py", line 70, in warn_with_traceback
traceback.print_stack(file=log)
/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/amp/grad_scaler.py:132: UserWarning:
torch.cuda.amp.GradScaler is enabled, but CUDA is not available. Disabling.
1/100 * Epoch (train): 0% 0/27 [00:00<?, ?it/s]DEBUG:rasterio.session:Could not import boto3, continuing with reduced functionality.
DEBUG:rasterio.session:Could not import boto3, continuing with reduced functionality.
DEBUG:rasterio.session:Could not import boto3, continuing with reduced functionality.
DEBUG:rasterio.session:Could not import boto3, continuing with reduced functionality.
Error executing job with overrides: []
Traceback (most recent call last):
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel2.py", line 679, in main
pipeline.train()
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/train_multilabel2.py", line 536, in train
runner.train(
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/catalyst/runners/runner.py", line 170, in train
distributed_cmd_run(self.run_experiment, distributed)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/catalyst/utils/scripts.py", line 176, in distributed_cmd_run
worker_fn(*args, **kwargs)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/catalyst/core/runner.py", line 929, in run_experiment
self._run_event("on_exception")
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/catalyst/core/runner.py", line 724, in _run_event
getattr(callback, event)(self)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/catalyst/callbacks/exception.py", line 34, in on_exception
raise exception
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/catalyst/core/runner.py", line 917, in run_experiment
self._run_stage(stage)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/catalyst/core/runner.py", line 885, in _run_stage
self._run_epoch(stage=stage, epoch=self.epoch)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/catalyst/core/runner.py", line 864, in _run_epoch
self._run_loader(loader)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/catalyst/core/runner.py", line 798, in _run_loader
for i, batch in enumerate(loader):
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/dataloader.py", line 630, in next
data = self._next_data()
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/dataloader.py", line 1344, in _next_data
return self._process_data(data)
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/dataloader.py", line 1370, in _process_data
data.reraise()
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/_utils.py", line 706, in reraise
raise exception
FileNotFoundError: Caught FileNotFoundError in DataLoader worker process 0.
Original Traceback (most recent call last):
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/_utils/worker.py", line 309, in _worker_loop
data = fetcher.fetch(index) # type: ignore[possibly-undefined]
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/_utils/fetch.py", line 52, in fetch
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/opt/anaconda3/envs/sam3/lib/python3.9/site-packages/torch/utils/data/_utils/fetch.py", line 52, in
data = [self.dataset[idx] for idx in possibly_batched_index]
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/dataset/random_crop_dataset.py", line 159, in getitem
targets = self.load_image(index, crop_coords=crop_coords)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/dataset/keypoint_dataset.py", line 91, in load_image
individual_channels = self.read_image_fn(self.scenes[index], channels=self.input_channels, crop_coords=crop_coords)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/dataset/io.py", line 151, in read_multichannel_image
img = read_tiff(channel_image_fname, crop_coords=crop_coords).astype(np.float32, copy=False)
File "/Users/samerkharboush/Downloads/SAR-MPS-OptunaNasFbnYoloTransformers/xview3/dataset/io.py", line 37, in read_tiff
raise FileNotFoundError(image_fname)
FileNotFoundError: data/full/train/2f53eb6658f5d979t/VH_dB.tif
Set the environment variable HYDRA_FULL_ERROR=1 for a complete stack trace.
1/100 * Epoch (train): 0% 0/27 [00:14<?, ?it/s]
(sam3) samerkharboush@Samers-MBP SAR-MPS-OptunaNasFbnYoloTransformers %
some data loading files
##data_module.py
import os
from collections import namedtuple
from typing import Tuple, Optional, Union, Dict
import numpy as np
import pandas as pd
import torch
from omegaconf import DictConfig
from pytorch_toolbelt.utils import to_numpy
all = [
"XView3DataModule",
"ignore_low_confidence_objects",
"filter_low_confidence_objects",
"drop_unused_columns",
"MultilabelTargets",
]
from xview3.constants import PIX_TO_M, IGNORE_LABEL
from .splitters import *
def ignore_low_confidence_objects(df: pd.DataFrame) -> pd.DataFrame:
"""
Set is_vessel, is_fishing and vessel_length_m fields to nan for low-confidence objects.
window = None
if crop_coords is not None:
(row_start, row_stop), (col_start, col_stop) = crop_coords
window = Window.from_slices((row_start, row_stop), (col_start, col_stop))
if not os.path.isfile(image_fname):
raise FileNotFoundError(image_fname)
with rasterio.open(image_fname) as f:
return f.read(1, window=window)
def read_multichannel_image(scene_id, channels: List[str], crop_coords=None):
individual_channels = {}
for channel in channels:
if channel in {"diff(vv,vh)", "mean(vv,vh)"}:
continue
def stack_multichannel_image(individual_channels: Dict[str, np.ndarray], input_channels: List[str]):
channels = []
for channel_name in input_channels:
img = individual_channels[channel_name]
channels.append(img)
code
image = np.dstack(channels)
return image
###multilabel_dataset.py
import os
from functools import partial
from typing import List, Tuple, Optional, Callable, Dict, Any, Union
from xview3.centernet.models.heads.yolo_head import generate_yolo_targets
import albumentations as A
import cv2
import numpy as np
import pandas as pd
import torch
from torch import nn
from omegaconf import DictConfig
from pytorch_toolbelt.datasets import INPUT_IMAGE_KEY, INPUT_INDEX_KEY
from pytorch_toolbelt.utils.torch_utils import image_to_tensor
from sklearn.neighbors import BallTree
from sklearn.utils import compute_sample_weight
from torch.utils.data import Sampler, WeightedRandomSampler
from torch.utils.data.dataloader import default_collate
from tqdm import tqdm
from omegaconf import OmegaConf
from .bboxer import (
MultilabelCircleNetCoder,
MultilabelCircleNetEncodeResult,
)
from .constants import *
from ..constants import *
all = [
"MultilabelCircleNetDataModule",
"MultilabelCircleNetFixedCropDataset",
"MultilabelCircleNetRandomCropDataset",
"centernet_collate",
]
from ..dataset import (
RandomCropFromImageDataset,
RandomCropAroundEachObjectDataset,
XView3DataModule,
KeypointsDataset,
FixedCropFromImageDataset,
read_multichannel_image,
)
from ..dataset.random_crop_dataset import encode_labels
from ..metric import get_shoreline_shoreline_contours
excluded_items = {k: [] for k in skip_keys}
included_items = []
for b in batch:
included = {k: v for k, v in b.items() if k not in skip_keys}
included_items.append(included)
for k in skip_keys:
if k in b:
excluded_items[k].append(b[k])
# Use default_collate for included items (numerical tensors)
batch_dict = default_collate(included_items)
# Process excluded items (categorical lists)
for k, v in excluded_items.items():
if v:
# Keep categorical fields as lists of lists or lists of tuples
batch_dict[k] = v # List of lists or list of tuples
# Handle channels_last if necessary
if channels_last and INPUT_IMAGE_KEY in batch_dict:
batch_dict[INPUT_IMAGE_KEY] = batch_dict[INPUT_IMAGE_KEY].to(memory_format=torch.channels_last)
return batch_dict
class MultilabelCircleNetTargetsMixin:
box_coder: MultilabelCircleNetCoder
code
def __init__(
self,
stride=32,
confidence_mapping=None,
vessel_mapping=None,
fishing_mapping=None,
ignore_value=-1,
):
self.stride = stride
self.confidence_mapping = confidence_mapping or {0: 0.0, 1: 1.0}
self.vessel_mapping = vessel_mapping or {0: 0, 1: 1}
self.fishing_mapping = fishing_mapping or {0: 0, 1: 1}
self.ignore_value = ignore_value
def generate_yolo_targets(
self,
centers,
confidences,
is_vessel,
is_fishing,
lengths,
grid_height,
grid_width,
):
num_objects = len(centers)
yolo_targets = np.zeros(
(grid_height, grid_width, 6), dtype=np.float32
) # Adjust the last dimension as needed
for i in range(num_objects):
center = centers[i]
confidence = self.confidence_mapping.get(confidences[i], 0.0)
vessel_type = self.vessel_mapping.get(is_vessel[i], self.ignore_value)
fishing_status = self.fishing_mapping.get(is_fishing[i], self.ignore_value)
length = lengths[i]
# Assuming centers are normalized between 0 and 1
grid_x = int(center[0] * grid_width)
grid_y = int(center[1] * grid_height)
# Ensure grid indices are within bounds
grid_x = min(max(grid_x, 0), grid_width - 1)
grid_y = min(max(grid_y, 0), grid_height - 1)
# Assign the values
yolo_targets[grid_y, grid_x, 0:4] = np.array([center[0], center[1], length, length])
yolo_targets[grid_y, grid_x, 4] = confidence
yolo_targets[grid_y, grid_x, 5] = vessel_type
return yolo_targets
def build_centernet_sample(
self,
image,
centers,
confidences,
lengths,
is_vessel,
is_fishing,
index,
image_id,
is_near_shore,
location,
folder: str,
crop_coords: Tuple[Tuple[int, int], Tuple[int, int]],
) -> Dict[str, Any]:
box_coder = self.box_coder.create_box_coder_for_image_size(image.shape[:2])
# Define grid dimensions based on image size and stride
image_height, image_width = image.shape[:2]
grid_height = image_height // self.box_coder.output_stride
grid_width = image_width // self.box_coder.output_stride
# Now use grid_height and grid_width
yolo_targets = self.box_coder.generate_yolo_targets(
centers,
confidences,
is_vessel,
is_fishing,
lengths,
grid_height,
grid_width
)
# Convert numerical fields to NumPy arrays with explicit dtypes
centers_np = np.array(centers, dtype=np.float32)
lengths_np = np.array(lengths, dtype=np.float32)
is_vessel_np = np.array(is_vessel, dtype=np.float32)
is_fishing_np = np.array(is_fishing, dtype=np.float32)
is_near_shore_np = np.array(is_near_shore, dtype=np.float32)
# Validate consistency in lengths
num_objects = len(confidences)
if not all([
len(centers_np) == num_objects,
len(lengths_np) == num_objects,
len(is_vessel_np) == num_objects,
len(is_fishing_np) == num_objects,
]):
raise ValueError("Mismatch in number of objects across targets")
# Construct the result dictionary with tensors for numerical fields and lists for categorical fields
result = {
INPUT_INDEX_KEY: index,
INPUT_IMAGE_KEY: image_to_tensor(image), # Keeps image as tensor
TARGET_CENTERS_KEY: torch.from_numpy(centers_np), # Convert to tensor
TARGET_VESSEL_KEY: torch.from_numpy(is_vessel_np), # Convert to tensor
TARGET_FISHING_KEY: torch.from_numpy(is_fishing_np), # Convert to tensor
TARGET_LENGTHS_KEY: torch.from_numpy(lengths_np), # Convert to tensor
INPUT_CONFIDENCE_KEY: confidences, # Keep as list of categorical values
INPUT_IS_NEAR_SHORE_KEY: torch.from_numpy(is_near_shore_np), # Convert to tensor
INPUT_LOCATION_ID_KEY: location,
INPUT_FOLDER_KEY: folder,
INPUT_SCENE_ID_KEY: image_id,
TARGET_SAMPLE_WEIGHT: {"train": 0.25, "validation": 1.0, "valid": 1.0, "test": 0.1}[folder],
}
if crop_coords is not None:
result[INPUT_SCENE_CROP_KEY] = crop_coords # Keep as tuple of tuples
# Encode targets using the box coder
centernet_targets: MultilabelCircleNetEncodeResult = box_coder.encode(
centers=centers_np,
confidences=confidences, # Pass as list of categorical labels
lengths=lengths_np,
is_vessel=is_vessel_np,
is_fishing=is_fishing_np,
)
# Convert encoded targets to PyTorch tensors
result[CENTERNET_TARGET_OBJECTNESS_MAP] = torch.from_numpy(centernet_targets.heatmap).float()
result[CENTERNET_TARGET_VESSEL_MAP] = torch.from_numpy(centernet_targets.is_vessel).float()
result[CENTERNET_TARGET_FISHING_MAP] = torch.from_numpy(centernet_targets.is_fishing).float()
result[CENTERNET_TARGET_SIZE] = torch.from_numpy(centernet_targets.lengths).float()
result[CENTERNET_TARGET_OFFSET] = torch.from_numpy(centernet_targets.offset).float()
result[CENTERNET_TARGET_YOLO] = torch.from_numpy(yolo_targets).float()
return result
The error you're encountering—FileNotFoundError: data/full/train/2f53eb6658f5d979t/VH_dB.tif—suggests that your script is attempting to access a file using a relative path (data/full/train/...) instead of an absolute path (/Volumes/Crucial/data/full/train/...). This discrepancy is likely the root cause of the issue. Let's break down the problem and offer a comprehensive solution.
Understanding the Error
Environment Variable Configuration:
You have set the environment variable XVIEW3_DIR to /Volumes/Crucial/, which is intended to be the base directory for your data.
Error Traceback:
The error occurs when the script tries to load the file VH_dB.tif from the path data/full/train/2f53eb6658f5d979t/VH_dB.tif.
This path is relative, meaning it depends on the current working directory from which the script is executed.
Expected Path:
Given XVIEW3_DIR=/Volumes/Crucial/, the absolute path to the file should be /Volumes/Crucial/data/full/train/2f53eb6658f5d979t/VH_dB.tif.
Possible Causes:
Relative vs. Absolute Paths: The script is constructing paths relative to the current working directory instead of using the absolute path based on XVIEW3_DIR.
Incorrect Path Construction: In the data loading mechanisms, the base directory (XVIEW3_DIR) might not be properly prepended to the relative paths.
Step-by-Step Solution
1. Verify the Existence of the File
Before diving into the code, ensure that the file /Volumes/Crucial/data/full/train/2f53eb6658f5d979t/VH_dB.tif actually exists.
bash
ls /Volumes/Crucial/data/full/train/2f53eb6658f5d979t/VH_dB.tif
If the file exists, proceed to the next steps.
If the file does not exist, verify that your data is correctly placed in the specified directory.
2. Ensure Absolute Paths in Your Data Module
The primary issue appears to be the construction of file paths without including the base directory (XVIEW3_DIR). To resolve this, you need to ensure that all paths are absolute by prepending XVIEW3_DIR to them.
a. Modify data_module.py
In your MultilabelCircleNetDataModule, when constructing scene_path or any other paths, ensure that XVIEW3_DIR is included. Here's how you can adjust your methods:
This ensures that all scene paths in the DataFrame are absolute.
4. Verify Environment Variable Usage
Ensure that XVIEW3_DIR is correctly set and accessed within your code.
Check Environment Variable:
python
import os
xview3_dir = os.environ.get('XVIEW3_DIR')
if not xview3_dir:
raise EnvironmentError("Environment variable 'XVIEW3_DIR' is not set.")
Usage in Code:
Make sure all references to data directories use xview3_dir or self.data_dir accordingly.
5. Additional Recommendations
Logging Absolute Paths: To debug, add logging statements to print out the absolute paths being accessed. This can help verify that paths are constructed correctly.
python
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# When constructing scene_path
scene_path = os.path.join(self.data_dir, train_df.scene_path.values[0])
logger.debug(f"Loading scene from: {scene_path}")
Handle Missing Files Gracefully: While it's essential to fix the path issues, adding checks for file existence can make your code more robust.
python
if not os.path.isfile(channel_image_fname):
logger.error(f"File not found: {channel_image_fname}")
raise FileNotFoundError(f"Required file missing: {channel_image_fname}")
Ensure Consistent Data Directory Structure: Verify that all parts of your code (training, validation, testing) consistently use the XVIEW3_DIR base directory.
6. Summary of Changes
Prepend XVIEW3_DIR to All Relative Paths:
Ensure that every file path used in your data loading pipeline starts with /Volumes/Crucial/ (or the value of XVIEW3_DIR).
Update Data Module Methods:
Modify methods like get_random_crop_each_object_dataset and get_validation_dataset to construct absolute paths.
Update DataFrame Entries:
Convert relative paths in your DataFrame to absolute paths based on XVIEW3_DIR.
Add Logging for Debugging:
Implement logging to verify that paths are correctly constructed during runtime.
7. Example Implementation
Here's an example of how you might adjust the get_random_crop_each_object_dataset method in data_module.py:
python
8. Final Checks
After implementing the changes:
Run a Test Load:
Before training, attempt to load a single sample to ensure paths are correctly set.
python
# Example test
sample = train_ds[0]
print(sample.keys())
print(sample['INPUT_IMAGE_KEY'].shape)
Monitor Logs:
Check the debug logs to verify that the absolute paths are being used.
Re-run the Training Script:
Execute your training script again:
bash
python train_multilabel2.py
Ensure that the FileNotFoundError no longer appears.
Conclusion
The FileNotFoundError is primarily due to incorrect path constructions where relative paths are being used instead of absolute paths based on the XVIEW3_DIR environment variable. By ensuring that all file paths are constructed absolutely, you can resolve this error. Implement the recommended changes, verify path correctness through logging, and ensure that all components of your data pipeline consistently use absolute paths derived from XVIEW3_DIR.
If you continue to face issues after these adjustments, consider the following additional steps:
Permissions Check: Ensure that the script has the necessary permissions to read from /Volumes/Crucial/.
Mount Points: Verify that the /Volumes/Crucial/ drive is properly mounted and accessible during script execution.
Environment Consistency: Ensure that environment variables are correctly set in the environment where the script is running, especially if using IDEs or job schedulers that might have different environments.
Feel free to reach out with further details if the problem persists!
Not yet included in a published release.
import os
import logging
from functools import partial
from typing import Callable, Dict, List, Optional, Tuple
import albumentations as A
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Sampler, WeightedRandomSampler
from tqdm import tqdm
from .multilabel_dataset import MultilabelCircleNetRandomCropAroundEachObjectDataset, MultilabelCircleNetCoder
logger = logging.getLogger(__name__)
class MultilabelCircleNetDataModule(XView3DataModule):
def __init__(self, config: DictConfig):
super().__init__(data_dir=config.dataset.data_dir) # Ensure data_dir is /Volumes/Crucial/
self.config = config
@classmethod
def get_multilabel_targets_from_df(cls, df: pd.DataFrame):
# Existing implementation
pass
def get_random_crop_each_object_dataset(
self,
train_df: pd.DataFrame,
train_image_size: Tuple[int, int],
input_channels: List[str],
box_coder_config: Dict,
normalization: Dict[str, A.ImageOnlyTransform],
num_samples: int = 1024,
individual_augmentations: Optional[Dict] = None,
augmentations: Optional[List[A.BasicTransform]] = None,
balance_crowd=False,
balance_per_scene=True,
balance_near_shore=None,
balance_vessel_type=False,
balance_fishing_type=False,
balance_by_type=False,
balance_location=False,
channels_last=False,
read_image_fn=read_multichannel_image,
) -> Tuple[KeypointsDataset, Optional[Sampler]]:
if augmentations is None:
augmentations = []
elif isinstance(augmentations, A.Compose):
augmentations = augmentations.transforms
transform = A.Compose(
augmentations
+ [
A.PadIfNeeded(
train_image_size[0],
train_image_size[1],
value=float("nan"),
border_mode=cv2.BORDER_CONSTANT,
),
],
keypoint_params=self.get_keypoint_params(),
)
# Instantiate the box_coder using the configuration
box_coder = MultilabelCircleNetCoder.from_config(box_coder_config)
all_images = []
all_coordinates = []
all_confidences = []
all_is_vessel = []
all_is_fishing = []
all_lengths = []
all_is_near_shore = []
all_locations = []
all_size = []
all_scenes = []
all_locations = []
center_is_vessel = []
center_is_fishing = []
center_neighbors = []
center_near_shore = []
for scene_id in tqdm(train_df.scene_id.unique(), desc="Preparing training dataset"):
# Get detections only for current scene
scene_df = train_df[train_df.scene_id == scene_id]
scene_size = scene_sizes[scene_id]
scene_relative_path = scene_df.scene_path.values[0]
# Construct absolute path
scene_path = os.path.join(self.data_dir, scene_relative_path)
logger.debug(f"Loading scene from: {scene_path}")
if not os.path.isdir(scene_path):
logger.error(f"Scene directory does not exist: {scene_path}")
raise FileNotFoundError(f"Scene directory missing: {scene_path}")
location_id = scene_df.location.values[0]
targets = self.get_multilabel_targets_from_df(scene_df)
distance_from_shore_km = scene_df.distance_from_shore_km
near_shore = (distance_from_shore_km < 2).values
# Append data
all_images.extend([scene_path] * len(scene_df))
all_locations.extend([location_id] * len(scene_df))
all_coordinates.extend([targets.centers] * len(scene_df))
all_confidences.extend([targets.confidences] * len(scene_df))
all_is_vessel.extend([targets.is_vessel] * len(scene_df))
all_is_fishing.extend([targets.is_fishing] * len(scene_df))
all_lengths.extend([targets.lengths] * len(scene_df))
all_is_near_shore.extend([targets.is_near_shore] * len(scene_df))
all_size.extend([scene_size] * len(scene_df))
# Balancing weights
tree = BallTree(targets.centers, leaf_size=8, metric="chebyshev")
neighbors = tree.query_radius(targets.centers, r=max(train_image_size) // 2, count_only=True)
center_neighbors.extend(neighbors)
center_near_shore.extend(near_shore)
center_is_vessel.extend(targets.is_vessel)
center_is_fishing.extend(targets.is_fishing)
train_ds = MultilabelCircleNetRandomCropAroundEachObjectDataset(
scenes=all_images,
locations=all_locations,
centers=all_coordinates,
confidences=all_confidences,
crop_centers=np.array(all_coordinates),
lengths=all_lengths,
is_vessel=all_is_vessel,
is_fishing=all_is_fishing,
is_near_shore=all_is_near_shore,
scene_sizes=all_size,
individual_transforms=individual_augmentations,
input_channels=input_channels,
transform=transform,
normalization=normalization,
read_image_fn=read_image_fn,
box_coder=box_coder,
crop_size=train_image_size,
channels_last=channels_last,
)
# Continue with sampler creation...
# Your existing sampler logic
return train_ds, train_sampler