| |
|
|
| import os |
| import torch |
| import numpy as np |
| from PIL import Image |
| import matplotlib.pyplot as plt |
| from tqdm import tqdm |
| import torchvision.transforms as transforms |
| import torchvision.datasets as datasets |
| from torchvision.models import vgg16 |
| import torch.nn.functional as F |
| import random |
| from collections import defaultdict |
| import json |
| import warnings |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| import threading |
| import multiprocessing as mp |
| import time |
|
|
| class SimpleImageDataLoader: |
| def __init__(self, dataset_type='imagenet100', dataset_path=None, samples_per_block=50): |
| self.dataset_type = dataset_type |
| self.dataset_path = dataset_path |
| self.samples_per_block = samples_per_block |
| self.class_info = {} |
| self.total_blocks_per_class = {} |
| self.vgg_model = None |
| |
| |
| self.train_class_info = {} |
| self.val_class_info = {} |
| self.train_blocks_per_class = {} |
| self.val_blocks_per_class = {} |
| |
| |
| self._scan_dataset() |
|
|
| def _scan_dataset(self): |
| """扫描数据集,获取每个类别的图片路径和块数""" |
| print(f"Scanning {self.dataset_type} dataset...") |
| |
| if self.dataset_type == 'imagenet100': |
| self._scan_imagenet100() |
| elif self.dataset_type == 'imagenet10': |
| self._scan_imagenet10() |
| elif self.dataset_type in ['cifar10', 'cifar100']: |
| self._scan_cifar() |
| elif self.dataset_type == 'folder': |
| self._scan_folder() |
| |
| print(f"Found {len(self.class_info)} classes") |
| for class_idx, info in list(self.class_info.items())[:5]: |
| print(f" Class {class_idx}: {info['total_images']} images, {self.total_blocks_per_class[class_idx]} blocks") |
| if len(self.class_info) > 5: |
| print(f" ... and {len(self.class_info) - 5} more classes") |
|
|
| def _scan_imagenet100(self): |
| """修改后的ImageNet100扫描 - 分别存储train和val""" |
| print(f"Scanning {self.dataset_type} dataset...") |
| |
| |
| train_folders = [] |
| val_folder = None |
| |
| if os.path.exists(self.dataset_path): |
| for item in os.listdir(self.dataset_path): |
| item_path = os.path.join(self.dataset_path, item) |
| if os.path.isdir(item_path): |
| if item.startswith('train.X'): |
| train_folders.append(item_path) |
| elif item == 'val.X': |
| val_folder = item_path |
| |
| train_folders.sort() |
| |
| |
| all_classes = set() |
| for train_folder in train_folders: |
| if os.path.exists(train_folder): |
| classes = [f for f in os.listdir(train_folder) |
| if os.path.isdir(os.path.join(train_folder, f)) and f.startswith('n')] |
| all_classes.update(classes) |
| |
| all_classes = sorted(list(all_classes)) |
| |
| |
| for class_idx, class_name in enumerate(all_classes): |
| train_paths = [] |
| val_paths = [] |
| |
| |
| for train_folder in train_folders: |
| class_path = os.path.join(train_folder, class_name) |
| if os.path.exists(class_path): |
| files = [f for f in os.listdir(class_path) |
| if f.lower().endswith(('.jpg', '.jpeg', '.png'))] |
| files.sort() |
| paths = [os.path.join(class_path, f) for f in files] |
| train_paths.extend(paths) |
| |
| |
| if val_folder: |
| val_class_path = os.path.join(val_folder, class_name) |
| if os.path.exists(val_class_path): |
| files = [f for f in os.listdir(val_class_path) |
| if f.lower().endswith(('.jpg', '.jpeg', '.png'))] |
| files.sort() |
| paths = [os.path.join(val_class_path, f) for f in files] |
| val_paths.extend(paths) |
| |
| |
| self.train_class_info[class_idx] = { |
| 'class_name': class_name, |
| 'image_paths': train_paths, |
| 'total_images': len(train_paths) |
| } |
| self.train_blocks_per_class[class_idx] = max(1, len(train_paths) // self.samples_per_block) |
| |
| self.val_class_info[class_idx] = { |
| 'class_name': class_name, |
| 'image_paths': val_paths, |
| 'total_images': len(val_paths) |
| } |
| self.val_blocks_per_class[class_idx] = max(1, len(val_paths) // self.samples_per_block) |
| |
| print(f"Found {len(all_classes)} classes") |
| print(f"Train images per class (first 3): {[self.train_class_info[i]['total_images'] for i in range(min(3, len(all_classes)))]}") |
| print(f"Val images per class (first 3): {[self.val_class_info[i]['total_images'] for i in range(min(3, len(all_classes)))]}") |
| |
| def _get_current_class_info(self, is_test_mode=False): |
| """根据是否为测试模式返回相应的class_info""" |
| if is_test_mode: |
| return self.val_class_info, self.val_blocks_per_class |
| else: |
| return self.train_class_info, self.train_blocks_per_class |
| |
| def load_images_for_class_block(self, class_idx, block_idx, args=None, is_test_mode=False): |
| """修改后的图片加载 - 支持train/val切换""" |
| |
| |
| class_info, _ = self._get_current_class_info(is_test_mode) |
| |
| if class_idx not in class_info: |
| return [] |
| |
| class_data = class_info[class_idx] |
| |
| if self.dataset_type in ['cifar10', 'cifar100']: |
| return self._load_cifar_block(class_idx, block_idx, is_test_mode) |
| else: |
| |
| image_paths = class_data['image_paths'] |
| start_idx = block_idx * self.samples_per_block |
| end_idx = min(start_idx + self.samples_per_block, len(image_paths)) |
| |
| if start_idx >= len(image_paths): |
| start_idx = max(0, len(image_paths) - self.samples_per_block) |
| end_idx = len(image_paths) |
| |
| block_paths = image_paths[start_idx:end_idx] |
| |
| |
| if getattr(args, 'use_vgg_features', False) and self._get_vgg_cache_dir(args): |
| return block_paths |
| else: |
| images = [] |
| for img_path in block_paths: |
| try: |
| img = Image.open(img_path).convert('RGB') |
| |
| if args and hasattr(args, 'image_noise_level') and args.image_noise_level > 0: |
| aug_type = getattr(args, 'image_aug_type', 'pixel') |
| img_tensor = self.apply_image_augmentation(img, args.image_noise_level, aug_type) |
| img = transforms.ToPILImage()(img_tensor) |
| |
| images.append(img) |
| except Exception as e: |
| print(f"Error loading {img_path}: {e}") |
| continue |
| |
| return images |
| |
| def get_epoch_mapping(self, epoch, batch_size, class_combination_seed=42, is_test_mode=False): |
| """修改后的epoch映射 - 支持train/val切换""" |
| |
| |
| class_info, blocks_per_class = self._get_current_class_info(is_test_mode) |
| num_classes = len(class_info) |
| |
| |
| random.seed(class_combination_seed + epoch) |
| np.random.seed(class_combination_seed + epoch) |
| |
| |
| total_class_combinations = num_classes * (num_classes - 1) |
| |
| |
| max_blocks = max(blocks_per_class.values()) if blocks_per_class else 1 |
| |
| batch_mappings = [] |
| |
| for batch_idx in range(batch_size): |
| global_batch_id = epoch * batch_size + batch_idx |
| |
| |
| block_round = global_batch_id // total_class_combinations |
| |
| |
| combination_idx = global_batch_id % total_class_combinations |
| |
| |
| class1 = combination_idx // (num_classes - 1) |
| class2_offset = combination_idx % (num_classes - 1) |
| class2 = class2_offset if class2_offset < class1 else class2_offset + 1 |
| |
| |
| block1 = block_round % blocks_per_class.get(class1, 1) |
| block2 = block_round % blocks_per_class.get(class2, 1) |
| |
| batch_mappings.append({ |
| 'batch_idx': batch_idx, |
| 'global_batch_id': global_batch_id, |
| 'class1': class1, |
| 'class2': class2, |
| 'block1': block1, |
| 'block2': block2, |
| 'block_round': block_round, |
| 'is_test_mode': is_test_mode |
| }) |
| |
| return batch_mappings |
| |
| def apply_image_augmentation(self, image, noise_level=0.0, aug_type='pixel'): |
| """图像增强函数""" |
| if noise_level <= 0: |
| return image |
| |
| if isinstance(image, Image.Image): |
| image = transforms.ToTensor()(image) |
| |
| if aug_type == 'pixel': |
| |
| noise = torch.randn_like(image) * noise_level |
| image = torch.clamp(image + noise, 0, 1) |
| elif aug_type == 'color': |
| |
| rand_val = random.random() |
| if rand_val < 0.33: |
| brightness_factor = 1 + (random.random() - 0.5) * noise_level |
| image = torch.clamp(image * brightness_factor, 0, 1) |
| elif rand_val < 0.66: |
| mean_val = image.mean() |
| contrast_factor = 1 + (random.random() - 0.5) * noise_level |
| image = torch.clamp((image - mean_val) * contrast_factor + mean_val, 0, 1) |
| else: |
| if image.shape[0] == 3: |
| gray = 0.299 * image[0] + 0.587 * image[1] + 0.114 * image[2] |
| saturation_factor = 1 + (random.random() - 0.5) * noise_level |
| image = torch.clamp(gray.unsqueeze(0) + (image - gray.unsqueeze(0)) * saturation_factor, 0, 1) |
| |
| return image |
| |
| def load_images_for_class_block(self, class_idx, block_idx, args=None): |
| """加载指定类别和块的图片""" |
| if class_idx not in self.class_info: |
| return [] |
| |
| class_info = self.class_info[class_idx] |
| |
| if self.dataset_type in ['cifar10', 'cifar100']: |
| return self._load_cifar_block(class_idx, block_idx) |
| else: |
| |
| image_paths = class_info['image_paths'] |
| start_idx = block_idx * self.samples_per_block |
| end_idx = min(start_idx + self.samples_per_block, len(image_paths)) |
| |
| if start_idx >= len(image_paths): |
| |
| start_idx = max(0, len(image_paths) - self.samples_per_block) |
| end_idx = len(image_paths) |
| |
| block_paths = image_paths[start_idx:end_idx] |
| |
| |
| images = [] |
| for img_path in block_paths: |
| try: |
| img = Image.open(img_path).convert('RGB') |
| |
| |
| if args and hasattr(args, 'image_noise_level') and args.image_noise_level > 0: |
| aug_type = getattr(args, 'image_aug_type', 'pixel') |
| img_tensor = self.apply_image_augmentation(img, args.image_noise_level, aug_type) |
| |
| img = transforms.ToPILImage()(img_tensor) |
| |
| images.append(img) |
| except Exception as e: |
| print(f"Error loading {img_path}: {e}") |
| continue |
| |
| return images |
| |
| def _load_cifar_block(self, class_idx, block_idx): |
| """加载CIFAR数据集的指定块""" |
| try: |
| if self.dataset_type == 'cifar10': |
| dataset = datasets.CIFAR10(self.dataset_path or './data', train=True, download=True) |
| else: |
| dataset = datasets.CIFAR100(self.dataset_path or './data', train=True, download=True) |
| |
| |
| class_indices = [i for i, (_, label) in enumerate(dataset) if label == class_idx] |
| |
| |
| start_idx = block_idx * self.samples_per_block |
| end_idx = min(start_idx + self.samples_per_block, len(class_indices)) |
| |
| if start_idx >= len(class_indices): |
| start_idx = max(0, len(class_indices) - self.samples_per_block) |
| end_idx = len(class_indices) |
| |
| selected_indices = class_indices[start_idx:end_idx] |
| |
| |
| images = [] |
| for idx in selected_indices: |
| img, _ = dataset[idx] |
| images.append(img) |
| |
| return images |
| |
| except Exception as e: |
| print(f"Error loading CIFAR block: {e}") |
| return [] |
| |
| def get_vgg_features(self, images, device='cuda', args=None): |
| """获取VGG特征 - 带缓存机制""" |
| if self.vgg_model is None: |
| self.vgg_model = vgg16(pretrained=True).features.to(device) |
| self.vgg_model.eval() |
| |
| self.normalize = transforms.Normalize( |
| mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) |
| |
| self.vgg_input_size = 224 |
| |
| if not images: |
| return torch.zeros(0, 512, device=device) |
| |
| |
| cache_dir = self._get_vgg_cache_dir(args) |
| if cache_dir: |
| return self._get_vgg_features_with_cache(images, device, args, cache_dir) |
| else: |
| return self._extract_vgg_features(images, device, args) |
| |
| def _get_vgg_cache_dir(self, args): |
| """获取VGG特征缓存目录""" |
| if not args or not hasattr(args, 'dataset_path'): |
| return None |
| |
| base_path = getattr(args, 'dataset_path', '') |
| if not base_path: |
| return None |
|
|
| cache_components = ['vgg'] |
|
|
| if hasattr(args, 'embedding_noise_level') and args.embedding_noise_level > 0: |
| cache_components.append(f"noise{args.embedding_noise_level}") |
|
|
| if hasattr(args, 'normalize_features') and args.normalize_features: |
| cache_components.append("norm") |
|
|
| cache_suffix = '_'.join(cache_components) |
| cache_dir = f"{base_path}_{cache_suffix}" |
| return cache_dir |
|
|
|
|
| |
| def _get_image_cache_path(self, image_path, cache_dir): |
| """获取单张图片的缓存路径""" |
| |
| import hashlib |
| path_hash = hashlib.md5(image_path.encode()).hexdigest() |
| return os.path.join(cache_dir, f"{path_hash}.pt") |
| |
| def _get_vgg_features_with_cache(self, images, device, args, cache_dir): |
| """带缓存的VGG特征提取""" |
| os.makedirs(cache_dir, exist_ok=True) |
| |
| |
| image_paths = [] |
| pil_images = [] |
| |
| for img in images: |
| if isinstance(img, str): |
| |
| image_paths.append(img) |
| try: |
| pil_img = Image.open(img).convert('RGB') |
| pil_images.append(pil_img) |
| except: |
| pil_images.append(None) |
| elif hasattr(img, 'filename'): |
| |
| image_paths.append(getattr(img, 'filename', '')) |
| pil_images.append(img) |
| else: |
| |
| image_paths.append('') |
| pil_images.append(img) |
| |
| |
| cached_features = [] |
| uncached_indices = [] |
| uncached_images = [] |
| |
| for i, (img_path, pil_img) in enumerate(zip(image_paths, pil_images)): |
| if img_path and os.path.exists(img_path): |
| cache_path = self._get_image_cache_path(img_path, cache_dir) |
| |
| if os.path.exists(cache_path): |
| try: |
| |
| cached_feature = torch.load(cache_path, map_location=device) |
| cached_features.append((i, cached_feature)) |
| continue |
| except: |
| pass |
| |
| |
| uncached_indices.append(i) |
| uncached_images.append(pil_img) |
| |
| |
| if uncached_images: |
| print(f"Computing VGG features for {len(uncached_images)} uncached images...") |
| new_features = self._extract_vgg_features(uncached_images, device, args) |
| |
| |
| for j, (original_idx, feature) in enumerate(zip(uncached_indices, new_features)): |
| img_path = image_paths[original_idx] |
| if img_path and os.path.exists(img_path): |
| cache_path = self._get_image_cache_path(img_path, cache_dir) |
| try: |
| torch.save(feature.cpu(), cache_path) |
| except Exception as e: |
| print(f"Failed to cache feature for {img_path}: {e}") |
| else: |
| new_features = torch.zeros(0, 512, device=device) |
| |
| |
| all_features = torch.zeros(len(images), 512, device=device) |
| |
| |
| for original_idx, cached_feature in cached_features: |
| all_features[original_idx] = cached_feature.to(device) |
| |
| |
| new_feature_idx = 0 |
| for original_idx in uncached_indices: |
| if new_feature_idx < len(new_features): |
| all_features[original_idx] = new_features[new_feature_idx] |
| new_feature_idx += 1 |
| |
| return all_features |
| |
| def _extract_vgg_features(self, images, device, args): |
| """实际的VGG特征提取逻辑""" |
| |
| transform = transforms.Compose([ |
| transforms.Resize((self.vgg_input_size, self.vgg_input_size)), |
| transforms.ToTensor() |
| ]) |
| |
| |
| img_tensors = [] |
| for img in images: |
| if img is None: |
| continue |
| |
| if isinstance(img, Image.Image): |
| |
| if img.mode != 'RGB': |
| img = img.convert('RGB') |
| img_tensor = transform(img) |
| else: |
| |
| if img.dim() == 3: |
| img_tensor = F.interpolate(img.unsqueeze(0), |
| size=(self.vgg_input_size, self.vgg_input_size), |
| mode='bilinear', align_corners=False).squeeze(0) |
| else: |
| img_tensor = img |
| |
| |
| if img_tensor.shape[0] == 1: |
| img_tensor = img_tensor.repeat(3, 1, 1) |
| elif img_tensor.shape[0] != 3: |
| img_tensor = img_tensor[:3] |
| |
| img_tensors.append(img_tensor) |
| |
| if not img_tensors: |
| return torch.zeros(0, 512, device=device) |
| |
| batch_tensor = torch.stack(img_tensors).to(device) |
| |
| with torch.no_grad(): |
| |
| normalized_batch = torch.stack([self.normalize(img) for img in batch_tensor]) |
| |
| |
| process_batch_size = 16 |
| features_list = [] |
| |
| for i in range(0, len(normalized_batch), process_batch_size): |
| batch = normalized_batch[i:i+process_batch_size] |
| |
| |
| batch_features = self.vgg_model(batch) |
| |
| |
| batch_features = F.adaptive_avg_pool2d(batch_features, (1, 1)) |
| batch_features = batch_features.view(batch_features.size(0), -1) |
| |
| features_list.append(batch_features) |
| |
| if features_list: |
| features = torch.cat(features_list, dim=0) |
| else: |
| features = torch.zeros(0, 512, device=device) |
| |
| |
| if args and hasattr(args, 'embedding_noise_level') and args.embedding_noise_level > 0: |
| noise = torch.randn_like(features) * args.embedding_noise_level |
| features = features + noise |
| |
| |
| if args and hasattr(args, 'normalize_features') and args.normalize_features: |
| features = F.normalize(features, p=2, dim=1) |
| |
| |
| if args and hasattr(args, 'feature_dropout') and args.feature_dropout > 0: |
| if hasattr(self.vgg_model, 'training') and self.vgg_model.training: |
| features = F.dropout(features, p=args.feature_dropout, training=True) |
| |
| return features |
|
|
| def load_images_for_class_block(self, class_idx, block_idx, args=None, is_test_mode=None): |
| """加载指定类别和块的图片 - 支持train/val切换""" |
| |
| |
| if is_test_mode is None: |
| |
| if args and hasattr(args, 'current_epoch'): |
| is_test_mode = args.current_epoch >= 99999 |
| else: |
| is_test_mode = False |
| |
| |
| if hasattr(self, 'train_class_info') and hasattr(self, 'val_class_info'): |
| |
| class_info = self.val_class_info if is_test_mode else self.train_class_info |
| else: |
| |
| class_info = self.class_info |
| |
| if class_idx not in class_info: |
| return [] |
| |
| class_data = class_info[class_idx] |
| |
| if self.dataset_type in ['cifar10', 'cifar100']: |
| return self._load_cifar_block(class_idx, block_idx, is_test_mode) |
| else: |
| |
| image_paths = class_data['image_paths'] |
| start_idx = block_idx * self.samples_per_block |
| end_idx = min(start_idx + self.samples_per_block, len(image_paths)) |
| |
| if start_idx >= len(image_paths): |
| |
| start_idx = max(0, len(image_paths) - self.samples_per_block) |
| end_idx = len(image_paths) |
| |
| block_paths = image_paths[start_idx:end_idx] |
| |
| |
| use_vgg = getattr(args, 'use_vgg_features', False) if args else False |
| cache_dir = self._get_vgg_cache_dir(args) if args else None |
| |
| if use_vgg and cache_dir: |
| |
| return block_paths |
| else: |
| |
| images = [] |
| for img_path in block_paths: |
| try: |
| img = Image.open(img_path).convert('RGB') |
| |
| |
| if args and hasattr(args, 'image_noise_level') and args.image_noise_level > 0: |
| aug_type = getattr(args, 'image_aug_type', 'pixel') |
| img_tensor = self.apply_image_augmentation(img, args.image_noise_level, aug_type) |
| |
| img = transforms.ToPILImage()(img_tensor) |
| |
| images.append(img) |
| except Exception as e: |
| print(f"Error loading {img_path}: {e}") |
| continue |
| |
| return images |
|
|
|
|
| def generate_batch_data(self, epoch, batch_size, device='cuda', args=None): |
| use_vgg_features = getattr(args, 'use_vgg_features', False) |
| downsample_size = getattr(args, 'downsample_size', 32) |
| scale_rbf = getattr(args, 'scale_rbf', 1.0) |
| k_nn = getattr(args, 'k_nn', 10) |
| class_combination_seed = getattr(args, 'class_combination_seed', 42) |
| n_samples_per_class = getattr(args, 'n_samples_per_class', 50) |
| |
| |
| is_test_mode = epoch >= 99999 |
| |
| |
| batch_mappings = self.get_epoch_mapping(epoch, batch_size, class_combination_seed, is_test_mode) |
| |
| data_source = "VALIDATION" if is_test_mode else "TRAINING" |
| print(f"Loading epoch {epoch} from {data_source} set...") |
| |
| all_raw_data = [] |
| all_labels = [] |
| all_laplacians = [] |
| all_adjacencies = [] |
| |
| for mapping in tqdm(batch_mappings, desc=f"Loading {data_source} epoch {epoch}"): |
| class1, class2 = mapping['class1'], mapping['class2'] |
| block1, block2 = mapping['block1'], mapping['block2'] |
| |
| |
| images1 = self.load_images_for_class_block(class1, block1, args, is_test_mode) |
| images2 = self.load_images_for_class_block(class2, block2, args, is_test_mode) |
| |
| |
| if len(images1) > n_samples_per_class: |
| images1 = images1[:n_samples_per_class] |
| if len(images2) > n_samples_per_class: |
| images2 = images2[:n_samples_per_class] |
| |
| |
| all_images = images1 + images2 |
| all_batch_labels = [0] * len(images1) + [1] * len(images2) |
| |
| if len(all_images) == 0: |
| |
| img_dim = 32 * 32 * 3 if not use_vgg_features else 512 |
| raw_data = torch.zeros(100, img_dim, device=device) |
| labels = torch.randint(0, 2, (100,), dtype=torch.long, device=device) |
| laplacian = torch.eye(100, device=device) |
| adjacency = torch.eye(100, device=device) * 1e-6 |
| else: |
| |
| if use_vgg_features: |
| |
| print(f"Extracting VGG features for batch (class {class1} & {class2})...") |
| raw_data = self.get_vgg_features(all_images, device, args) |
| else: |
| |
| processed_images = [] |
| for img in all_images: |
| if isinstance(img, str): |
| |
| img = Image.open(img).convert('RGB') |
| |
| if isinstance(img, Image.Image): |
| if downsample_size and downsample_size != img.size[0]: |
| img = img.resize((downsample_size, downsample_size), Image.LANCZOS) |
| img_tensor = transforms.ToTensor()(img) |
| else: |
| img_tensor = img |
| |
| if img_tensor.shape[0] == 3: |
| img_tensor = transforms.functional.rgb_to_grayscale(img_tensor) |
| |
| processed_images.append(img_tensor) |
| |
| if processed_images: |
| img_data_tensor = torch.stack(processed_images) |
| raw_data = img_data_tensor.view(img_data_tensor.shape[0], -1).to(device) |
| else: |
| raw_data = torch.zeros(0, 32*32, device=device) |
| |
| |
| current_size = raw_data.shape[0] |
| if current_size < 100: |
| padding_size = 100 - current_size |
| feature_dim = raw_data.shape[1] |
| padding_data = torch.zeros(padding_size, feature_dim, device=device) |
| raw_data = torch.cat([raw_data, padding_data], dim=0) |
| |
| padding_labels = torch.randint(0, 2, (padding_size,), dtype=torch.long, device=device) |
| all_batch_labels.extend(padding_labels.tolist()) |
| elif current_size > 100: |
| raw_data = raw_data[:100] |
| all_batch_labels = all_batch_labels[:100] |
| |
| labels = torch.tensor(all_batch_labels, dtype=torch.long, device=device) |
| |
| |
| distances = torch.cdist(raw_data, raw_data, p=2) |
| adjacency = torch.exp(-scale_rbf * distances ** 2) |
| |
| |
| adjacency_copy = adjacency.clone() |
| adjacency_copy.fill_diagonal_(0.0) |
| _, nn_indices = torch.topk(adjacency_copy, k_nn, dim=1) |
| |
| |
| adj_matrix = torch.zeros_like(adjacency, device=device) |
| batch_indices = torch.arange(100, device=device).unsqueeze(1).expand(-1, k_nn) |
| adj_matrix[batch_indices, nn_indices] = adjacency[batch_indices, nn_indices] |
| adj_matrix[nn_indices, batch_indices] = adjacency[nn_indices, batch_indices] |
| adj_matrix.fill_diagonal_(1e-6) |
| adjacency = adj_matrix |
| |
| |
| degree = adjacency.sum(dim=1) |
| degree = torch.clamp(degree, min=1e-10) |
| D_inv_sqrt = torch.diag(degree.pow(-0.5)).to(device) |
| laplacian = torch.eye(100, device=device) - D_inv_sqrt @ adjacency @ D_inv_sqrt |
| |
| all_raw_data.append(raw_data) |
| all_labels.append(labels) |
| all_laplacians.append(laplacian) |
| all_adjacencies.append(adjacency) |
| |
| |
| final_raw_data = torch.stack(all_raw_data, dim=0) |
| final_labels = torch.stack(all_labels, dim=0) |
| final_laplacians = torch.stack(all_laplacians, dim=0) |
| final_adjacencies = torch.stack(all_adjacencies, dim=0) |
| |
| return final_raw_data, final_laplacians, final_labels, final_adjacencies |
|
|
| |
| def clean_vgg_cache(dataset_path, noise_level=None): |
| """清理VGG特征缓存""" |
| cache_components = ['vgg'] |
| if noise_level is not None: |
| cache_components.append(f"noise{noise_level}") |
| |
| cache_dir = f"{dataset_path}_{'_'.join(cache_components)}" |
| |
| if os.path.exists(cache_dir): |
| import shutil |
| shutil.rmtree(cache_dir) |
| print(f"Cleaned VGG cache: {cache_dir}") |
| else: |
| print(f"Cache directory does not exist: {cache_dir}") |
|
|
| def get_vgg_cache_info(dataset_path, noise_level=None): |
| """获取VGG缓存信息""" |
| cache_components = ['vgg'] |
| if noise_level is not None: |
| cache_components.append(f"noise{noise_level}") |
| |
| cache_dir = f"{dataset_path}_{'_'.join(cache_components)}" |
| |
| if not os.path.exists(cache_dir): |
| return {"exists": False, "path": cache_dir} |
| |
| |
| cache_files = [f for f in os.listdir(cache_dir) if f.endswith('.pt')] |
| total_size = sum(os.path.getsize(os.path.join(cache_dir, f)) for f in cache_files) |
| |
| return { |
| "exists": True, |
| "path": cache_dir, |
| "num_files": len(cache_files), |
| "total_size_mb": total_size / (1024 * 1024), |
| "files": cache_files[:10] |
| } |
| |
| def save_feature_statistics(epoch, features, labels, save_dir="./feature_stats"): |
| """保存特征统计信息""" |
| os.makedirs(save_dir, exist_ok=True) |
| |
| stats = { |
| 'epoch': epoch, |
| 'feature_mean': features.mean(dim=0).cpu().numpy(), |
| 'feature_std': features.std(dim=0).cpu().numpy(), |
| 'feature_min': features.min(dim=0)[0].cpu().numpy(), |
| 'feature_max': features.max(dim=0)[0].cpu().numpy(), |
| 'label_distribution': torch.bincount(labels.flatten()).cpu().numpy(), |
| 'feature_norm': torch.norm(features, dim=-1).cpu().numpy() |
| } |
| |
| save_path = os.path.join(save_dir, f"feature_stats_epoch_{epoch}.json") |
| with open(save_path, 'w') as f: |
| |
| json_stats = {} |
| for key, value in stats.items(): |
| if isinstance(value, np.ndarray): |
| json_stats[key] = value.tolist() |
| else: |
| json_stats[key] = value |
| json.dump(json_stats, f, indent=2) |
| |
| print(f"Feature statistics saved to {save_path}") |
|
|
| def analyze_dataset_structure(dataset_type='imagenet100', dataset_path=None, args=None): |
| """分析数据集结构""" |
| loader = SimpleImageDataLoader(dataset_type, dataset_path, 50) |
| stats = loader.get_dataset_stats() |
| |
| print(f"\n=== Dataset Analysis: {dataset_type} ===") |
| print(f"Dataset path: {dataset_path}") |
| print(f"Total classes: {stats['num_classes']}") |
| print(f"Total class combinations: {stats['total_combinations']}") |
| print(f"Max blocks per class: {stats['max_blocks_per_class']}") |
| print(f"Total possible batches: {stats['total_possible_batches']:,}") |
| |
| print(f"\nImages per class:") |
| img_stats = stats['images_per_class'] |
| print(f" Min: {img_stats['min']}, Max: {img_stats['max']}, Avg: {img_stats['avg']:.1f}") |
| |
| print(f"\nBlocks per class:") |
| block_stats = stats['blocks_per_class'] |
| print(f" Min: {block_stats['min']}, Max: {block_stats['max']}, Avg: {block_stats['avg']:.1f}") |
| |
| print(f"\nTraining estimates for different batch sizes:") |
| for bs in [50, 100, 200, 500]: |
| epochs_needed = (stats['total_possible_batches'] + bs - 1) // bs |
| print(f" Batch size {bs:3d}: {epochs_needed:,} epochs to cover all combinations") |
| |
| return stats |
|
|
| def test_epoch_mappings(dataset_type='imagenet100', dataset_path=None, args=None): |
| """测试epoch映射功能""" |
| loader = SimpleImageDataLoader(dataset_type, dataset_path, 50) |
| |
| print(f"\n=== Testing Epoch Mappings ===") |
| |
| |
| for epoch in range(3): |
| print(f"\n--- Epoch {epoch} ---") |
| class_combination_seed = getattr(args, 'class_combination_seed', 42) if args else 42 |
| mappings = loader.get_epoch_mapping(epoch, 5, class_combination_seed) |
| |
| print(f"{'Batch':>5} {'Global':>8} {'Class1':>6} {'Block1':>6} {'Class2':>6} {'Block2':>6} {'Round':>5}") |
| print("-" * 50) |
| |
| for mapping in mappings: |
| print(f"{mapping['batch_idx']:>5} {mapping['global_batch_id']:>8} " |
| f"{mapping['class1']:>6} {mapping['block1']:>6} " |
| f"{mapping['class2']:>6} {mapping['block2']:>6} " |
| f"{mapping['block_round']:>5}") |
|
|
| def test_vgg_cache(dataset_path, args=None): |
| """测试VGG缓存功能""" |
| print(f"\n=== Testing VGG Cache ===") |
| |
| |
| if args is None: |
| class TestArgs: |
| def __init__(self): |
| self.dataset_type = 'imagenet100' |
| self.use_vgg_features = True |
| self.dataset_path = dataset_path |
| self.embedding_noise_level = 0.0 |
| self.normalize_features = False |
| args = TestArgs() |
| |
| |
| loader = SimpleImageDataLoader('imagenet100', dataset_path, 50) |
| |
| |
| if len(loader.class_info) > 0: |
| class_idx = 0 |
| block_idx = 0 |
| |
| print(f"Testing cache with class {class_idx}, block {block_idx}") |
| |
| |
| start_time = time.time() |
| images = loader.load_images_for_class_block(class_idx, block_idx, args)[:10] |
| features1 = loader.get_vgg_features(images, 'cuda', args) |
| time1 = time.time() - start_time |
| |
| print(f"First extraction: {time1:.2f}s, features shape: {features1.shape}") |
| |
| |
| start_time = time.time() |
| features2 = loader.get_vgg_features(images, 'cuda', args) |
| time2 = time.time() - start_time |
| |
| print(f"Second extraction: {time2:.2f}s, features shape: {features2.shape}") |
| print(f"Speedup: {time1/time2:.1f}x") |
| print(f"Features identical: {torch.allclose(features1, features2)}") |
| |
| |
| cache_info = get_vgg_cache_info(dataset_path) |
| print(f"Cache info: {cache_info}") |
|
|
| |
| def get_or_generate_data_image_integrated(*args, **kwargs): |
| """向后兼容的别名""" |
| return get_or_generate_data_image(*args, **kwargs) |
|
|
| def get_or_generate_data_image_simple(*args, **kwargs): |
| """向后兼容的别名""" |
| return get_or_generate_data_image(*args, **kwargs) |
|
|
| |
| if __name__ == "__main__": |
| print("=== Simple Image Data Loader with VGG Cache ===") |
| print("Features:") |
| print(" - Support for ImageNet100, ImageNet10, CIFAR10/100, and folder datasets") |
| print(" - Systematic epoch->class combination mapping") |
| print(" - Block-wise image loading (50 images per block)") |
| print(" - VGG feature extraction with intelligent caching") |
| print(" - Complete argument compatibility") |
| print(" - Efficient caching and parallel processing") |
| print() |
| |
| |
| class Args: |
| def __init__(self): |
| self.dataset_type = 'imagenet100' |
| self.use_vgg_features = True |
| self.dataset_path = '/work/jf381/data/icl_jay/imagenet100' |
| self.image_noise_level = 0.0 |
| self.image_aug_type = 'pixel' |
| self.embedding_noise_level = 0.0 |
| self.class_combination_seed = 42 |
| self.test_class_combination_seed = 12345 |
| self.n_samples_per_class = 50 |
| self.vgg_feature_dim = 512 |
| self.normalize_features = False |
| self.feature_dropout = 0.0 |
| self.visualize_samples = False |
| self.save_feature_stats = False |
| |
| |
| args = Args() |
| |
| print("VGG Cache Examples:") |
| print(f" Cache dir (no noise): {args.dataset_path}_vgg") |
| print(f" Cache dir (noise=0.1): {args.dataset_path}_vgg_noise0.1") |
| print(f" Cache dir (noise+norm): {args.dataset_path}_vgg_noise0.1_norm") |
| print() |
| |
| |
| print("Testing cache functionality...") |
| try: |
| test_vgg_cache('/work/jf381/data/icl_jay/imagenet100', args) |
| except Exception as e: |
| print(f"Cache test failed: {e}") |
| |
| print("\nCache management functions:") |
| print(" - get_vgg_cache_info(dataset_path, noise_level)") |
| print(" - clean_vgg_cache(dataset_path, noise_level)") |
| print(" - test_vgg_cache(dataset_path, args)") |
| |
| print("\nSimple Image Data Loader with VGG cache ready for use!") |
| print("Use get_or_generate_data_image() as your main interface.") |
|
|
| def generate_batch_data(self, epoch, batch_size, device='cuda', args=None): |
| """生成一个epoch的batch数据""" |
| |
| |
| use_vgg_features = getattr(args, 'use_vgg_features', False) |
| downsample_size = getattr(args, 'downsample_size', 32) |
| scale_rbf = getattr(args, 'scale_rbf', 1.0) |
| k_nn = getattr(args, 'k_nn', 10) |
| class_combination_seed = getattr(args, 'class_combination_seed', 42) |
| n_samples_per_class = getattr(args, 'n_samples_per_class', 50) |
| |
| |
| batch_mappings = self.get_epoch_mapping(epoch, batch_size, class_combination_seed) |
| |
| all_raw_data = [] |
| all_labels = [] |
| all_laplacians = [] |
| all_adjacencies = [] |
| |
| for mapping in tqdm(batch_mappings, desc=f"Loading epoch {epoch}"): |
| class1, class2 = mapping['class1'], mapping['class2'] |
| block1, block2 = mapping['block1'], mapping['block2'] |
| |
| |
| images1 = self.load_images_for_class_block(class1, block1, args) |
| images2 = self.load_images_for_class_block(class2, block2, args) |
| |
| |
| if len(images1) > n_samples_per_class: |
| images1 = images1[:n_samples_per_class] |
| if len(images2) > n_samples_per_class: |
| images2 = images2[:n_samples_per_class] |
| |
| |
| all_images = images1 + images2 |
| all_batch_labels = [0] * len(images1) + [1] * len(images2) |
| |
| if len(all_images) == 0: |
| |
| img_dim = 32 * 32 * 3 if not use_vgg_features else getattr(args, 'vgg_feature_dim', 512) |
| raw_data = torch.zeros(100, img_dim, device=device) |
| labels = torch.randint(0, 2, (100,), dtype=torch.long, device=device) |
| laplacian = torch.eye(100, device=device) |
| adjacency = torch.eye(100, device=device) * 1e-6 |
| else: |
| |
| processed_images = [] |
| for img in all_images: |
| if isinstance(img, Image.Image): |
| if downsample_size and downsample_size != img.size[0]: |
| img = img.resize((downsample_size, downsample_size), Image.LANCZOS) |
| img_tensor = transforms.ToTensor()(img) |
| else: |
| img_tensor = img |
| |
| if not use_vgg_features and img_tensor.shape[0] == 3: |
| img_tensor = transforms.functional.rgb_to_grayscale(img_tensor) |
| |
| processed_images.append(img_tensor) |
| |
| |
| if use_vgg_features: |
| |
| raw_data = self.get_vgg_features(all_images, device, args) |
| else: |
| img_data_tensor = torch.stack(processed_images) |
| raw_data = img_data_tensor.view(img_data_tensor.shape[0], -1).to(device) |
| |
| |
| current_size = raw_data.shape[0] |
| if current_size < 100: |
| padding_size = 100 - current_size |
| feature_dim = raw_data.shape[1] |
| padding_data = torch.zeros(padding_size, feature_dim, device=device) |
| raw_data = torch.cat([raw_data, padding_data], dim=0) |
| |
| padding_labels = torch.randint(0, 2, (padding_size,), dtype=torch.long, device=device) |
| all_batch_labels.extend(padding_labels.tolist()) |
| elif current_size > 100: |
| raw_data = raw_data[:100] |
| all_batch_labels = all_batch_labels[:100] |
| |
| labels = torch.tensor(all_batch_labels, dtype=torch.long, device=device) |
| |
| |
| distances = torch.cdist(raw_data, raw_data, p=2) |
| adjacency = torch.exp(-scale_rbf * distances ** 2) |
| |
| |
| adjacency_copy = adjacency.clone() |
| adjacency_copy.fill_diagonal_(0.0) |
| _, nn_indices = torch.topk(adjacency_copy, k_nn, dim=1) |
| |
| |
| adj_matrix = torch.zeros_like(adjacency, device=device) |
| batch_indices = torch.arange(100, device=device).unsqueeze(1).expand(-1, k_nn) |
| adj_matrix[batch_indices, nn_indices] = adjacency[batch_indices, nn_indices] |
| adj_matrix[nn_indices, batch_indices] = adjacency[nn_indices, batch_indices] |
| adj_matrix.fill_diagonal_(1e-6) |
| adjacency = adj_matrix |
| |
| |
| degree = adjacency.sum(dim=1) |
| degree = torch.clamp(degree, min=1e-10) |
| D_inv_sqrt = torch.diag(degree.pow(-0.5)).to(device) |
| laplacian = torch.eye(100, device=device) - D_inv_sqrt @ adjacency @ D_inv_sqrt |
| |
| all_raw_data.append(raw_data) |
| all_labels.append(labels) |
| all_laplacians.append(laplacian) |
| all_adjacencies.append(adjacency) |
| |
| |
| final_raw_data = torch.stack(all_raw_data, dim=0) |
| final_labels = torch.stack(all_labels, dim=0) |
| final_laplacians = torch.stack(all_laplacians, dim=0) |
| final_adjacencies = torch.stack(all_adjacencies, dim=0) |
| |
| return final_raw_data, final_laplacians, final_labels, final_adjacencies |
|
|
| |
| def get_or_generate_data_image( |
| epoch, |
| batch_size, |
| n_samples, |
| scale_rbf, |
| k_nn, |
| device, |
| label_percent, |
| context_size, |
| k_feat, |
| data_dir="./cached_data", |
| image_dir="./data", |
| force=False, |
| downsample_size=32, |
| scale_factor=1.0, |
| pixel_scale_factor=None, |
| manifold_list=None, |
| prod_threshold=None, |
| args=None |
| ): |
| """ |
| 主数据生成函数 - 保持原有接口兼容性 |
| """ |
| os.makedirs(data_dir, exist_ok=True) |
| |
| |
| dataset_type = getattr(args, 'dataset_type', 'imagenet100') |
| use_vgg_features = getattr(args, 'use_vgg_features', False) |
| class_combination_seed = getattr(args, 'class_combination_seed', 42) |
| test_class_combination_seed = getattr(args, 'test_class_combination_seed', 12345) |
| |
| |
| is_test = epoch >= 99999 |
| seed_to_use = test_class_combination_seed if is_test else class_combination_seed |
| |
| |
| cache_components = [ |
| f"epoch_{epoch}", |
| f"mode_{'test' if is_test else 'train'}", |
| f"bs{batch_size}", |
| f"seed{seed_to_use}", |
| f"dataset{dataset_type}", |
| "vgg" if use_vgg_features else "pixel", |
| f"ds{downsample_size}" if downsample_size else "nods", |
| f"scale{scale_factor}" if scale_factor != 1.0 else "noscale", |
| f"scale_rbf{scale_rbf}" |
| ] |
| |
| |
| if hasattr(args, 'image_noise_level') and args.image_noise_level > 0: |
| cache_components.append(f"imgnoise{args.image_noise_level}_{getattr(args, 'image_aug_type', 'pixel')}") |
| |
| if hasattr(args, 'embedding_noise_level') and args.embedding_noise_level > 0: |
| cache_components.append(f"embnoise{args.embedding_noise_level}") |
| |
| cache_file = os.path.join(data_dir, f"data_{'_'.join(cache_components)}.pt") |
| print(cache_file) |
| |
| if not force and os.path.exists(cache_file): |
| try: |
| print(f"Loading cached data from {cache_file}") |
| cached_data = torch.load(cache_file, map_location=device) |
| |
| raw_data = cached_data['raw_data'].to(device) |
| real_lap = cached_data['real_lap'].to(device) |
| labels_tensor = cached_data['labels_tensor'].to(device) |
| real_adj = cached_data['real_adj'].to(device) |
| real_ev = cached_data['real_ev'].to(device) |
| |
| |
| n_labeled = int(100 * label_percent / 100) |
| labeled_indices = torch.stack([torch.randperm(100, device=device)[:n_labeled] for _ in range(batch_size)]) |
| context_indices = torch.stack([torch.randperm(n_labeled, device=device)[:context_size] for _ in range(batch_size)]) |
| |
| all_indices = torch.arange(n_labeled, device=device).expand(batch_size, n_labeled) |
| mask = torch.zeros(batch_size, n_labeled, dtype=torch.bool, device=device) |
| for i in range(batch_size): |
| mask[i].scatter_(0, context_indices[i], True) |
| query_indices = all_indices[~mask].view(batch_size, n_labeled - context_size) |
| |
| return raw_data, real_lap, labels_tensor, real_adj, labeled_indices, context_indices, query_indices, real_ev |
| |
| except Exception as e: |
| print(f"Failed to load cached data: {e}") |
| |
| |
| |
| if args: |
| args_copy = type(args)() |
| for attr in dir(args): |
| if not attr.startswith('_'): |
| setattr(args_copy, attr, getattr(args, attr)) |
| args_copy.class_combination_seed = seed_to_use |
| args = args_copy |
| |
| loader = SimpleImageDataLoader( |
| dataset_type=dataset_type, |
| dataset_path=image_dir, |
| samples_per_block=getattr(args, 'n_samples_per_class', 50) if args else 50 |
| ) |
| |
| |
| start_time = time.time() |
| print(f"Generating data for epoch {epoch}...") |
| |
| raw_data, real_lap, labels_tensor, real_adj = loader.generate_batch_data( |
| epoch=epoch, |
| batch_size=batch_size, |
| device=device, |
| args=args |
| ) |
| |
| |
| real_eigs = [] |
| for b in range(batch_size): |
| try: |
| _, vecs = torch.linalg.eigh(real_lap[b]) |
| real_eigs.append(vecs[:, :k_feat]) |
| except Exception: |
| real_eigs.append(torch.eye(100, k_feat, device=device)) |
| |
| real_ev = torch.stack(real_eigs, dim=0) |
| |
| |
| n_labeled = int(100 * label_percent / 100) |
| labeled_indices = torch.stack([torch.randperm(100, device=device)[:n_labeled] for _ in range(batch_size)]) |
| context_indices = torch.stack([torch.randperm(n_labeled, device=device)[:context_size] for _ in range(batch_size)]) |
| |
| all_indices = torch.arange(n_labeled, device=device).expand(batch_size, n_labeled) |
| mask = torch.zeros(batch_size, n_labeled, dtype=torch.bool, device=device) |
| for i in range(batch_size): |
| mask[i].scatter_(0, context_indices[i], True) |
| query_indices = all_indices[~mask].view(batch_size, n_labeled - context_size) |
| |
| generation_time = time.time() - start_time |
| print(f"Data generation completed in {generation_time:.2f} seconds") |
| |
| |
| if args and hasattr(args, 'save_feature_stats') and args.save_feature_stats: |
| save_feature_statistics(epoch, raw_data, labels_tensor) |
| |
| |
| cached_data = { |
| 'raw_data': raw_data.cpu(), |
| 'real_lap': real_lap.cpu(), |
| 'labels_tensor': labels_tensor.cpu(), |
| 'real_adj': real_adj.cpu(), |
| 'real_ev': real_ev.cpu(), |
| 'generation_time': generation_time, |
| 'dataset_type': dataset_type, |
| 'epoch': epoch, |
| 'seed_used': seed_to_use |
| } |
| |
| try: |
| torch.save(cached_data, cache_file) |
| print(f"Data cached to {cache_file}") |
| except Exception as e: |
| print(f"Failed to cache data: {e}") |
| |
| return raw_data, real_lap, labels_tensor, real_adj, labeled_indices, context_indices, query_indices, real_ev |
|
|
| |
| def save_feature_statistics(epoch, features, labels, save_dir="./feature_stats"): |
| """保存特征统计信息""" |
| os.makedirs(save_dir, exist_ok=True) |
| |
| stats = { |
| 'epoch': epoch, |
| 'feature_mean': features.mean(dim=0).cpu().numpy(), |
| 'feature_std': features.std(dim=0).cpu().numpy(), |
| 'feature_min': features.min(dim=0)[0].cpu().numpy(), |
| 'feature_max': features.max(dim=0)[0].cpu().numpy(), |
| 'label_distribution': torch.bincount(labels.flatten()).cpu().numpy(), |
| 'feature_norm': torch.norm(features, dim=-1).cpu().numpy() |
| } |
| |
| save_path = os.path.join(save_dir, f"feature_stats_epoch_{epoch}.json") |
| with open(save_path, 'w') as f: |
| |
| json_stats = {} |
| for key, value in stats.items(): |
| if isinstance(value, np.ndarray): |
| json_stats[key] = value.tolist() |
| else: |
| json_stats[key] = value |
| json.dump(json_stats, f, indent=2) |
| |
| print(f"Feature statistics saved to {save_path}") |
|
|
| def analyze_dataset_structure(dataset_type='imagenet100', dataset_path=None, args=None): |
| """分析数据集结构""" |
| loader = SimpleImageDataLoader(dataset_type, dataset_path, 50) |
| stats = loader.get_dataset_stats() |
| |
| print(f"\n=== Dataset Analysis: {dataset_type} ===") |
| print(f"Dataset path: {dataset_path}") |
| print(f"Total classes: {stats['num_classes']}") |
| print(f"Total class combinations: {stats['total_combinations']}") |
| print(f"Max blocks per class: {stats['max_blocks_per_class']}") |
| print(f"Total possible batches: {stats['total_possible_batches']:,}") |
| |
| print(f"\nImages per class:") |
| img_stats = stats['images_per_class'] |
| print(f" Min: {img_stats['min']}, Max: {img_stats['max']}, Avg: {img_stats['avg']:.1f}") |
| |
| print(f"\nBlocks per class:") |
| block_stats = stats['blocks_per_class'] |
| print(f" Min: {block_stats['min']}, Max: {block_stats['max']}, Avg: {block_stats['avg']:.1f}") |
| |
| print(f"\nTraining estimates for different batch sizes:") |
| for bs in [50, 100, 200, 500]: |
| epochs_needed = (stats['total_possible_batches'] + bs - 1) // bs |
| print(f" Batch size {bs:3d}: {epochs_needed:,} epochs to cover all combinations") |
| |
| return stats |
|
|
| def test_epoch_mappings(dataset_type='imagenet100', dataset_path=None, args=None): |
| """测试epoch映射功能""" |
| loader = SimpleImageDataLoader(dataset_type, dataset_path, 50) |
| |
| print(f"\n=== Testing Epoch Mappings ===") |
| |
| |
| for epoch in range(3): |
| print(f"\n--- Epoch {epoch} ---") |
| class_combination_seed = getattr(args, 'class_combination_seed', 42) if args else 42 |
| mappings = loader.get_epoch_mapping(epoch, 5, class_combination_seed) |
| |
| print(f"{'Batch':>5} {'Global':>8} {'Class1':>6} {'Block1':>6} {'Class2':>6} {'Block2':>6} {'Round':>5}") |
| print("-" * 50) |
| |
| for mapping in mappings: |
| print(f"{mapping['batch_idx']:>5} {mapping['global_batch_id']:>8} " |
| f"{mapping['class1']:>6} {mapping['block1']:>6} " |
| f"{mapping['class2']:>6} {mapping['block2']:>6} " |
| f"{mapping['block_round']:>5}") |
|
|
| |
| def get_or_generate_data_image_integrated(*args, **kwargs): |
| """向后兼容的别名""" |
| return get_or_generate_data_image(*args, **kwargs) |
|
|
| def get_or_generate_data_image_simple(*args, **kwargs): |
| """向后兼容的别名""" |
| return get_or_generate_data_image(*args, **kwargs) |
|
|
| |
| if __name__ == "__main__": |
| print("=== Simple Image Data Loader ===") |
| print("Features:") |
| print(" - Support for ImageNet100, ImageNet10, CIFAR10/100, and folder datasets") |
| print(" - Systematic epoch->class combination mapping") |
| print(" - Block-wise image loading (50 images per block)") |
| print(" - VGG feature extraction with all augmentation options") |
| print(" - Complete argument compatibility") |
| print(" - Efficient caching and parallel processing") |
| print() |
| |
| |
| class Args: |
| def __init__(self): |
| self.dataset_type = 'imagenet100' |
| self.use_vgg_features = False |
| self.image_noise_level = 0.0 |
| self.image_aug_type = 'pixel' |
| self.embedding_noise_level = 0.0 |
| self.class_combination_seed = 42 |
| self.test_class_combination_seed = 12345 |
| self.n_samples_per_class = 50 |
| self.vgg_feature_dim = 512 |
| self.normalize_features = False |
| self.feature_dropout = 0.0 |
| self.visualize_samples = False |
| self.save_feature_stats = False |
| |
| |
| args = Args() |
| |
| |
| print("Testing dataset analysis...") |
| try: |
| analyze_dataset_structure('imagenet100', '/work/jf381/data/icl_jay/imagenet100', args) |
| except Exception as e: |
| print(f"Dataset analysis failed: {e}") |
| |
| |
| print("\nTesting epoch mappings...") |
| try: |
| test_epoch_mappings('imagenet100', '/work/jf381/data/icl_jay/imagenet100', args) |
| except Exception as e: |
| print(f"Epoch mapping test failed: {e}") |
| |
| print("\nSimple Image Data Loader ready for use!") |
| print("Use get_or_generate_data_image() as your main interface.") |