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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import numpy as np
|
| 4 |
+
import os
|
| 5 |
+
import json
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
|
| 8 |
+
class time_travel_saver:
|
| 9 |
+
"""可视化数据提取器
|
| 10 |
+
|
| 11 |
+
用于保存模型训练过程中的各种数据,包括:
|
| 12 |
+
1. 模型权重 (.pth)
|
| 13 |
+
2. 高维特征 (representation/*.npy)
|
| 14 |
+
3. 预测结果 (prediction/*.npy)
|
| 15 |
+
4. 标签数据 (label/labels.npy)
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
def __init__(self, model, dataloader, device, save_dir, model_name,
|
| 19 |
+
auto_save_embedding=False, layer_name=None,show = False):
|
| 20 |
+
"""初始化
|
| 21 |
+
|
| 22 |
+
Args:
|
| 23 |
+
model: 要保存的模型实例
|
| 24 |
+
dataloader: 数据加载器(必须是顺序加载的)
|
| 25 |
+
device: 计算设备(cpu or gpu)
|
| 26 |
+
save_dir: 保存根目录
|
| 27 |
+
model_name: 模型名称
|
| 28 |
+
"""
|
| 29 |
+
self.model = model
|
| 30 |
+
self.dataloader = dataloader
|
| 31 |
+
self.device = device
|
| 32 |
+
self.save_dir = save_dir
|
| 33 |
+
self.model_name = model_name
|
| 34 |
+
self.auto_save = auto_save_embedding
|
| 35 |
+
self.layer_name = layer_name
|
| 36 |
+
|
| 37 |
+
if show and not layer_name:
|
| 38 |
+
layer_dimensions = self.show_dimensions()
|
| 39 |
+
# print(layer_dimensions)
|
| 40 |
+
|
| 41 |
+
def show_dimensions(self):
|
| 42 |
+
"""显示模型中所有层的名称和对应的维度
|
| 43 |
+
|
| 44 |
+
这个函数会输出模型中所有层的名称和它们的输出维度,
|
| 45 |
+
帮助用户选择合适的层来提取特征。
|
| 46 |
+
|
| 47 |
+
Returns:
|
| 48 |
+
layer_dimensions: 包含层名称和维度的字典
|
| 49 |
+
"""
|
| 50 |
+
activation = {}
|
| 51 |
+
layer_dimensions = {}
|
| 52 |
+
|
| 53 |
+
def get_activation(name):
|
| 54 |
+
def hook(model, input, output):
|
| 55 |
+
activation[name] = output.detach()
|
| 56 |
+
return hook
|
| 57 |
+
|
| 58 |
+
# 注册钩子到所有层
|
| 59 |
+
handles = []
|
| 60 |
+
for name, module in self.model.named_modules():
|
| 61 |
+
if isinstance(module, nn.Module) and not isinstance(module, nn.ModuleList) and not isinstance(module, nn.ModuleDict):
|
| 62 |
+
handles.append(module.register_forward_hook(get_activation(name)))
|
| 63 |
+
|
| 64 |
+
self.model.eval()
|
| 65 |
+
with torch.no_grad():
|
| 66 |
+
# 获取一个batch来分析每层的输出维度
|
| 67 |
+
inputs, _ = next(iter(self.dataloader))
|
| 68 |
+
inputs = inputs.to(self.device)
|
| 69 |
+
_ = self.model(inputs)
|
| 70 |
+
|
| 71 |
+
# 分析所有层的输出维度
|
| 72 |
+
print("\n模型各层的名称和维度:")
|
| 73 |
+
print("-" * 50)
|
| 74 |
+
print(f"{'层名称':<40} {'特征维度':<15} {'输出形状'}")
|
| 75 |
+
print("-" * 50)
|
| 76 |
+
|
| 77 |
+
for name, feat in activation.items():
|
| 78 |
+
if feat is None:
|
| 79 |
+
continue
|
| 80 |
+
|
| 81 |
+
# 获取特征维度(展平后)
|
| 82 |
+
feat_dim = feat.view(feat.size(0), -1).size(1)
|
| 83 |
+
layer_dimensions[name] = feat_dim
|
| 84 |
+
# 打印层信息
|
| 85 |
+
shape_str = str(list(feat.shape))
|
| 86 |
+
print(f"{name:<40} {feat_dim:<15} {shape_str}")
|
| 87 |
+
|
| 88 |
+
print("-" * 50)
|
| 89 |
+
print("注: 特征维度是将输出张量展平后的维度大小")
|
| 90 |
+
print("你可以通过修改time_travel_saver的layer_name参数来选择不同的层")
|
| 91 |
+
print("例如:layer_name='avg_pool'或layer_name='layer4'等")
|
| 92 |
+
|
| 93 |
+
# 移除所有钩子
|
| 94 |
+
for handle in handles:
|
| 95 |
+
handle.remove()
|
| 96 |
+
|
| 97 |
+
return layer_dimensions
|
| 98 |
+
|
| 99 |
+
def _extract_features_and_predictions(self):
|
| 100 |
+
"""提取特征和预测结果
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
features: 高维特征 [样本数, 特征维度]
|
| 104 |
+
predictions: 预测结果 [样本数, 类别数]
|
| 105 |
+
"""
|
| 106 |
+
features = []
|
| 107 |
+
predictions = []
|
| 108 |
+
indices = []
|
| 109 |
+
activation = {}
|
| 110 |
+
|
| 111 |
+
def get_activation(name):
|
| 112 |
+
def hook(model, input, output):
|
| 113 |
+
# 只在需要时保存激活值,避免内存浪费
|
| 114 |
+
if name not in activation or activation[name] is None:
|
| 115 |
+
activation[name] = output.detach()
|
| 116 |
+
return hook
|
| 117 |
+
|
| 118 |
+
# 根据层的名称或维度来选择层
|
| 119 |
+
|
| 120 |
+
# 注册钩子到所有层
|
| 121 |
+
handles = []
|
| 122 |
+
for name, module in self.model.named_modules():
|
| 123 |
+
if isinstance(module, nn.Module) and not isinstance(module, nn.ModuleList) and not isinstance(module, nn.ModuleDict):
|
| 124 |
+
handles.append(module.register_forward_hook(get_activation(name)))
|
| 125 |
+
|
| 126 |
+
self.model.eval()
|
| 127 |
+
with torch.no_grad():
|
| 128 |
+
# 首先获取一个batch来分析每层的输出维度
|
| 129 |
+
inputs, _ = next(iter(self.dataloader))
|
| 130 |
+
inputs = inputs.to(self.device)
|
| 131 |
+
_ = self.model(inputs)
|
| 132 |
+
|
| 133 |
+
# 如果指定了层名,则直接使用该层
|
| 134 |
+
if self.layer_name is not None:
|
| 135 |
+
if self.layer_name not in activation:
|
| 136 |
+
raise ValueError(f"指定的层 {self.layer_name} 不存在于模型中")
|
| 137 |
+
|
| 138 |
+
feat = activation[self.layer_name]
|
| 139 |
+
if feat is None:
|
| 140 |
+
raise ValueError(f"指定的层 {self.layer_name} 没有输出特征")
|
| 141 |
+
|
| 142 |
+
suitable_layer_name = self.layer_name
|
| 143 |
+
suitable_dim = feat.view(feat.size(0), -1).size(1)
|
| 144 |
+
print(f"使用指定的特征层: {suitable_layer_name}, 特征维度: {suitable_dim}")
|
| 145 |
+
else:
|
| 146 |
+
# 找到维度在指定范围内的层
|
| 147 |
+
target_dim_range = (256, 2048)
|
| 148 |
+
suitable_layer_name = None
|
| 149 |
+
suitable_dim = None
|
| 150 |
+
|
| 151 |
+
# 分析所有层的输出维度
|
| 152 |
+
for name, feat in activation.items():
|
| 153 |
+
if feat is None:
|
| 154 |
+
continue
|
| 155 |
+
feat_dim = feat.view(feat.size(0), -1).size(1)
|
| 156 |
+
if target_dim_range[0] <= feat_dim <= target_dim_range[1]:
|
| 157 |
+
suitable_layer_name = name
|
| 158 |
+
suitable_dim = feat_dim
|
| 159 |
+
break
|
| 160 |
+
|
| 161 |
+
if suitable_layer_name is None:
|
| 162 |
+
raise ValueError("没有找到合适维度的特征层")
|
| 163 |
+
|
| 164 |
+
print(f"自动选择的特征层: {suitable_layer_name}, 特征维度: {suitable_dim}")
|
| 165 |
+
|
| 166 |
+
# 保存层信息
|
| 167 |
+
layer_info = {
|
| 168 |
+
'layer_id': suitable_layer_name,
|
| 169 |
+
'dim': suitable_dim
|
| 170 |
+
}
|
| 171 |
+
layer_info_path = os.path.join(os.path.dirname(self.save_dir), 'layer_info.json')
|
| 172 |
+
with open(layer_info_path, 'w') as f:
|
| 173 |
+
json.dump(layer_info, f)
|
| 174 |
+
|
| 175 |
+
# 清除第一次运行的激活值
|
| 176 |
+
activation.clear()
|
| 177 |
+
|
| 178 |
+
# 现在处理所有数据
|
| 179 |
+
for batch_idx, (inputs, _) in enumerate(tqdm(self.dataloader, desc="提取特征和预测结果")):
|
| 180 |
+
inputs = inputs.to(self.device)
|
| 181 |
+
outputs = self.model(inputs) # 获取预测结果
|
| 182 |
+
|
| 183 |
+
# 获取并处理特征
|
| 184 |
+
feat = activation[suitable_layer_name]
|
| 185 |
+
flat_features = torch.flatten(feat, start_dim=1)
|
| 186 |
+
features.append(flat_features.cpu().numpy())
|
| 187 |
+
predictions.append(outputs.cpu().numpy())
|
| 188 |
+
|
| 189 |
+
# 清除本次的激活值
|
| 190 |
+
activation.clear()
|
| 191 |
+
|
| 192 |
+
# 移除所有钩子
|
| 193 |
+
for handle in handles:
|
| 194 |
+
handle.remove()
|
| 195 |
+
|
| 196 |
+
if len(features) > 0:
|
| 197 |
+
features = np.vstack(features)
|
| 198 |
+
predictions = np.vstack(predictions)
|
| 199 |
+
return features, predictions
|
| 200 |
+
else:
|
| 201 |
+
return np.array([]), np.array([])
|
| 202 |
+
|
| 203 |
+
def save_lables_index(self, path):
|
| 204 |
+
"""保存标签数据和索引信息
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
path: 保存路径
|
| 208 |
+
"""
|
| 209 |
+
os.makedirs(path, exist_ok=True)
|
| 210 |
+
labels_path = os.path.join(path, 'labels.npy')
|
| 211 |
+
index_path = os.path.join(path, 'index.json')
|
| 212 |
+
|
| 213 |
+
# 尝试从不同的属性获取标签
|
| 214 |
+
try:
|
| 215 |
+
if hasattr(self.dataloader.dataset, 'targets'):
|
| 216 |
+
# CIFAR10/CIFAR100使用targets属性
|
| 217 |
+
labels = np.array(self.dataloader.dataset.targets)
|
| 218 |
+
elif hasattr(self.dataloader.dataset, 'labels'):
|
| 219 |
+
# 某些数据集使用labels属性
|
| 220 |
+
labels = np.array(self.dataloader.dataset.labels)
|
| 221 |
+
else:
|
| 222 |
+
# 如果上面的方法都不起作用,则从数据加载器中收集标签
|
| 223 |
+
labels = []
|
| 224 |
+
for _, batch_labels in self.dataloader:
|
| 225 |
+
labels.append(batch_labels.numpy())
|
| 226 |
+
labels = np.concatenate(labels)
|
| 227 |
+
|
| 228 |
+
# 保存标签数据
|
| 229 |
+
np.save(labels_path, labels)
|
| 230 |
+
print(f"标签数据已保存到 {labels_path}")
|
| 231 |
+
|
| 232 |
+
# 创建数据集索引
|
| 233 |
+
num_samples = len(labels)
|
| 234 |
+
indices = list(range(num_samples))
|
| 235 |
+
|
| 236 |
+
# 创建索引字典
|
| 237 |
+
index_dict = {
|
| 238 |
+
"train": indices, # 所有数据默认为训练集
|
| 239 |
+
"test": [], # 初始为空
|
| 240 |
+
"validation": [] # 初始为空
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
# 保存索引到JSON文件
|
| 244 |
+
with open(index_path, 'w') as f:
|
| 245 |
+
json.dump(index_dict, f, indent=4)
|
| 246 |
+
|
| 247 |
+
print(f"数据集索引已保存到 {index_path}")
|
| 248 |
+
|
| 249 |
+
except Exception as e:
|
| 250 |
+
print(f"保存标签和索引时出错: {e}")
|
| 251 |
+
|
| 252 |
+
def save_checkpoint_embeddings_predictions(self, model = None):
|
| 253 |
+
"""保存所有数据"""
|
| 254 |
+
if model is not None:
|
| 255 |
+
self.model = model
|
| 256 |
+
# 保存模型权重
|
| 257 |
+
os.makedirs(self.save_dir, exist_ok=True)
|
| 258 |
+
model_path = os.path.join(self.save_dir,'model.pth')
|
| 259 |
+
torch.save(self.model.state_dict(), model_path)
|
| 260 |
+
|
| 261 |
+
if self.auto_save:
|
| 262 |
+
# 提取并保存特征和预测结果
|
| 263 |
+
features, predictions = self._extract_features_and_predictions()
|
| 264 |
+
|
| 265 |
+
# 保存特征
|
| 266 |
+
np.save(os.path.join(self.save_dir, 'embeddings.npy'), features)
|
| 267 |
+
# 保存预测结果
|
| 268 |
+
np.save(os.path.join(self.save_dir, 'predictions.npy'), predictions)
|
| 269 |
+
print("\n保存了以下数据:")
|
| 270 |
+
print(f"- 模型权重: {model_path}")
|
| 271 |
+
print(f"- 特征向量: [样本数: {features.shape[0]}, 特征维度: {features.shape[1]}]")
|
| 272 |
+
print(f"- 预测结果: [样本数: {predictions.shape[0]}, 类别数: {predictions.shape[1]}]")
|
ResNet-CIFAR10/Classification-normal/scripts/train.py
CHANGED
|
@@ -10,15 +10,10 @@ import logging
|
|
| 10 |
import numpy as np
|
| 11 |
from tqdm import tqdm
|
| 12 |
|
| 13 |
-
# 将项目根目录添加到Python路径中
|
| 14 |
-
current_dir = Path(__file__).resolve().parent
|
| 15 |
-
project_root = current_dir.parent.parent.parent
|
| 16 |
-
sys.path.append(str(project_root))
|
| 17 |
-
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
| 18 |
|
| 19 |
from dataset_utils import get_cifar10_dataloaders
|
| 20 |
from model import ResNet18
|
| 21 |
-
from
|
| 22 |
|
| 23 |
def setup_logger(log_file):
|
| 24 |
"""配置日志记录器,如果日志文件存在则覆盖
|
|
|
|
| 10 |
import numpy as np
|
| 11 |
from tqdm import tqdm
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
from dataset_utils import get_cifar10_dataloaders
|
| 15 |
from model import ResNet18
|
| 16 |
+
from get_representation import time_travel_saver
|
| 17 |
|
| 18 |
def setup_logger(log_file):
|
| 19 |
"""配置日志记录器,如果日志文件存在则覆盖
|
ttv_utils/save_embeddings.py
CHANGED
|
@@ -6,7 +6,7 @@ import json
|
|
| 6 |
from tqdm import tqdm
|
| 7 |
|
| 8 |
class time_travel_saver:
|
| 9 |
-
"""
|
| 10 |
|
| 11 |
用于保存模型训练过程中的各种数据,包括:
|
| 12 |
1. 模型权重 (.pth)
|
|
|
|
| 6 |
from tqdm import tqdm
|
| 7 |
|
| 8 |
class time_travel_saver:
|
| 9 |
+
"""可视化数据提取器
|
| 10 |
|
| 11 |
用于保存模型训练过程中的各种数据,包括:
|
| 12 |
1. 模型权重 (.pth)
|