File size: 6,612 Bytes
1f2e262 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | """
Brain Tumor Dataset - Stage 4
Custom PyTorch Dataset for loading preprocessed MRI images.
"""
from pathlib import Path
from typing import Optional, Tuple, Callable
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset
# Class name to index mapping
CLASS_TO_IDX = {
'glioma': 0,
'meningioma': 1,
'notumor': 2,
'pituitary': 3
}
IDX_TO_CLASS = {v: k for k, v in CLASS_TO_IDX.items()}
class BrainTumorDataset(Dataset):
"""
Custom Dataset for brain tumor MRI images.
Loads preprocessed images from cached numpy arrays and applies transforms.
"""
def __init__(
self,
data_dir: Path,
manifest_df: pd.DataFrame,
transform: Optional[Callable] = None
):
"""
Initialize dataset.
Args:
data_dir: Root directory containing preprocessed data
manifest_df: DataFrame with columns ['filepath', 'class', 'split']
transform: Optional transform to apply to images
"""
self.data_dir = Path(data_dir)
self.manifest = manifest_df.reset_index(drop=True)
self.transform = transform
# Validate manifest columns
required_cols = ['filepath', 'class', 'split']
if not all(col in self.manifest.columns for col in required_cols):
raise ValueError(f"Manifest must contain columns: {required_cols}")
# Validate classes
unique_classes = set(self.manifest['class'].unique())
expected_classes = set(CLASS_TO_IDX.keys())
if not unique_classes.issubset(expected_classes):
raise ValueError(
f"Unknown classes in manifest: {unique_classes - expected_classes}"
)
def __len__(self) -> int:
"""Return number of samples in dataset."""
return len(self.manifest)
def __getitem__(self, idx: int) -> Tuple[torch.Tensor, int]:
"""
Get a single sample.
Args:
idx: Index of sample to retrieve
Returns:
Tuple of (image_tensor, label)
Raises:
FileNotFoundError: If the .npy file doesn't exist
ValueError: If image cannot be loaded
"""
# Get metadata
row = self.manifest.iloc[idx]
filepath = self.data_dir / row['filepath']
class_name = row['class']
label = CLASS_TO_IDX[class_name]
# Load numpy array
if not filepath.exists():
raise FileNotFoundError(f"Image file not found: {filepath}")
try:
image = np.load(filepath)
except Exception as e:
raise ValueError(f"Failed to load {filepath}: {e}")
# Validate image shape
if image.ndim != 3 or image.shape[2] != 3:
raise ValueError(
f"Expected image shape (H, W, 3), got {image.shape} for {filepath}"
)
# Apply transforms
if self.transform is not None:
image = self.transform(image)
else:
# Default: convert to tensor
image = torch.from_numpy(image).permute(2, 0, 1).float() / 255.0
return image, label
def get_class_counts(self) -> dict:
"""
Get count of samples per class.
Returns:
Dictionary mapping class names to counts
"""
return self.manifest['class'].value_counts().to_dict()
def get_class_weights(self) -> torch.Tensor:
"""
Compute class weights for balanced training.
Uses inverse frequency weighting.
Returns:
Tensor of shape (num_classes,) with weights
"""
class_counts = self.manifest['class'].value_counts()
total = len(self.manifest)
num_classes = len(CLASS_TO_IDX)
# Inverse frequency
weights = torch.zeros(num_classes)
for class_name, count in class_counts.items():
idx = CLASS_TO_IDX[class_name]
weights[idx] = total / (num_classes * count)
return weights
def get_sample_info(self, idx: int) -> dict:
"""
Get metadata for a sample without loading the image.
Args:
idx: Index of sample
Returns:
Dictionary with sample metadata
"""
row = self.manifest.iloc[idx]
return {
'filepath': str(self.data_dir / row['filepath']),
'class': row['class'],
'label': CLASS_TO_IDX[row['class']],
'split': row['split']
}
def create_dataloaders(
manifest_path: Path,
processed_dir: Path,
train_transform: Callable,
val_transform: Callable,
batch_size: int = 32,
num_workers: int = 4,
pin_memory: bool = True
) -> Tuple[torch.utils.data.DataLoader, torch.utils.data.DataLoader]:
"""
Create train and validation dataloaders from manifest.
Args:
manifest_path: Path to manifest CSV file
processed_dir: Root directory of preprocessed data
train_transform: Transform for training data
val_transform: Transform for validation data
batch_size: Batch size for dataloaders
num_workers: Number of worker processes
pin_memory: Whether to pin memory for faster GPU transfer
Returns:
Tuple of (train_loader, val_loader)
"""
# Load manifest
manifest = pd.read_csv(manifest_path)
# Split into train and val
train_df = manifest[manifest['split'] == 'train'].copy()
val_df = manifest[manifest['split'] == 'val'].copy()
# Create datasets
train_dataset = BrainTumorDataset(
data_dir=processed_dir,
manifest_df=train_df,
transform=train_transform
)
val_dataset = BrainTumorDataset(
data_dir=processed_dir,
manifest_df=val_df,
transform=val_transform
)
# Create dataloaders
train_loader = torch.utils.data.DataLoader(
train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=num_workers,
pin_memory=pin_memory,
persistent_workers=num_workers > 0
)
val_loader = torch.utils.data.DataLoader(
val_dataset,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers,
pin_memory=pin_memory,
persistent_workers=num_workers > 0
)
return train_loader, val_loader
|