| """ |
| PCA 可视化 - Feature Space Visualization |
| |
| 对比 DeCLIP 解耦蒸馏和 Integrated 集成蒸馏的特征质量 |
| |
| 使用方法: |
| 1. 加载训练好的模型 |
| 2. 提取特征 |
| 3. PCA 降维到 3 维 |
| 4. 映射为 RGB 图像 |
| """ |
|
|
| import torch |
| import torch.nn.functional as F |
| import numpy as np |
| from PIL import Image |
| import matplotlib.pyplot as plt |
| from sklearn.decomposition import PCA |
| from typing import Tuple, Optional, Dict |
| import os |
|
|
|
|
| class PCAFeatureVisualizer: |
| """ |
| PCA 特征可视化器 |
| |
| 用于对比不同方法的特征质量 |
| """ |
| |
| def __init__(self, save_dir: str = "pca_visualization_results"): |
| self.save_dir = save_dir |
| os.makedirs(save_dir, exist_ok=True) |
| |
| def extract_and_visualize( |
| self, |
| model: torch.nn.Module, |
| image: torch.Tensor, |
| mode: str = "vanilla", |
| title: str = "Feature PCA", |
| save_name: Optional[str] = None |
| ) -> np.ndarray: |
| """ |
| 提取特征并进行 PCA 可视化 |
| |
| Args: |
| model: CLIP 模型 |
| image: 输入图像 (1, 3, H, W) |
| mode: 特征提取模式 ("vanilla" for integrated, "csa_vfm_distill" for decoupled) |
| title: 图像标题 |
| save_name: 保存文件名 |
| |
| Returns: |
| PCA RGB 图像 (H, W, 3) |
| """ |
| model.eval() |
| |
| with torch.no_grad(): |
| if mode == "vanilla": |
| |
| features = model.encode_dense(image, normalize=False, keep_shape=True, mode="vanilla") |
| elif mode in ["csa_vfm_distill", "qq_vfm_distill", "vv_vfm_distill"]: |
| |
| features, context = model.encode_dense(image, normalize=False, keep_shape=True, mode=mode) |
| else: |
| features = model.encode_dense(image, normalize=False, keep_shape=True, mode=mode) |
| |
| |
| B, C, H, W = features.shape |
| |
| |
| features_flat = features[0].permute(1, 2, 0).reshape(-1, C).cpu().numpy() |
| |
| |
| pca = PCA(n_components=3) |
| features_pca = pca.fit_transform(features_flat) |
| |
| |
| features_pca = (features_pca - features_pca.min()) / (features_pca.max() - features_pca.min() + 1e-8) |
| |
| |
| pca_image = features_pca.reshape(H, W, 3) |
| |
| |
| if save_name: |
| self._save_visualization(pca_image, title, save_name) |
| |
| return pca_image |
| |
| def compare_decoupled_vs_integrated( |
| self, |
| decoupled_model: torch.nn.Module, |
| integrated_model: torch.nn.Module, |
| image: torch.Tensor, |
| original_image: Optional[np.ndarray] = None, |
| save_name: str = "comparison.png" |
| ): |
| """ |
| 对比 DeCLIP 解耦蒸馏和 Integrated 集成蒸馏的特征 |
| |
| Args: |
| decoupled_model: 解耦蒸馏模型 |
| integrated_model: 集成蒸馏模型 |
| image: 输入图像 (1, 3, H, W) |
| original_image: 原始图像 (H, W, 3) 用于对比显示 |
| save_name: 保存文件名 |
| """ |
| |
| decoupled_pca = self.extract_and_visualize( |
| decoupled_model, image, mode="csa_vfm_distill", title="DeCLIP (Decoupled)" |
| ) |
| |
| |
| integrated_pca = self.extract_and_visualize( |
| integrated_model, image, mode="vanilla", title="Integrated" |
| ) |
| |
| |
| fig, axes = plt.subplots(1, 3 if original_image is not None else 2, figsize=(15, 5)) |
| |
| idx = 0 |
| if original_image is not None: |
| axes[idx].imshow(original_image) |
| axes[idx].set_title("Original Image", fontsize=14) |
| axes[idx].axis("off") |
| idx += 1 |
| |
| axes[idx].imshow(decoupled_pca) |
| axes[idx].set_title("DeCLIP (Decoupled)\nExpected: Clear boundaries, semantic coherence", fontsize=12) |
| axes[idx].axis("off") |
| idx += 1 |
| |
| axes[idx].imshow(integrated_pca) |
| axes[idx].set_title("Integrated\nExpected: Blurry, mixed features", fontsize=12) |
| axes[idx].axis("off") |
| |
| plt.tight_layout() |
| save_path = os.path.join(self.save_dir, save_name) |
| plt.savefig(save_path, dpi=150, bbox_inches="tight") |
| plt.close() |
| |
| print(f"Comparison saved to {save_path}") |
| |
| def extract_qv_features( |
| self, |
| model: torch.nn.Module, |
| image: torch.Tensor, |
| save_name: str = "qv_features.png" |
| ): |
| """ |
| 提取并可视化 DeCLIP 的 Q 和 V 特征 |
| |
| 用于展示解耦效果 |
| """ |
| model.eval() |
| |
| with torch.no_grad(): |
| |
| features, context = model.encode_dense(image, normalize=False, keep_shape=True, mode="csa_vfm_distill") |
| |
| |
| if isinstance(context, tuple) and len(context) >= 2: |
| q_feature, v_feature = context[0], context[1] |
| |
| |
| B, N, nHead, dim = q_feature.shape |
| H = W = int(np.sqrt(N - 1)) |
| |
| q_flat = q_feature[0, 1:].reshape(H, W, -1).cpu().numpy() |
| v_flat = v_feature[0, 1:].reshape(H, W, -1).cpu().numpy() |
| |
| |
| pca_q = PCA(n_components=3) |
| pca_v = PCA(n_components=3) |
| |
| q_pca = pca_q.fit_transform(q_flat.reshape(-1, q_flat.shape[-1])) |
| v_pca = pca_v.fit_transform(v_flat.reshape(-1, v_flat.shape[-1])) |
| |
| q_pca = (q_pca - q_pca.min()) / (q_pca.max() - q_pca.min() + 1e-8) |
| v_pca = (v_pca - v_pca.min()) / (v_pca.max() - v_pca.min() + 1e-8) |
| |
| q_image = q_pca.reshape(H, W, 3) |
| v_image = v_pca.reshape(H, W, 3) |
| |
| |
| fig, axes = plt.subplots(1, 2, figsize=(12, 5)) |
| |
| axes[0].imshow(q_image) |
| axes[0].set_title("Q Features (Content)", fontsize=14) |
| axes[0].axis("off") |
| |
| axes[1].imshow(v_image) |
| axes[1].set_title("V Features (Context)", fontsize=14) |
| axes[1].axis("off") |
| |
| plt.tight_layout() |
| save_path = os.path.join(self.save_dir, save_name) |
| plt.savefig(save_path, dpi=150, bbox_inches="tight") |
| plt.close() |
| |
| print(f"Q/V features saved to {save_path}") |
| return q_image, v_image |
| else: |
| print("Could not extract Q and V features. Context format unexpected.") |
| return None, None |
| |
| def _save_visualization(self, pca_image: np.ndarray, title: str, save_name: str): |
| """保存可视化结果""" |
| plt.figure(figsize=(8, 8)) |
| plt.imshow(pca_image) |
| plt.title(title, fontsize=14) |
| plt.axis("off") |
| |
| save_path = os.path.join(self.save_dir, save_name) |
| plt.savefig(save_path, dpi=150, bbox_inches="tight") |
| plt.close() |
| |
| print(f"Visualization saved to {save_path}") |
|
|
|
|
| def visualize_feature_comparison( |
| decoupled_checkpoint: str, |
| integrated_checkpoint: str, |
| image_path: str, |
| model_name: str = "EVA02-CLIP-B-16", |
| save_dir: str = "pca_visualization_results" |
| ): |
| """ |
| 便捷函数:加载模型并进行特征对比可视化 |
| |
| Args: |
| decoupled_checkpoint: 解耦蒸馏模型的 checkpoint 路径 |
| integrated_checkpoint: 集成蒸馏模型的 checkpoint 路径 |
| image_path: 测试图像路径 |
| model_name: 模型名称 |
| save_dir: 保存目录 |
| """ |
| from open_clip import create_model |
| from torchvision import transforms |
| from PIL import Image |
| |
| |
| print("Loading models...") |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| |
| decoupled_model = create_model(model_name, pretrained="eva", device=device) |
| decoupled_model.load_state_dict(torch.load(decoupled_checkpoint, map_location=device)["state_dict"]) |
| decoupled_model.eval() |
| |
| integrated_model = create_model(model_name, pretrained="eva", device=device) |
| integrated_model.load_state_dict(torch.load(integrated_checkpoint, map_location=device)["state_dict"]) |
| integrated_model.eval() |
| |
| |
| print(f"Loading image: {image_path}") |
| image = Image.open(image_path).convert("RGB") |
| original_image = np.array(image) |
| |
| |
| transform = transforms.Compose([ |
| transforms.Resize((560, 560)), |
| transforms.ToTensor(), |
| transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) |
| ]) |
| image_tensor = transform(image).unsqueeze(0).to(device) |
| |
| |
| visualizer = PCAFeatureVisualizer(save_dir) |
| visualizer.compare_decoupled_vs_integrated( |
| decoupled_model, integrated_model, image_tensor, |
| original_image=original_image, |
| save_name="decoupled_vs_integrated.png" |
| ) |
| |
| print("Done!") |
|
|
|
|
| if __name__ == "__main__": |
| print("PCA Feature Visualizer") |
| print("Usage:") |
| print(" from decoupling_analysis.pca_visualization import PCAFeatureVisualizer") |
| print(" visualizer = PCAFeatureVisualizer('save_dir')") |
| print(" visualizer.compare_decoupled_vs_integrated(decoupled_model, integrated_model, image)") |
|
|