carin-jf381-data / ICL_code /ICL_Jay /data copy /image_data_scale.py
jasonfan's picture
2026-03-19: ICL code
64bce2a verified
Raw
History Blame Contribute Delete
60 kB
# simple_image_data.py - Block 1/3 - 基础类和数据集扫描
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
# 🔑 关键修改:分别存储train和val数据
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文件夹和val文件夹
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))
# 🔑 关键修改:分别处理train和val数据
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:
# ImageNet类型数据集
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
brightness_factor = 1 + (random.random() - 0.5) * noise_level
image = torch.clamp(image * brightness_factor, 0, 1)
elif rand_val < 0.66: # Contrast
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: # Saturation
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:
# ImageNet类型数据集或folder
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)
# 转回PIL Image
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()
# ImageNet标准归一化参数
self.normalize = transforms.Normalize(
mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
# VGG标准输入尺寸
self.vgg_input_size = 224
if not images:
return torch.zeros(0, 512, device=device) # VGG16 features = 512维
# 检查是否有缓存目录配置
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):
"""获取单张图片的缓存路径"""
# 使用图片路径的hash作为缓存文件名
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)
# 分离图片路径和PIL对象
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'):
# PIL Image对象可能有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特征提取逻辑"""
# 预处理:resize到224x224 + 转tensor
transform = transforms.Compose([
transforms.Resize((self.vgg_input_size, self.vgg_input_size)), # 224x224
transforms.ToTensor()
])
# 转换图片为张量
img_tensors = []
for img in images:
if img is None:
continue
if isinstance(img, Image.Image):
# 确保是RGB模式
if img.mode != 'RGB':
img = img.convert('RGB')
img_tensor = transform(img)
else:
# 如果已经是tensor,需要resize到224x224
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
# 确保是RGB 3通道
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():
# ImageNet标准归一化
normalized_batch = torch.stack([self.normalize(img) for img in batch_tensor])
# 分批处理避免内存问题
process_batch_size = 16 # VGG比较占内存,减小batch size
features_list = []
for i in range(0, len(normalized_batch), process_batch_size):
batch = normalized_batch[i:i+process_batch_size]
# VGG特征提取
batch_features = self.vgg_model(batch) # 输出: [N, 512, 7, 7]
# 全局平均池化到512维
batch_features = F.adaptive_avg_pool2d(batch_features, (1, 1)) # [N, 512, 1, 1]
batch_features = batch_features.view(batch_features.size(0), -1) # [N, 512]
features_list.append(batch_features)
if features_list:
features = torch.cat(features_list, dim=0) # [total_images, 512]
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)
# Feature dropout(训练时使用)
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切换"""
# 🔑 如果没有传入 is_test_mode,从 args 中推断
if is_test_mode is None:
# 如果args中有epoch信息,可以从中推断
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'):
# 新版本:支持train/val分离
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:
# ImageNet类型数据集或folder
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]
# 检查是否使用VGG特征且启用缓存
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:
# 返回图片路径而不是PIL对象,让VGG特征提取器处理缓存
return block_paths
else:
# 传统模式:加载PIL图片
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)
# 转回PIL Image
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
# 获取epoch的映射
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:
# 使用VGG特征提取(带缓存)
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)
# 填充到100个样本
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)
# k近邻
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)
# 堆叠所有batch数据
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] # 显示前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:
# Convert numpy arrays to lists for JSON serialization
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 ===")
# 测试前几个epoch的映射
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 ===")
# 创建测试args
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] # 只测试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 # 启用VGG特征
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.")# simple_image_data.py - Block 3/3 - 主要接口和工具函数
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)
# 获取epoch的映射
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:
# 重新使用PIL图片进行VGG特征提取
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)
# 填充到100个样本
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)
# k近邻
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)
# 堆叠所有batch数据
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:
# Convert numpy arrays to lists for JSON serialization
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 ===")
# 测试前几个epoch的映射
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}")
# 测试epoch映射
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.")