File size: 10,714 Bytes
64bce2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# image_data_corrected.py - Block 1/3
# 修正版:每个batch对应唯一类别组合,优先遍历类别

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文件夹
            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)
            
            # 并行扫描ImageNet10类别
            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
    
    # 计算总batch数(修正逻辑)
    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]
            
            # 检查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]
                        
                        # 检查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