| |
| |
|
|
| 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 |
| from functools import lru_cache |
| import time |
|
|
| |
| _dataset_cache = {} |
| _combinations_cache = {} |
| _cache_lock = threading.Lock() |
|
|
| def get_vgg_features(images, device='cuda'): |
| """优化的VGG特征提取""" |
| if not hasattr(get_vgg_features, 'vgg_model'): |
| get_vgg_features.vgg_model = vgg16(pretrained=True).features.to(device) |
| get_vgg_features.vgg_model.eval() |
| get_vgg_features.normalize = transforms.Normalize( |
| mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) |
| |
| vgg = get_vgg_features.vgg_model |
| normalize = get_vgg_features.normalize |
| |
| with torch.no_grad(): |
| if images.dim() == 3: |
| images = images.unsqueeze(1).repeat(1, 3, 1, 1) |
| elif images.shape[1] == 1: |
| images = images.repeat(1, 3, 1, 1) |
| |
| normalized_images = torch.stack([normalize(img) for img in images]) |
| |
| |
| batch_size = 32 |
| features_list = [] |
| for i in range(0, len(normalized_images), batch_size): |
| batch = normalized_images[i:i+batch_size] |
| batch_features = vgg(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) |
| |
| features = torch.cat(features_list, dim=0) |
| return features |
|
|
| def scan_class_parallel(args): |
| """并行扫描类别文件夹""" |
| class_folder, train_folders, dataset_path = args |
| total_images = 0 |
| all_paths = [] |
| |
| try: |
| for train_folder in train_folders: |
| class_path = os.path.join(train_folder, class_folder) |
| 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] |
| all_paths.extend(paths) |
| total_images += len(files) |
| return class_folder, total_images, all_paths |
| except Exception as e: |
| print(f"Error scanning {class_folder}: {e}") |
| return class_folder, 0, [] |
|
|
| @lru_cache(maxsize=32) |
| def detect_dataset_structure(dataset_type, dataset_path): |
| """缓存的数据集结构探测""" |
| cache_key = f"{dataset_type}_{dataset_path}" |
| |
| with _cache_lock: |
| if cache_key in _dataset_cache: |
| print(f"Using cached structure for {dataset_type}") |
| return _dataset_cache[cache_key] |
| |
| print(f"🚀 Detecting {dataset_type} structure: {dataset_path}") |
| structure = {'num_classes': 0, 'images_per_class': {}, 'samples_per_class': 50, |
| 'sampling_ways_per_class': {}, 'image_paths': {}} |
| |
| |
| if dataset_path: |
| path_lower = dataset_path.lower() |
| if 'cifar10' in path_lower: |
| dataset_type = 'cifar10' |
| elif 'cifar100' in path_lower: |
| dataset_type = 'cifar100' |
| elif 'imagenet-10' in path_lower: |
| dataset_type = 'imagenet10' |
| elif 'imagenet100' in path_lower: |
| dataset_type = 'imagenet100' |
| |
| if dataset_type == 'imagenet100': |
| if dataset_path and os.path.exists(dataset_path): |
| |
| train_folders = [os.path.join(dataset_path, item) |
| for item in os.listdir(dataset_path) |
| if item.startswith('train.X') and os.path.isdir(os.path.join(dataset_path, item))] |
| |
| if train_folders: |
| train_folders.sort() |
| print(f" Found {len(train_folders)} train folders") |
| |
| |
| first_train = train_folders[0] |
| class_folders = [f for f in os.listdir(first_train) |
| if os.path.isdir(os.path.join(first_train, f)) and f.startswith('n')] |
| class_folders.sort() |
| |
| |
| scan_args = [(cf, train_folders, dataset_path) for cf in class_folders] |
| max_workers = min(mp.cpu_count(), 16) |
| |
| with ThreadPoolExecutor(max_workers=max_workers) as executor: |
| futures = [executor.submit(scan_class_parallel, args) for args in scan_args] |
| results = [f.result() for f in tqdm(as_completed(futures), |
| total=len(futures), desc="Scanning")] |
| |
| structure['num_classes'] = len(class_folders) |
| for i, (class_folder, total_images, image_paths) in enumerate(results): |
| if class_folder in class_folders: |
| class_idx = class_folders.index(class_folder) |
| structure['images_per_class'][class_idx] = total_images |
| structure['sampling_ways_per_class'][class_idx] = max(1, total_images // 50) |
| structure['image_paths'][class_idx] = image_paths |
| |
| structure['class_folders'] = class_folders |
| structure['train_folders'] = train_folders |
| else: |
| |
| structure['num_classes'] = 100 |
| for i in range(100): |
| structure['images_per_class'][i] = 1300 |
| structure['sampling_ways_per_class'][i] = 26 |
| |
| elif dataset_type == 'imagenet10': |
| if dataset_path and os.path.exists(dataset_path): |
| class_folders = [f for f in os.listdir(dataset_path) |
| if os.path.isdir(os.path.join(dataset_path, f)) and f.startswith('n')] |
| if not class_folders: |
| train_path = os.path.join(dataset_path, 'train') |
| if os.path.exists(train_path): |
| class_folders = [f for f in os.listdir(train_path) |
| if os.path.isdir(os.path.join(train_path, f))] |
| dataset_path = train_path |
| |
| class_folders.sort() |
| structure['num_classes'] = len(class_folders) |
| |
| |
| def scan_imagenet10(cf): |
| class_path = os.path.join(dataset_path, cf) |
| files = [f for f in os.listdir(class_path) |
| if f.lower().endswith(('.jpg', '.jpeg', '.png'))] |
| paths = [os.path.join(class_path, f) for f in sorted(files)] |
| return cf, len(files), paths |
| |
| with ThreadPoolExecutor(max_workers=min(mp.cpu_count(), len(class_folders))) as executor: |
| futures = [executor.submit(scan_imagenet10, cf) for cf in class_folders] |
| results = [f.result() for f in as_completed(futures)] |
| |
| for i, (class_folder, num_images, image_paths) in enumerate(results): |
| if class_folder in class_folders: |
| class_idx = class_folders.index(class_folder) |
| structure['images_per_class'][class_idx] = num_images |
| structure['sampling_ways_per_class'][class_idx] = max(1, num_images // 50) |
| structure['image_paths'][class_idx] = image_paths |
| |
| structure['class_folders'] = class_folders |
| |
| elif dataset_type == 'cifar10': |
| structure['num_classes'] = 10 |
| for i in range(10): |
| structure['images_per_class'][i] = 5000 |
| structure['sampling_ways_per_class'][i] = 100 |
| |
| elif dataset_type == 'cifar100': |
| structure['num_classes'] = 100 |
| for i in range(100): |
| structure['images_per_class'][i] = 500 |
| structure['sampling_ways_per_class'][i] = 10 |
| |
| |
| total_batches = 0 |
| num_classes = structure['num_classes'] |
| for c1 in range(num_classes): |
| ways_c1 = structure['sampling_ways_per_class'][c1] |
| for c2 in range(num_classes): |
| if c2 != c1: |
| ways_c2 = structure['sampling_ways_per_class'][c2] |
| total_batches += ways_c1 * ways_c2 |
| |
| structure['total_batches'] = total_batches |
| |
| print(f" Classes: {num_classes}, Total batches: {total_batches:,}") |
| |
| with _cache_lock: |
| _dataset_cache[cache_key] = structure |
| |
| return structure |
|
|
| def generate_prioritized_combinations(dataset_structure): |
| """ |
| 生成优先遍历类别的组合 |
| 逻辑:先遍历所有类别组合(前50张),再遍历接下来的50张,依次类推 |
| """ |
| print("🚀 Generating prioritized combinations...") |
| |
| num_classes = dataset_structure['num_classes'] |
| samples_per_class = dataset_structure['samples_per_class'] |
| |
| |
| max_ways = max(dataset_structure['sampling_ways_per_class'].values()) |
| |
| all_combinations = [] |
| |
| |
| for way_idx in range(max_ways): |
| print(f" Processing sampling way {way_idx + 1}/{max_ways}") |
| |
| |
| for c1 in range(num_classes): |
| ways_c1 = dataset_structure['sampling_ways_per_class'][c1] |
| |
| |
| if way_idx < ways_c1: |
| c1_start = way_idx * samples_per_class |
| |
| for c2 in range(num_classes): |
| if c2 != c1: |
| ways_c2 = dataset_structure['sampling_ways_per_class'][c2] |
| |
| |
| if way_idx < ways_c2: |
| c2_start = way_idx * samples_per_class |
| all_combinations.append((c1, c1_start, c2, c2_start, way_idx)) |
| |
| print(f"Generated {len(all_combinations):,} prioritized combinations") |
| return all_combinations |
|
|
| |