#!/usr/bin/env python3 # vgg_cache_builder.py - Block 1/2 - 基础功能和数据处理 import os import sys import torch import numpy as np from PIL import Image import torchvision.transforms as transforms from torchvision.models import vgg16 import torch.nn.functional as F from tqdm import tqdm import argparse import hashlib import time from collections import defaultdict import threading from concurrent.futures import ThreadPoolExecutor import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import accuracy_score, classification_report from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import warnings warnings.filterwarnings('ignore') class VGGCacheBuilder: def __init__(self, dataset_path, cache_dir, device='cuda', batch_size=16): self.dataset_path = dataset_path self.cache_dir = cache_dir self.device = device self.batch_size = batch_size self.vgg_model = None self.normalize = None self.vgg_input_size = 224 # 初始化VGG模型 self._init_vgg_model() # 扫描数据集 self.class_info = {} self.total_blocks_per_class = {} self._scan_dataset() def _init_vgg_model(self): """初始化VGG模型""" print(f"Loading VGG16 model on {self.device}...") self.vgg_model = vgg16(pretrained=True).features.to(self.device) self.vgg_model.eval() self.normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) print("VGG16 model loaded successfully!") def _scan_dataset(self): """扫描ImageNet100数据集""" print(f"Scanning dataset: {self.dataset_path}") # 找到所有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() print(f"Found {len(train_folders)} train folders and {'1' if val_folder else '0'} val folder") # 收集所有类别 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)) print(f"Found {len(all_classes)} classes") # 为每个类别收集图片路径 for class_idx, class_name in enumerate(all_classes): all_paths = [] # 从所有train文件夹收集 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] all_paths.extend(paths) # 从val文件夹收集(如果存在) 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] all_paths.extend(paths) self.class_info[class_idx] = { 'class_name': class_name, 'image_paths': all_paths, 'total_images': len(all_paths) } self.total_blocks_per_class[class_idx] = max(1, len(all_paths) // 50) # 50 images per block if class_idx < 10: # 只显示前10个类别避免输出过长 print(f"Class {class_idx:2d} ({class_name}): {len(all_paths):4d} images, {self.total_blocks_per_class[class_idx]:2d} blocks") def get_epoch_mapping(self, epoch, batch_size, class_combination_seed=42): """获取epoch的类别组合映射""" num_classes = len(self.class_info) # 计算总的类别组合数 (C1, C2) where C1 != C2 total_class_combinations = num_classes * (num_classes - 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 % self.total_blocks_per_class.get(class1, 1) block2 = block_round % self.total_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 }) return batch_mappings def get_images_for_epochs(self, max_epochs, batch_size): """获取前max_epochs个epoch需要的所有图片路径""" all_image_paths = set() print(f"Analyzing first {max_epochs} epochs with batch_size={batch_size}...") for epoch in tqdm(range(max_epochs), desc="Analyzing epochs"): batch_mappings = self.get_epoch_mapping(epoch, batch_size) for mapping in batch_mappings: class1, class2 = mapping['class1'], mapping['class2'] block1, block2 = mapping['block1'], mapping['block2'] # 获取class1的图片 if class1 in self.class_info: class1_paths = self.class_info[class1]['image_paths'] start_idx = block1 * 50 end_idx = min(start_idx + 50, len(class1_paths)) if start_idx < len(class1_paths): selected_paths = class1_paths[start_idx:end_idx] all_image_paths.update(selected_paths) # 获取class2的图片 if class2 in self.class_info: class2_paths = self.class_info[class2]['image_paths'] start_idx = block2 * 50 end_idx = min(start_idx + 50, len(class2_paths)) if start_idx < len(class2_paths): selected_paths = class2_paths[start_idx:end_idx] all_image_paths.update(selected_paths) return list(all_image_paths) def get_image_cache_path(self, image_path): """获取单张图片的缓存路径""" path_hash = hashlib.md5(image_path.encode()).hexdigest() return os.path.join(self.cache_dir, f"{path_hash}.pt") def extract_vgg_features(self, image_paths): """批量提取VGG特征""" # 预处理pipeline transform = transforms.Compose([ transforms.Resize((self.vgg_input_size, self.vgg_input_size)), transforms.ToTensor() ]) # 分批处理 all_features = [] valid_paths = [] for i in tqdm(range(0, len(image_paths), self.batch_size), desc="Extracting VGG features"): batch_paths = image_paths[i:i + self.batch_size] batch_images = [] batch_valid_paths = [] # 加载这一批图片 for img_path in batch_paths: try: img = Image.open(img_path).convert('RGB') img_tensor = transform(img) # 确保是RGB 3通道 if img_tensor.shape[0] != 3: if img_tensor.shape[0] == 1: img_tensor = img_tensor.repeat(3, 1, 1) else: img_tensor = img_tensor[:3] batch_images.append(img_tensor) batch_valid_paths.append(img_path) except Exception as e: print(f"Error loading {img_path}: {e}") continue if not batch_images: continue # 转换为批处理张量 batch_tensor = torch.stack(batch_images).to(self.device) with torch.no_grad(): # ImageNet标准归一化 normalized_batch = torch.stack([self.normalize(img) for img in batch_tensor]) # VGG特征提取 batch_features = self.vgg_model(normalized_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] all_features.extend(batch_features.cpu()) valid_paths.extend(batch_valid_paths) return all_features, valid_paths def cache_features(self, image_paths, overwrite=False): """缓存VGG特征到本地""" os.makedirs(self.cache_dir, exist_ok=True) # 检查哪些图片还没有缓存 uncached_paths = [] cached_count = 0 print("Checking existing cache...") for img_path in tqdm(image_paths, desc="Checking cache"): cache_path = self.get_image_cache_path(img_path) if overwrite or not os.path.exists(cache_path): uncached_paths.append(img_path) else: cached_count += 1 print(f"Found {cached_count} already cached images") print(f"Need to process {len(uncached_paths)} images") if not uncached_paths: print("All images are already cached!") return # 提取特征 print(f"Extracting VGG features for {len(uncached_paths)} images...") start_time = time.time() features, valid_paths = self.extract_vgg_features(uncached_paths) extraction_time = time.time() - start_time print(f"Feature extraction completed in {extraction_time:.2f} seconds") print(f"Successfully processed {len(valid_paths)}/{len(uncached_paths)} images") # 保存特征到缓存 print("Saving features to cache...") saved_count = 0 failed_count = 0 for feature, img_path in tqdm(zip(features, valid_paths), desc="Saving cache", total=len(features)): cache_path = self.get_image_cache_path(img_path) try: torch.save(feature, cache_path) saved_count += 1 except Exception as e: print(f"Failed to save cache for {img_path}: {e}") failed_count += 1 print(f"Cache saved: {saved_count} files, {failed_count} failed") # 计算缓存大小 total_size = 0 cache_files = [f for f in os.listdir(self.cache_dir) if f.endswith('.pt')] for cache_file in cache_files: total_size += os.path.getsize(os.path.join(self.cache_dir, cache_file)) print(f"Total cache size: {total_size / (1024 * 1024):.1f} MB ({len(cache_files)} files)") def load_batch_features_and_labels(self, epoch, batch_idx, batch_size=200): """加载指定epoch中某个batch的特征和标签""" batch_mappings = self.get_epoch_mapping(epoch, batch_size) if batch_idx >= len(batch_mappings): print(f"Batch {batch_idx} not found in epoch {epoch}") return None, None, None mapping = batch_mappings[batch_idx] class1, class2 = mapping['class1'], mapping['class2'] block1, block2 = mapping['block1'], mapping['block2'] # 获取两个类别的图片路径 all_paths = [] all_labels = [] # Class 1 images if class1 in self.class_info: class1_paths = self.class_info[class1]['image_paths'] start_idx = block1 * 50 end_idx = min(start_idx + 50, len(class1_paths)) if start_idx < len(class1_paths): paths = class1_paths[start_idx:end_idx] all_paths.extend(paths) all_labels.extend([class1] * len(paths)) # Class 2 images if class2 in self.class_info: class2_paths = self.class_info[class2]['image_paths'] start_idx = block2 * 50 end_idx = min(start_idx + 50, len(class2_paths)) if start_idx < len(class2_paths): paths = class2_paths[start_idx:end_idx] all_paths.extend(paths) all_labels.extend([class2] * len(paths)) # 从缓存加载特征 features = [] valid_labels = [] for img_path, label in zip(all_paths, all_labels): cache_path = self.get_image_cache_path(img_path) if os.path.exists(cache_path): try: feature = torch.load(cache_path, map_location='cpu') features.append(feature) valid_labels.append(label) except: continue if features: features_tensor = torch.stack(features) binary_labels = [0 if label == class1 else 1 for label in valid_labels] batch_info = { 'class1': class1, 'class2': class2, 'class1_name': self.class_info[class1]['class_name'], 'class2_name': self.class_info[class2]['class_name'], 'block1': block1, 'block2': block2 } return features_tensor, torch.tensor(binary_labels), batch_info else: return None, None, None # vgg_cache_builder.py - Block 2/2 - 验证功能和主函数 def analyze_embedding_quality(self, epochs_to_test=[0, 10, 50], batches_per_epoch=5, save_plots=True): """分析embedding质量:同类相似性和不同类分离度""" print("\n" + "="*60) print("🔍 EMBEDDING QUALITY ANALYSIS") print("="*60) results = {} for epoch in epochs_to_test: print(f"\n📊 Analyzing epoch {epoch}...") epoch_results = { 'intra_class_distances': [], 'inter_class_distances': [], 'intra_class_sims': [], 'inter_class_sims': [], 'batch_info': [] } # 分析多个batch for batch_idx in range(min(batches_per_epoch, 200)): # 最多分析200个batch features, labels, batch_info = self.load_batch_features_and_labels(epoch, batch_idx) if features is None: continue # 分离两个类别的特征 class1_mask = (labels == 0) class2_mask = (labels == 1) class1_features = features[class1_mask] class2_features = features[class2_mask] if len(class1_features) < 2 or len(class2_features) < 2: continue # 计算类内距离(同类特征之间的距离) class1_distances = torch.cdist(class1_features, class1_features, p=2) class2_distances = torch.cdist(class2_features, class2_features, p=2) # 只取上三角矩阵(避免重复和对角线) class1_dist_values = class1_distances[torch.triu(torch.ones_like(class1_distances), 1) == 1] class2_dist_values = class2_distances[torch.triu(torch.ones_like(class2_distances), 1) == 1] # 计算类间距离(不同类特征之间的距离) inter_distances = torch.cdist(class1_features, class2_features, p=2) inter_dist_values = inter_distances.flatten() # 计算余弦相似度 class1_norm = F.normalize(class1_features, p=2, dim=1) class2_norm = F.normalize(class2_features, p=2, dim=1) class1_sims = torch.mm(class1_norm, class1_norm.t()) class2_sims = torch.mm(class2_norm, class2_norm.t()) inter_sims = torch.mm(class1_norm, class2_norm.t()) class1_sim_values = class1_sims[torch.triu(torch.ones_like(class1_sims), 1) == 1] class2_sim_values = class2_sims[torch.triu(torch.ones_like(class2_sims), 1) == 1] inter_sim_values = inter_sims.flatten() # 存储结果 epoch_results['intra_class_distances'].extend([class1_dist_values.mean().item(), class2_dist_values.mean().item()]) epoch_results['inter_class_distances'].append(inter_dist_values.mean().item()) epoch_results['intra_class_sims'].extend([class1_sim_values.mean().item(), class2_sim_values.mean().item()]) epoch_results['inter_class_sims'].append(inter_sim_values.mean().item()) epoch_results['batch_info'].append(batch_info) # 计算统计量 if epoch_results['intra_class_distances']: intra_dist_mean = np.mean(epoch_results['intra_class_distances']) inter_dist_mean = np.mean(epoch_results['inter_class_distances']) intra_sim_mean = np.mean(epoch_results['intra_class_sims']) inter_sim_mean = np.mean(epoch_results['inter_class_sims']) separation_ratio = inter_dist_mean / intra_dist_mean similarity_ratio = intra_sim_mean / inter_sim_mean print(f" 📏 Distance Analysis:") print(f" Intra-class distance: {intra_dist_mean:.4f} (same class)") print(f" Inter-class distance: {inter_dist_mean:.4f} (different class)") print(f" Separation ratio: {separation_ratio:.4f} (higher is better)") print(f" 📐 Similarity Analysis:") print(f" Intra-class similarity: {intra_sim_mean:.4f} (same class)") print(f" Inter-class similarity: {inter_sim_mean:.4f} (different class)") print(f" Similarity ratio: {similarity_ratio:.4f} (higher is better)") results[epoch] = { 'intra_dist_mean': intra_dist_mean, 'inter_dist_mean': inter_dist_mean, 'intra_sim_mean': intra_sim_mean, 'inter_sim_mean': inter_sim_mean, 'separation_ratio': separation_ratio, 'similarity_ratio': similarity_ratio, 'raw_data': epoch_results } else: print(f" ❌ No valid data for epoch {epoch}") # 可视化结果 if save_plots and results: self._plot_embedding_analysis(results) return results def icl_pe_classifier_test(self, epochs_to_test=[0, 10, 50], batches_per_epoch=10, k_feat=4, context_sizes=[5, 10, 20]): """真正的In-Context Learning PE测试 - 每个图独立计算PE""" print("\n" + "="*60) print("🧠 IN-CONTEXT LEARNING PE PERFORMANCE TEST") print("="*60) print("🔍 Key insight: PE features are graph-specific and cannot be transferred between graphs!") print("📊 Each batch forms its own graph with its own PE basis") results = {} for epoch in epochs_to_test: print(f"\n🔬 Testing epoch {epoch}...") epoch_results = {} for context_size in context_sizes: print(f" 📋 Context size: {context_size}") all_accuracies = [] all_context_seps = [] all_query_seps = [] # 测试多个batch,每个batch独立 for batch_idx in range(min(batches_per_epoch, 50)): features, labels, batch_info = self.load_batch_features_and_labels(epoch, batch_idx) if features is None or len(features) < context_size * 2: continue # 构建这个batch的图和PE pe_features, laplacian = self._compute_batch_pe(features, k_feat) if pe_features is None: continue # ICL测试:在同一个图内做context learning batch_accuracy, context_sep, query_sep = self._icl_test_single_batch( pe_features, labels, context_size ) if batch_accuracy is not None: all_accuracies.append(batch_accuracy) all_context_seps.append(context_sep) all_query_seps.append(query_sep) if all_accuracies: avg_accuracy = np.mean(all_accuracies) std_accuracy = np.std(all_accuracies) avg_context_sep = np.mean(all_context_seps) avg_query_sep = np.mean(all_query_seps) print(f" 🎯 Average ICL accuracy: {avg_accuracy:.3f} ± {std_accuracy:.3f}") print(f" 📏 Context separation: {avg_context_sep:.4f}") print(f" 📏 Query separation: {avg_query_sep:.4f}") print(f" 📊 Valid batches: {len(all_accuracies)}") epoch_results[context_size] = { 'mean_accuracy': avg_accuracy, 'std_accuracy': std_accuracy, 'context_separation': avg_context_sep, 'query_separation': avg_query_sep, 'valid_batches': len(all_accuracies), 'all_accuracies': all_accuracies } else: print(f" ❌ No valid batches for context size {context_size}") results[epoch] = epoch_results # 可视化ICL结果 if results: self._plot_icl_results(results, context_sizes) return results def _compute_batch_pe(self, features, k_feat): """为单个batch计算PE特征""" try: # 计算邻接矩阵 distances = torch.cdist(features, features, p=2) adjacency = torch.exp(-1.0 * distances ** 2) # scale_rbf = 1.0 # k近邻 k_nn = min(10, len(features) - 1) 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) batch_indices = torch.arange(len(features)).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) # 计算拉普拉斯矩阵 degree = adj_matrix.sum(dim=1) degree = torch.clamp(degree, min=1e-10) D_inv_sqrt = torch.diag(degree.pow(-0.5)) laplacian = torch.eye(len(features)) - D_inv_sqrt @ adj_matrix @ D_inv_sqrt # 计算PE特征向量 eigenvals, eigenvecs = torch.linalg.eigh(laplacian) pe_features = eigenvecs[:, :k_feat] # [batch_size, k_feat] return pe_features, laplacian except Exception as e: print(f" ⚠️ PE computation failed: {e}") return None, None def _icl_test_single_batch(self, pe_features, labels, context_size): """在单个batch内进行ICL测试""" try: n_samples = len(pe_features) # 确保每个类别在context中都有足够样本 class_0_indices = torch.where(labels == 0)[0] class_1_indices = torch.where(labels == 1)[0] if len(class_0_indices) < context_size // 2 or len(class_1_indices) < context_size // 2: return None, None, None # 平衡采样context:每个类别取context_size//2个样本 context_per_class = context_size // 2 # 随机选择context样本 selected_class_0 = class_0_indices[torch.randperm(len(class_0_indices))[:context_per_class]] selected_class_1 = class_1_indices[torch.randperm(len(class_1_indices))[:context_per_class]] context_indices = torch.cat([selected_class_0, selected_class_1]) # 剩余的作为query all_indices = torch.arange(n_samples) query_mask = torch.ones(n_samples, dtype=torch.bool) query_mask[context_indices] = False query_indices = all_indices[query_mask] if len(query_indices) < 2: return None, None, None # 分离context和query context_features = pe_features[context_indices] context_labels = labels[context_indices] query_features = pe_features[query_indices] query_labels = labels[query_indices] # 🎯 ICL方法:在context上训练分类器,在query上测试 accuracy = self._icl_train_classifier(context_features, context_labels, query_features, query_labels) # 计算特征分离度 context_sep = self._compute_separation_ratio(context_features, context_labels) query_sep = self._compute_separation_ratio(query_features, query_labels) return accuracy, context_sep, query_sep except Exception as e: print(f" ⚠️ ICL test failed: {e}") return None, None, None def _icl_mlp_classifier(self, context_features, context_labels, query_features, query_labels): """ICL MLP分类器 - 处理非线性PE特征""" try: from sklearn.neural_network import MLPClassifier X_context = context_features.numpy() y_context = context_labels.numpy() X_query = query_features.numpy() y_query = query_labels.numpy() # 检查context是否有两个类别 if len(np.unique(y_context)) < 2: return 0.0 # 检查是否有足够的数据训练MLP if len(X_context) < 8: # MLP至少需要8个样本 return 0.0 # 标准化特征(基于context的统计量) scaler = StandardScaler() X_context_scaled = scaler.fit_transform(X_context) X_query_scaled = scaler.transform(X_query) # 🧠 训练MLP分类器 # 根据数据量调整网络大小 if len(X_context) <= 20: hidden_layers = (16,) # 小数据:简单网络 max_iter = 500 else: hidden_layers = (32, 16) # 大数据:深层网络 max_iter = 1000 mlp = MLPClassifier( hidden_layer_sizes=hidden_layers, activation='relu', solver='adam', alpha=0.01, # L2正则化 batch_size='auto', learning_rate='adaptive', learning_rate_init=0.001, max_iter=max_iter, random_state=42, early_stopping=True, validation_fraction=0.1, n_iter_no_change=10, tol=1e-4 ) # 训练MLP mlp.fit(X_context_scaled, y_context) # 🎯 在query上预测 y_pred = mlp.predict(X_query_scaled) accuracy = accuracy_score(y_query, y_pred) return accuracy except Exception as e: print(f" ⚠️ MLP classifier training failed: {e}") return 0.0 def _icl_train_classifier(self, context_features, context_labels, query_features, query_labels): """ICL线性分类器(保留原版本用于对比)""" try: # 转换为numpy用于sklearn X_context = context_features.numpy() y_context = context_labels.numpy() X_query = query_features.numpy() y_query = query_labels.numpy() # 检查context是否有两个类别 if len(np.unique(y_context)) < 2: return 0.0 # 标准化特征(基于context的统计量) scaler = StandardScaler() X_context_scaled = scaler.fit_transform(X_context) X_query_scaled = scaler.transform(X_query) # 用context的统计量转换query # 🔥 在context上训练线性分类器 clf = LogisticRegression( random_state=42, max_iter=1000, C=1.0, # 正则化参数 class_weight='balanced' # 处理类别不平衡 ) clf.fit(X_context_scaled, y_context) # 🎯 在query上预测 y_pred = clf.predict(X_query_scaled) accuracy = accuracy_score(y_query, y_pred) return accuracy except Exception as e: print(f" ⚠️ Linear classifier training failed: {e}") return 0.0 def _icl_multiple_methods(self, context_features, context_labels, query_features, query_labels): """比较多种ICL方法 - 包含MLP""" results = {} # 方法1: MLP分类器(新增的主要方法) results['mlp_classifier'] = self._icl_mlp_classifier( context_features, context_labels, query_features, query_labels ) # 方法2: 线性分类器(原有方法) results['linear_classifier'] = self._icl_train_classifier( context_features, context_labels, query_features, query_labels ) # 方法3: 最近邻 results['nearest_neighbor'] = self._icl_nearest_neighbor( context_features, context_labels, query_features, query_labels ) # 方法4: 原型分类 results['prototype'] = self._icl_prototype_classification( context_features, context_labels, query_features, query_labels ) # 方法5: SVM(如果数据足够) if len(context_features) >= 10: results['svm'] = self._icl_svm_classifier( context_features, context_labels, query_features, query_labels ) else: results['svm'] = 0.0 return results def comprehensive_icl_test(self, epochs_to_test=[0, 10, 50], batches_per_epoch=20, k_feat=4, context_sizes=[5, 10, 20]): """全面的ICL测试:比较多种方法包括MLP""" print("\n" + "="*70) print("🧠 COMPREHENSIVE IN-CONTEXT LEARNING PE TEST") print("="*70) print("🔍 Comparing multiple ICL methods on graph-specific PE features") print("📊 Methods: MLP, Linear Classifier, SVM, Nearest Neighbor, Prototype") results = {} for epoch in epochs_to_test: print(f"\n🔬 Testing epoch {epoch}...") epoch_results = {} for context_size in context_sizes: print(f" 📋 Context size: {context_size}") method_results = { 'mlp_classifier': [], 'linear_classifier': [], 'svm': [], 'nearest_neighbor': [], 'prototype': [] } valid_batches = 0 # 测试多个batch for batch_idx in range(min(batches_per_epoch, 50)): features, labels, batch_info = self.load_batch_features_and_labels(epoch, batch_idx) if features is None or len(features) < context_size * 2: continue # 构建PE pe_features, _ = self._compute_batch_pe(features, k_feat) if pe_features is None: continue # ICL测试 batch_results = self._icl_test_comprehensive_single_batch( pe_features, labels, context_size ) if batch_results is not None: for method in method_results: if method in batch_results: method_results[method].append(batch_results[method]) valid_batches += 1 # 计算统计量 if valid_batches > 0: print(f" 📊 Valid batches: {valid_batches}") # 按性能排序显示结果 method_averages = {} for method in method_results: if method_results[method]: mean_acc = np.mean(method_results[method]) std_acc = np.std(method_results[method]) method_averages[method] = mean_acc print(f" 🎯 {method.replace('_', ' ').title()}: {mean_acc:.3f} ± {std_acc:.3f}") # 显示最佳方法 if method_averages: best_method = max(method_averages, key=method_averages.get) best_score = method_averages[best_method] print(f" 🏆 Best method: {best_method.replace('_', ' ').title()} ({best_score:.3f})") epoch_results[context_size] = { 'method_results': method_results, 'valid_batches': valid_batches, 'best_method': best_method if method_averages else None, 'best_score': best_score if method_averages else 0 } else: print(f" ❌ No valid batches for context size {context_size}") results[epoch] = epoch_results # 可视化比较结果 if results: self._plot_comprehensive_icl_results(results, context_sizes) return results def _plot_comprehensive_icl_results(self, results, context_sizes): """绘制全面ICL比较结果 - 包含MLP""" epochs = sorted(results.keys()) methods = ['mlp_classifier', 'linear_classifier', 'svm', 'nearest_neighbor', 'prototype'] method_labels = ['MLP Classifier', 'Linear Classifier', 'SVM', 'Nearest Neighbor', 'Prototype'] colors = ['darkblue', 'blue', 'red', 'green', 'purple'] fig, axes = plt.subplots(2, 2, figsize=(16, 12)) fig.suptitle('Comprehensive ICL Methods Comparison (with MLP)', fontsize=16, fontweight='bold') # 1. 不同方法在不同context size下的表现 (latest epoch) latest_epoch = max(epochs) for i, context_size in enumerate(context_sizes): if context_size in results[latest_epoch]: method_accuracies = [] method_stds = [] for method in methods: accs = results[latest_epoch][context_size]['method_results'][method] if accs: method_accuracies.append(np.mean(accs)) method_stds.append(np.std(accs)) else: method_accuracies.append(0) method_stds.append(0) x_pos = np.arange(len(methods)) + i * 0.25 axes[0, 0].bar(x_pos, method_accuracies, width=0.25, label=f'Context {context_size}', alpha=0.8) axes[0, 0].set_xlabel('ICL Method') axes[0, 0].set_ylabel('Accuracy') axes[0, 0].set_title(f'Method Comparison (Epoch {latest_epoch})') axes[0, 0].set_xticks(np.arange(len(methods)) + 0.25) axes[0, 0].set_xticklabels(method_labels, rotation=45) axes[0, 0].legend() axes[0, 0].grid(True, alpha=0.3) axes[0, 0].set_ylim([0, 1]) # 2. MLP vs Linear Classifier vs Nearest Neighbor 对比 key_methods = ['mlp_classifier', 'linear_classifier', 'nearest_neighbor'] key_labels = ['MLP', 'Linear', 'Nearest Neighbor'] key_colors = ['darkblue', 'blue', 'green'] for epoch in epochs: for i, method in enumerate(key_methods): context_sizes_available = [] method_accs = [] for context_size in context_sizes: if context_size in results[epoch]: accs = results[epoch][context_size]['method_results'][method] if accs: context_sizes_available.append(context_size) method_accs.append(np.mean(accs)) if context_sizes_available: axes[0, 1].plot(context_sizes_available, method_accs, 'o-', label=f'{key_labels[i]} (Epoch {epoch})', color=key_colors[i], alpha=0.7, linewidth=2) axes[0, 1].set_xlabel('Context Size') axes[0, 1].set_ylabel('Accuracy') axes[0, 1].set_title('Key Methods Comparison') axes[0, 1].legend() axes[0, 1].grid(True, alpha=0.3) axes[0, 1].set_ylim([0, 1]) # 3. 最佳方法统计 mid_context = context_sizes[len(context_sizes)//2] best_method_counts = {} for epoch in epochs: if mid_context in results[epoch] and 'best_method' in results[epoch][mid_context]: best_method = results[epoch][mid_context]['best_method'] if best_method: best_method_counts[best_method] = best_method_counts.get(best_method, 0) + 1 if best_method_counts: methods_sorted = sorted(best_method_counts.keys()) counts = [best_method_counts[m] for m in methods_sorted] method_labels_sorted = [m.replace('_', ' ').title() for m in methods_sorted] axes[1, 0].bar(method_labels_sorted, counts, alpha=0.7, color='orange') axes[1, 0].set_xlabel('Method') axes[1, 0].set_ylabel('Times Best') axes[1, 0].set_title(f'Best Method Frequency (Context {mid_context})') axes[1, 0].tick_params(axis='x', rotation=45) axes[1, 0].grid(True, alpha=0.3) # 4. MLP vs 最强基线对比 mlp_wins = 0 baseline_wins = 0 for epoch in epochs: for context_size in context_sizes: if context_size in results[epoch]: mlp_accs = results[epoch][context_size]['method_results']['mlp_classifier'] nn_accs = results[epoch][context_size]['method_results']['nearest_neighbor'] if mlp_accs and nn_accs: mlp_avg = np.mean(mlp_accs) nn_avg = np.mean(nn_accs) if mlp_avg > nn_avg: mlp_wins += 1 else: baseline_wins += 1 win_data = [mlp_wins, baseline_wins] win_labels = ['MLP Wins', 'Nearest Neighbor Wins'] colors_pie = ['darkblue', 'green'] if sum(win_data) > 0: axes[1, 1].pie(win_data, labels=win_labels, colors=colors_pie, autopct='%1.1f%%') axes[1, 1].set_title('MLP vs Nearest Neighbor Head-to-Head') plt.tight_layout() plot_path = os.path.join(os.path.dirname(self.cache_dir), 'comprehensive_icl_with_mlp.png') plt.savefig(plot_path, dpi=300, bbox_inches='tight') print(f"📊 Comprehensive ICL with MLP plot saved to: {plot_path}") plt.close() def _icl_svm_classifier(self, context_features, context_labels, query_features, query_labels): """ICL SVM分类器""" try: from sklearn.svm import SVC X_context = context_features.numpy() y_context = context_labels.numpy() X_query = query_features.numpy() y_query = query_labels.numpy() if len(np.unique(y_context)) < 2: return 0.0 # 标准化 scaler = StandardScaler() X_context_scaled = scaler.fit_transform(X_context) X_query_scaled = scaler.transform(X_query) # 训练SVM clf = SVC( kernel='rbf', C=1.0, gamma='scale', random_state=42, class_weight='balanced' ) clf.fit(X_context_scaled, y_context) # 预测 y_pred = clf.predict(X_query_scaled) accuracy = accuracy_score(y_query, y_pred) return accuracy except Exception as e: return 0.0 def comprehensive_icl_test(self, epochs_to_test=[0, 10, 50], batches_per_epoch=20, k_feat=4, context_sizes=[5, 10, 20]): """全面的ICL测试:比较多种方法""" print("\n" + "="*70) print("🧠 COMPREHENSIVE IN-CONTEXT LEARNING PE TEST") print("="*70) print("🔍 Comparing multiple ICL methods on graph-specific PE features") print("📊 Methods: Linear Classifier, SVM, Nearest Neighbor, Prototype") results = {} for epoch in epochs_to_test: print(f"\n🔬 Testing epoch {epoch}...") epoch_results = {} for context_size in context_sizes: print(f" 📋 Context size: {context_size}") method_results = { 'linear_classifier': [], 'svm': [], 'nearest_neighbor': [], 'prototype': [] } valid_batches = 0 # 测试多个batch for batch_idx in range(min(batches_per_epoch, 50)): features, labels, batch_info = self.load_batch_features_and_labels(epoch, batch_idx) if features is None or len(features) < context_size * 2: continue # 构建PE pe_features, _ = self._compute_batch_pe(features, k_feat) if pe_features is None: continue # ICL测试 batch_results = self._icl_test_comprehensive_single_batch( pe_features, labels, context_size ) if batch_results is not None: for method in method_results: if method in batch_results: method_results[method].append(batch_results[method]) valid_batches += 1 # 计算统计量 if valid_batches > 0: print(f" 📊 Valid batches: {valid_batches}") for method in method_results: if method_results[method]: mean_acc = np.mean(method_results[method]) std_acc = np.std(method_results[method]) print(f" 🎯 {method.replace('_', ' ').title()}: {mean_acc:.3f} ± {std_acc:.3f}") epoch_results[context_size] = { 'method_results': method_results, 'valid_batches': valid_batches } else: print(f" ❌ No valid batches for context size {context_size}") results[epoch] = epoch_results # 可视化比较结果 if results: self._plot_comprehensive_icl_results(results, context_sizes) return results def _icl_test_comprehensive_single_batch(self, pe_features, labels, context_size): """单个batch的全面ICL测试""" try: n_samples = len(pe_features) # 检查数据充足性 class_0_indices = torch.where(labels == 0)[0] class_1_indices = torch.where(labels == 1)[0] if len(class_0_indices) < context_size // 2 or len(class_1_indices) < context_size // 2: return None # 采样context context_per_class = context_size // 2 selected_class_0 = class_0_indices[torch.randperm(len(class_0_indices))[:context_per_class]] selected_class_1 = class_1_indices[torch.randperm(len(class_1_indices))[:context_per_class]] context_indices = torch.cat([selected_class_0, selected_class_1]) # 获取query all_indices = torch.arange(n_samples) query_mask = torch.ones(n_samples, dtype=torch.bool) query_mask[context_indices] = False query_indices = all_indices[query_mask] if len(query_indices) < 2: return None # 分离数据 context_features = pe_features[context_indices] context_labels = labels[context_indices] query_features = pe_features[query_indices] query_labels = labels[query_indices] # 测试所有方法 results = self._icl_multiple_methods( context_features, context_labels, query_features, query_labels ) return results except Exception as e: return None def _plot_comprehensive_icl_results(self, results, context_sizes): """绘制全面ICL比较结果""" epochs = sorted(results.keys()) methods = ['linear_classifier', 'svm', 'nearest_neighbor', 'prototype'] method_labels = ['Linear Classifier', 'SVM', 'Nearest Neighbor', 'Prototype'] colors = ['blue', 'red', 'green', 'purple'] fig, axes = plt.subplots(2, 2, figsize=(16, 12)) fig.suptitle('Comprehensive ICL Methods Comparison', fontsize=16, fontweight='bold') # 1. 不同方法在不同context size下的表现 (latest epoch) latest_epoch = max(epochs) for i, context_size in enumerate(context_sizes): if context_size in results[latest_epoch]: method_accuracies = [] method_stds = [] for method in methods: accs = results[latest_epoch][context_size]['method_results'][method] if accs: method_accuracies.append(np.mean(accs)) method_stds.append(np.std(accs)) else: method_accuracies.append(0) method_stds.append(0) x_pos = np.arange(len(methods)) + i * 0.2 axes[0, 0].bar(x_pos, method_accuracies, width=0.2, label=f'Context {context_size}', alpha=0.8) axes[0, 0].set_xlabel('ICL Method') axes[0, 0].set_ylabel('Accuracy') axes[0, 0].set_title(f'Method Comparison (Epoch {latest_epoch})') axes[0, 0].set_xticks(np.arange(len(methods)) + 0.2) axes[0, 0].set_xticklabels(method_labels, rotation=45) axes[0, 0].legend() axes[0, 0].grid(True, alpha=0.3) # 2. Linear Classifier vs Context Size for epoch in epochs: context_sizes_available = [] linear_accs = [] for context_size in context_sizes: if context_size in results[epoch]: accs = results[epoch][context_size]['method_results']['linear_classifier'] if accs: context_sizes_available.append(context_size) linear_accs.append(np.mean(accs)) if context_sizes_available: axes[0, 1].plot(context_sizes_available, linear_accs, 'o-', label=f'Epoch {epoch}', linewidth=2, markersize=6) axes[0, 1].set_xlabel('Context Size') axes[0, 1].set_ylabel('Linear Classifier Accuracy') axes[0, 1].set_title('Context Size Effect') axes[0, 1].legend() axes[0, 1].grid(True, alpha=0.3) axes[0, 1].set_ylim([0, 1]) # 3. 方法对比 (固定context size) mid_context = context_sizes[len(context_sizes)//2] # 中等context size for i, method in enumerate(methods): method_accs_epochs = [] for epoch in epochs: if mid_context in results[epoch]: accs = results[epoch][mid_context]['method_results'][method] method_accs_epochs.append(np.mean(accs) if accs else 0) else: method_accs_epochs.append(0) axes[1, 0].plot(epochs, method_accs_epochs, 'o-', label=method_labels[i], color=colors[i], linewidth=2, markersize=6) axes[1, 0].set_xlabel('Epoch') axes[1, 0].set_ylabel('Accuracy') axes[1, 0].set_title(f'Method Comparison Across Epochs (Context {mid_context})') axes[1, 0].legend() axes[1, 0].grid(True, alpha=0.3) axes[1, 0].set_ylim([0, 1]) # 4. 数据可用性 for epoch in epochs: valid_counts = [] for context_size in context_sizes: if context_size in results[epoch]: valid_counts.append(results[epoch][context_size]['valid_batches']) else: valid_counts.append(0) axes[1, 1].plot(context_sizes, valid_counts, 'o-', label=f'Epoch {epoch}', linewidth=2, markersize=6) axes[1, 1].set_xlabel('Context Size') axes[1, 1].set_ylabel('Valid Batches') axes[1, 1].set_title('Data Availability') axes[1, 1].legend() axes[1, 1].grid(True, alpha=0.3) plt.tight_layout() plot_path = os.path.join(os.path.dirname(self.cache_dir), 'comprehensive_icl_comparison.png') plt.savefig(plot_path, dpi=300, bbox_inches='tight') print(f"📊 Comprehensive ICL comparison plot saved to: {plot_path}") plt.close() def _icl_nearest_neighbor(self, context_features, context_labels, query_features, query_labels): """基于context的最近邻分类""" try: # 对每个query样本,找到context中最近的样本 distances = torch.cdist(query_features, context_features, p=2) # [n_query, n_context] nearest_indices = torch.argmin(distances, dim=1) # [n_query] # 预测标签 predicted_labels = context_labels[nearest_indices] # 计算准确率 accuracy = (predicted_labels == query_labels).float().mean().item() return accuracy except Exception as e: print(f" ⚠️ Nearest neighbor classification failed: {e}") return 0.0 def _icl_prototype_classification(self, context_features, context_labels, query_features, query_labels): """基于原型的ICL分类""" try: # 计算每个类别的原型(中心点) class_0_mask = (context_labels == 0) class_1_mask = (context_labels == 1) if class_0_mask.sum() == 0 or class_1_mask.sum() == 0: return 0.0 prototype_0 = context_features[class_0_mask].mean(dim=0) # [k_feat] prototype_1 = context_features[class_1_mask].mean(dim=0) # [k_feat] # 对每个query样本,计算到两个原型的距离 dist_to_0 = torch.norm(query_features - prototype_0.unsqueeze(0), p=2, dim=1) dist_to_1 = torch.norm(query_features - prototype_1.unsqueeze(0), p=2, dim=1) # 预测为距离更近的类别 predicted_labels = (dist_to_0 > dist_to_1).long() # 计算准确率 accuracy = (predicted_labels == query_labels).float().mean().item() return accuracy except Exception as e: print(f" ⚠️ Prototype classification failed: {e}") return 0.0 def _compute_separation_ratio(self, features, labels): """计算特征的类间/类内距离比""" try: class_0_mask = (labels == 0) class_1_mask = (labels == 1) class_0_features = features[class_0_mask] class_1_features = features[class_1_mask] if len(class_0_features) < 2 or len(class_1_features) < 2: return 0.0 # 类内距离 intra_dist_0 = torch.cdist(class_0_features, class_0_features, p=2) intra_dist_1 = torch.cdist(class_1_features, class_1_features, p=2) # 取上三角矩阵的平均值 intra_dist_0_vals = intra_dist_0[torch.triu(torch.ones_like(intra_dist_0), 1) == 1] intra_dist_1_vals = intra_dist_1[torch.triu(torch.ones_like(intra_dist_1), 1) == 1] avg_intra_dist = torch.cat([intra_dist_0_vals, intra_dist_1_vals]).mean().item() # 类间距离 inter_dist = torch.cdist(class_0_features, class_1_features, p=2).mean().item() return inter_dist / avg_intra_dist if avg_intra_dist > 0 else 0.0 except Exception as e: return 0.0 def _plot_icl_results(self, results, context_sizes): """绘制ICL结果""" epochs = sorted(results.keys()) fig, axes = plt.subplots(2, 2, figsize=(15, 12)) fig.suptitle('In-Context Learning PE Performance Analysis', fontsize=16, fontweight='bold') colors = ['blue', 'red', 'green', 'purple', 'orange'] # 1. 不同context size的准确率对比 for i, context_size in enumerate(context_sizes): accuracies = [] for epoch in epochs: if context_size in results[epoch]: accuracies.append(results[epoch][context_size]['mean_accuracy']) else: accuracies.append(0) axes[0, 0].plot(epochs, accuracies, 'o-', label=f'Context {context_size}', color=colors[i % len(colors)], linewidth=2, markersize=6) axes[0, 0].set_xlabel('Epoch') axes[0, 0].set_ylabel('ICL Accuracy') axes[0, 0].set_title('ICL Accuracy vs Context Size') axes[0, 0].legend() axes[0, 0].grid(True, alpha=0.3) axes[0, 0].set_ylim([0, 1]) # 2. Context separation quality for i, context_size in enumerate(context_sizes): context_seps = [] for epoch in epochs: if context_size in results[epoch]: context_seps.append(results[epoch][context_size]['context_separation']) else: context_seps.append(0) axes[0, 1].plot(epochs, context_seps, 's-', label=f'Context {context_size}', color=colors[i % len(colors)], linewidth=2, markersize=6) axes[0, 1].set_xlabel('Epoch') axes[0, 1].set_ylabel('Separation Ratio') axes[0, 1].set_title('Context Feature Separation') axes[0, 1].legend() axes[0, 1].grid(True, alpha=0.3) # 3. Accuracy vs Context Size (最新epoch) latest_epoch = max(epochs) if latest_epoch in results: context_sizes_available = [] accuracies_latest = [] stds_latest = [] for context_size in context_sizes: if context_size in results[latest_epoch]: context_sizes_available.append(context_size) accuracies_latest.append(results[latest_epoch][context_size]['mean_accuracy']) stds_latest.append(results[latest_epoch][context_size]['std_accuracy']) if context_sizes_available: axes[1, 0].errorbar(context_sizes_available, accuracies_latest, yerr=stds_latest, 'o-', color='green', linewidth=2, markersize=8, capsize=5) axes[1, 0].set_xlabel('Context Size') axes[1, 0].set_ylabel('ICL Accuracy') axes[1, 0].set_title(f'Context Size Effect (Epoch {latest_epoch})') axes[1, 0].grid(True, alpha=0.3) axes[1, 0].set_ylim([0, 1]) # 4. Valid batches count for i, context_size in enumerate(context_sizes): valid_counts = [] for epoch in epochs: if context_size in results[epoch]: valid_counts.append(results[epoch][context_size]['valid_batches']) else: valid_counts.append(0) axes[1, 1].bar([e + i*0.1 - 0.2 for e in epochs], valid_counts, width=0.1, label=f'Context {context_size}', color=colors[i % len(colors)], alpha=0.7) axes[1, 1].set_xlabel('Epoch') axes[1, 1].set_ylabel('Valid Batches') axes[1, 1].set_title('Data Availability') axes[1, 1].legend() axes[1, 1].grid(True, alpha=0.3) plt.tight_layout() plot_path = os.path.join(os.path.dirname(self.cache_dir), 'icl_pe_performance.png') plt.savefig(plot_path, dpi=300, bbox_inches='tight') print(f"📊 ICL PE performance plot saved to: {plot_path}") plt.close() def simple_pe_classifier_test(self, epochs_to_test=[0, 10, 50], batches_per_epoch=10, k_feat=4): """简单的PE+分类器性能测试(原始版本 - 跨图合并数据)""" print("\n" + "="*60) print("🧠 TRADITIONAL PE + CLASSIFIER PERFORMANCE TEST") print("="*60) print("⚠️ Warning: This method merges PE features from different graphs!") print("📊 PE features are graph-specific and may not be comparable across batches") results = {} for epoch in epochs_to_test: print(f"\n🔬 Testing epoch {epoch}...") all_embeddings = [] all_labels = [] # 收集多个batch的数据 for batch_idx in range(min(batches_per_epoch, 50)): # 限制batch数量 features, labels, batch_info = self.load_batch_features_and_labels(epoch, batch_idx) if features is None or len(features) < 20: # 至少要有20个样本 continue # 计算邻接矩阵和拉普拉斯矩阵 pe_features, _ = self._compute_batch_pe(features, k_feat) if pe_features is not None: all_embeddings.append(pe_features) all_labels.append(labels) if not all_embeddings: print(f" ❌ No valid batches for epoch {epoch}") continue # 合并所有数据 combined_embeddings = torch.cat(all_embeddings, dim=0) combined_labels = torch.cat(all_labels, dim=0) print(f" 📊 Total samples: {len(combined_embeddings)}") print(f" 🎯 PE embedding shape: {combined_embeddings.shape}") # 简单线性分类器测试 accuracy = self._test_linear_classifier(combined_embeddings, combined_labels) # 计算特征质量指标 metrics = self._compute_embedding_metrics(combined_embeddings, combined_labels) results[epoch] = { 'accuracy': accuracy, 'total_samples': len(combined_embeddings), 'pe_dim': k_feat, **metrics } print(f" 🎯 Linear classifier accuracy: {accuracy:.3f}") print(f" 📏 Intra-class distance: {metrics['intra_dist']:.4f}") print(f" 📏 Inter-class distance: {metrics['inter_dist']:.4f}") print(f" 📊 Separation ratio: {metrics['separation_ratio']:.4f}") # 绘制结果 if len(results) > 1: self._plot_classifier_results(results) return results def _test_linear_classifier(self, embeddings, labels): """测试简单线性分类器性能""" # 转换为numpy X = embeddings.numpy() y = labels.numpy() if len(np.unique(y)) < 2: return 0.0 # 只有一个类别 # 标准化特征 scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 分割训练测试集 test_size = min(0.3, 0.8) # 至少保留20%用于训练 X_train, X_test, y_train, y_test = train_test_split( X_scaled, y, test_size=test_size, random_state=42, stratify=y ) # 训练分类器 clf = LogisticRegression(random_state=42, max_iter=1000) clf.fit(X_train, y_train) # 预测 y_pred = clf.predict(X_test) accuracy = accuracy_score(y_test, y_pred) return accuracy def _compute_embedding_metrics(self, embeddings, labels): """计算embedding质量指标""" class0_mask = (labels == 0) class1_mask = (labels == 1) class0_emb = embeddings[class0_mask] class1_emb = embeddings[class1_mask] metrics = {} if len(class0_emb) > 1 and len(class1_emb) > 1: # 类内距离 class0_dist = torch.cdist(class0_emb, class0_emb, p=2) class1_dist = torch.cdist(class1_emb, class1_emb, p=2) # 只取上三角(避免对角线和重复) class0_dist_vals = class0_dist[torch.triu(torch.ones_like(class0_dist), 1) == 1] class1_dist_vals = class1_dist[torch.triu(torch.ones_like(class1_dist), 1) == 1] intra_dist = torch.cat([class0_dist_vals, class1_dist_vals]).mean().item() # 类间距离 inter_dist = torch.cdist(class0_emb, class1_emb, p=2).mean().item() metrics['intra_dist'] = intra_dist metrics['inter_dist'] = inter_dist metrics['separation_ratio'] = inter_dist / intra_dist if intra_dist > 0 else 0 else: metrics['intra_dist'] = 0 metrics['inter_dist'] = 0 metrics['separation_ratio'] = 0 return metrics def _plot_embedding_analysis(self, results): """绘制embedding分析结果""" epochs = sorted(results.keys()) # 创建图表 fig, axes = plt.subplots(2, 2, figsize=(15, 12)) fig.suptitle('VGG Embedding Quality Analysis', fontsize=16, fontweight='bold') # 距离分析 intra_dists = [results[e]['intra_dist_mean'] for e in epochs] inter_dists = [results[e]['inter_dist_mean'] for e in epochs] axes[0, 0].plot(epochs, intra_dists, 'o-', label='Intra-class (same)', color='blue') axes[0, 0].plot(epochs, inter_dists, 's-', label='Inter-class (different)', color='red') axes[0, 0].set_xlabel('Epoch') axes[0, 0].set_ylabel('Average Distance') axes[0, 0].set_title('Distance Analysis') axes[0, 0].legend() axes[0, 0].grid(True, alpha=0.3) # 相似度分析 intra_sims = [results[e]['intra_sim_mean'] for e in epochs] inter_sims = [results[e]['inter_sim_mean'] for e in epochs] axes[0, 1].plot(epochs, intra_sims, 'o-', label='Intra-class (same)', color='blue') axes[0, 1].plot(epochs, inter_sims, 's-', label='Inter-class (different)', color='red') axes[0, 1].set_xlabel('Epoch') axes[0, 1].set_ylabel('Average Similarity') axes[0, 1].set_title('Similarity Analysis') axes[0, 1].legend() axes[0, 1].grid(True, alpha=0.3) # 分离比率 sep_ratios = [results[e]['separation_ratio'] for e in epochs] axes[1, 0].plot(epochs, sep_ratios, 'o-', color='green', linewidth=2) axes[1, 0].set_xlabel('Epoch') axes[1, 0].set_ylabel('Separation Ratio') axes[1, 0].set_title('Class Separation Quality') axes[1, 0].grid(True, alpha=0.3) # 相似度比率 sim_ratios = [results[e]['similarity_ratio'] for e in epochs] axes[1, 1].plot(epochs, sim_ratios, 's-', color='purple', linewidth=2) axes[1, 1].set_xlabel('Epoch') axes[1, 1].set_ylabel('Similarity Ratio') axes[1, 1].set_title('Similarity Quality') axes[1, 1].grid(True, alpha=0.3) plt.tight_layout() plot_path = os.path.join(os.path.dirname(self.cache_dir), 'embedding_quality_analysis.png') plt.savefig(plot_path, dpi=300, bbox_inches='tight') print(f"📊 Quality analysis plot saved to: {plot_path}") plt.close() def _plot_classifier_results(self, results): """绘制分类器性能结果""" epochs = sorted(results.keys()) fig, axes = plt.subplots(2, 2, figsize=(15, 10)) fig.suptitle('PE + Classifier Performance Analysis', fontsize=16, fontweight='bold') # 准确率 accuracies = [results[e]['accuracy'] for e in epochs] axes[0, 0].plot(epochs, accuracies, 'o-', color='green', linewidth=2, markersize=8) axes[0, 0].set_xlabel('Epoch') axes[0, 0].set_ylabel('Accuracy') axes[0, 0].set_title('Linear Classifier Accuracy') axes[0, 0].grid(True, alpha=0.3) axes[0, 0].set_ylim([0, 1]) # 分离比率 sep_ratios = [results[e]['separation_ratio'] for e in epochs] axes[0, 1].plot(epochs, sep_ratios, 's-', color='blue', linewidth=2, markersize=8) axes[0, 1].set_xlabel('Epoch') axes[0, 1].set_ylabel('Separation Ratio') axes[0, 1].set_title('Class Separation Quality') axes[0, 1].grid(True, alpha=0.3) # 类内vs类间距离 intra_dists = [results[e]['intra_dist'] for e in epochs] inter_dists = [results[e]['inter_dist'] for e in epochs] axes[1, 0].plot(epochs, intra_dists, 'o-', label='Intra-class', color='red') axes[1, 0].plot(epochs, inter_dists, 's-', label='Inter-class', color='blue') axes[1, 0].set_xlabel('Epoch') axes[1, 0].set_ylabel('Distance') axes[1, 0].set_title('PE Embedding Distances') axes[1, 0].legend() axes[1, 0].grid(True, alpha=0.3) # 样本数量 sample_counts = [results[e]['total_samples'] for e in epochs] axes[1, 1].bar(epochs, sample_counts, alpha=0.7, color='orange') axes[1, 1].set_xlabel('Epoch') axes[1, 1].set_ylabel('Total Samples') axes[1, 1].set_title('Sample Count per Epoch') axes[1, 1].grid(True, alpha=0.3) plt.tight_layout() plot_path = os.path.join(os.path.dirname(self.cache_dir), 'pe_classifier_performance.png') plt.savefig(plot_path, dpi=300, bbox_inches='tight') print(f"📊 PE classifier performance plot saved to: {plot_path}") plt.close() def comprehensive_validation(self, max_epochs=50, validation_batches=20, k_feat=4, save_dir=None): """综合验证:embedding质量 + PE性能""" print("\n" + "="*80) print("🔬 COMPREHENSIVE VGG CACHE VALIDATION") print("="*80) if save_dir is None: save_dir = os.path.dirname(self.cache_dir) # 选择测试的epoch test_epochs = [] if max_epochs >= 1: test_epochs.append(0) if max_epochs >= 10: test_epochs.append(9) if max_epochs >= 50: test_epochs.append(49) if max_epochs >= 100: test_epochs.append(99) print(f"🎯 Testing epochs: {test_epochs}") print(f"📦 Validation batches per epoch: {validation_batches}") print(f"🔧 PE dimensions: {k_feat}") # 1. Embedding质量分析 print("\n📊 Step 1: VGG Embedding Quality Analysis...") embedding_results = self.analyze_embedding_quality( epochs_to_test=test_epochs, batches_per_epoch=validation_batches, save_plots=True ) # 2. PE+分类器性能测试 print("\n🧠 Step 2: PE + Classifier Performance Test...") classifier_results = self.simple_pe_classifier_test( epochs_to_test=test_epochs, batches_per_epoch=validation_batches, k_feat=k_feat ) # 3. 生成综合报告 print("\n📋 Step 3: Generating Comprehensive Report...") report = self._generate_validation_report(embedding_results, classifier_results, test_epochs) # 保存报告 report_path = os.path.join(save_dir, 'vgg_cache_validation_report.txt') with open(report_path, 'w') as f: f.write(report) print(f"📄 Comprehensive report saved to: {report_path}") # 4. 生成建议 recommendations = self._generate_recommendations(embedding_results, classifier_results) print("\n💡 RECOMMENDATIONS:") for rec in recommendations: print(f" {rec}") return { 'embedding_results': embedding_results, 'classifier_results': classifier_results, 'recommendations': recommendations, 'test_epochs': test_epochs } def _generate_validation_report(self, embedding_results, classifier_results, test_epochs): """生成验证报告""" from datetime import datetime report = [] report.append("=" * 80) report.append("VGG CACHE VALIDATION REPORT") report.append("=" * 80) report.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") report.append(f"Dataset: {self.dataset_path}") report.append(f"Cache Directory: {self.cache_dir}") report.append(f"Test Epochs: {test_epochs}") report.append("") # Embedding质量结果 report.append("📊 VGG EMBEDDING QUALITY ANALYSIS") report.append("-" * 50) for epoch in test_epochs: if epoch in embedding_results: r = embedding_results[epoch] report.append(f"Epoch {epoch}:") report.append(f" Intra-class distance: {r['intra_dist_mean']:.4f}") report.append(f" Inter-class distance: {r['inter_dist_mean']:.4f}") report.append(f" Separation ratio: {r['separation_ratio']:.4f}") report.append(f" Intra-class similarity: {r['intra_sim_mean']:.4f}") report.append(f" Inter-class similarity: {r['inter_sim_mean']:.4f}") report.append(f" Similarity ratio: {r['similarity_ratio']:.4f}") report.append("") # PE+分类器结果 report.append("🧠 PE + CLASSIFIER PERFORMANCE") report.append("-" * 50) for epoch in test_epochs: if epoch in classifier_results: r = classifier_results[epoch] report.append(f"Epoch {epoch}:") report.append(f" Linear classifier accuracy: {r['accuracy']:.3f}") report.append(f" Total samples: {r['total_samples']}") report.append(f" PE embedding dimension: {r['pe_dim']}") report.append(f" Intra-class distance: {r['intra_dist']:.4f}") report.append(f" Inter-class distance: {r['inter_dist']:.4f}") report.append(f" Separation ratio: {r['separation_ratio']:.4f}") report.append("") return "\n".join(report) def _generate_recommendations(self, embedding_results, classifier_results): """生成使用建议""" recommendations = [] # 分析最佳性能epoch if classifier_results: best_epoch = max(classifier_results.keys(), key=lambda k: classifier_results[k]['accuracy']) best_acc = classifier_results[best_epoch]['accuracy'] if best_acc > 0.8: recommendations.append(f"✅ Excellent performance! Best accuracy: {best_acc:.3f} at epoch {best_epoch}") elif best_acc > 0.6: recommendations.append(f"✨ Good performance! Best accuracy: {best_acc:.3f} at epoch {best_epoch}") else: recommendations.append(f"⚠️ Performance needs improvement. Best accuracy: {best_acc:.3f} at epoch {best_epoch}") # 分析embedding质量趋势 if len(embedding_results) > 1: epochs = sorted(embedding_results.keys()) sep_ratios = [embedding_results[e]['separation_ratio'] for e in epochs] if sep_ratios[-1] > sep_ratios[0]: recommendations.append("📈 Embedding quality improves with more epochs") else: recommendations.append("📉 Early epochs might be sufficient for your use case") # 缓存建议 if classifier_results: max_samples = max(r['total_samples'] for r in classifier_results.values()) if max_samples > 1000: recommendations.append("💾 Large cache detected - consider SSD storage for faster access") avg_sep_ratio = np.mean([r['separation_ratio'] for r in classifier_results.values()]) if avg_sep_ratio > 2.0: recommendations.append("🎯 Excellent class separation - VGG features work well for your data") elif avg_sep_ratio > 1.5: recommendations.append("👍 Good class separation - VGG features are suitable") else: recommendations.append("💭 Consider fine-tuning VGG or trying different feature extraction") return recommendations def main(): parser = argparse.ArgumentParser(description="Build VGG feature cache for ImageNet100 with validation") parser.add_argument("--dataset_path", type=str, required=True, help="Path to ImageNet100 dataset") parser.add_argument("--cache_dir", type=str, help="Cache directory (default: dataset_path + '_vgg')") parser.add_argument("--max_epochs", type=int, default=501, help="Number of epochs to analyze (default: 501)") parser.add_argument("--batch_size", type=int, default=200, help="Batch size for training (default: 200)") parser.add_argument("--vgg_batch_size", type=int, default=16, help="Batch size for VGG inference (default: 16)") parser.add_argument("--device", type=str, default="cuda", help="Device to use (default: cuda)") parser.add_argument("--overwrite", action="store_true", help="Overwrite existing cache files") parser.add_argument("--analyze_only", action="store_true", help="Only analyze which images are needed, don't extract features") # 新增验证选项 parser.add_argument("--validate", action="store_true", help="Run comprehensive validation after caching") parser.add_argument("--validation_epochs", type=int, default=50, help="Max epochs for validation (default: 50)") parser.add_argument("--validation_batches", type=int, default=20, help="Batches per epoch for validation (default: 20)") parser.add_argument("--k_feat", type=int, default=4, help="PE embedding dimensions for validation (default: 4)") parser.add_argument("--embedding_only", action="store_true", help="Only run embedding quality analysis") parser.add_argument("--classifier_only", action="store_true", help="Only run PE + classifier test") args = parser.parse_args() # 设置缓存目录 if args.cache_dir is None: args.cache_dir = f"{args.dataset_path}_vgg" print("=== VGG Feature Cache Builder with Validation ===") print(f"Dataset path: {args.dataset_path}") print(f"Cache directory: {args.cache_dir}") print(f"Max epochs: {args.max_epochs}") print(f"Training batch size: {args.batch_size}") print(f"VGG batch size: {args.vgg_batch_size}") print(f"Device: {args.device}") print(f"Validation enabled: {args.validate}") print() # 检查数据集路径 if not os.path.exists(args.dataset_path): print(f"Error: Dataset path does not exist: {args.dataset_path}") sys.exit(1) # 创建缓存构建器 builder = VGGCacheBuilder( dataset_path=args.dataset_path, cache_dir=args.cache_dir, device=args.device, batch_size=args.vgg_batch_size ) # 分析前max_epochs个epoch需要的图片 if not args.embedding_only and not args.classifier_only: required_images = builder.get_images_for_epochs(args.max_epochs, args.batch_size) print(f"Analysis complete:") print(f" Total unique images needed: {len(required_images):,}") print(f" Total classes: {len(builder.class_info)}") print(f" Total class combinations: {len(builder.class_info) * (len(builder.class_info) - 1):,}") # 计算覆盖率 total_images = sum(info['total_images'] for info in builder.class_info.values()) coverage = len(required_images) / total_images * 100 print(f" Coverage: {len(required_images):,}/{total_images:,} ({coverage:.1f}%)") if args.analyze_only: print("\nAnalysis only mode - not extracting features") return # 构建缓存 print(f"\nBuilding VGG feature cache...") start_time = time.time() builder.cache_features(required_images, overwrite=args.overwrite) total_time = time.time() - start_time print(f"\nCache building completed in {total_time:.2f} seconds") print(f"Average time per image: {total_time/len(required_images)*1000:.2f} ms") # 验证阶段 if args.validate or args.embedding_only or args.classifier_only: print(f"\n🔬 Starting validation phase...") if args.embedding_only: builder.analyze_embedding_quality( epochs_to_test=[0, 9, 49] if args.validation_epochs >= 50 else [0], batches_per_epoch=args.validation_batches, save_plots=True ) elif args.classifier_only: builder.simple_pe_classifier_test( epochs_to_test=[0, 9, 49] if args.validation_epochs >= 50 else [0], batches_per_epoch=args.validation_batches, k_feat=args.k_feat ) else: builder.comprehensive_validation( max_epochs=args.validation_epochs, validation_batches=args.validation_batches, k_feat=args.k_feat ) if __name__ == "__main__": main()