File size: 9,837 Bytes
c9aee57 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | """
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":
# Integrated: 使用完整 forward 的最终输出
features = model.encode_dense(image, normalize=False, keep_shape=True, mode="vanilla")
elif mode in ["csa_vfm_distill", "qq_vfm_distill", "vv_vfm_distill"]:
# Decoupled: 使用解耦模式的输出
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)
# features: (B, C, H, W)
B, C, H, W = features.shape
# 转换为 (H*W, C) 用于 PCA
features_flat = features[0].permute(1, 2, 0).reshape(-1, C).cpu().numpy()
# PCA 降维到 3 维
pca = PCA(n_components=3)
features_pca = pca.fit_transform(features_flat)
# 归一化到 [0, 1]
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():
# 使用 csa_vfm_distill 模式提取 Q 和 K(实际上是 Q 和 V 的 self-attention)
features, context = model.encode_dense(image, normalize=False, keep_shape=True, mode="csa_vfm_distill")
# context 应该是 (q_feature, k_feature) 或类似结构
if isinstance(context, tuple) and len(context) >= 2:
q_feature, v_feature = context[0], context[1]
# 可视化 Q 特征
B, N, nHead, dim = q_feature.shape
H = W = int(np.sqrt(N - 1)) # 减去 cls token
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
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)")
|