File size: 15,162 Bytes
a3ab6c4 |
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 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
"""
特征预测器模块
该模块使用钩子机制从模型的中间层特征向量预测分类结果
"""
import torch
import torch.nn as nn
import json
import os
import torch.nn.functional as F
import numpy as np
from typing import Type, Union, Optional
class FeaturePredictor:
def __init__(self, model_class, model_weights_path, layer_info_path, device='cuda' if torch.cuda.is_available() else 'cpu'):
"""
初始化特征预测器
Args:
model_class: 模型类
model_weights_path: 模型权重文件路径
layer_info_path: 层信息文件路径
device: 运行设备
"""
self.device = device
self.model = model_class().to(device)
self.model.load_state_dict(torch.load(model_weights_path, map_location=device, weights_only=True))
self.model.eval()
# 加载层信息
with open(layer_info_path, 'r') as f:
layer_info = json.load(f)
self.target_layer = layer_info['layer_id']
self.feature_dim = layer_info['dim']
# 初始化变量
self.output_shape = None
self.inject_feature = None
self.handles = []
self.layer_name_map = {}
# 用于调试的变量
self.last_normalized_feature = None
self.last_reshaped_feature = None
self.last_layer_outputs = {}
# 注册钩子
self.register_hooks()
# 运行一次前向传播来获取形状
self._get_output_shape()
def _get_output_shape(self):
"""运行一次前向传播来获取目标层的输出形状"""
def shape_hook(module, input, output):
self.output_shape = output.shape[1:] # 不包括batch维度
print(f"[Init] 获取到目标层输出形状: {self.output_shape}")
return output
# 找到目标层并注册临时钩子
def find_layer(module, name=''):
for n, child in module.named_children():
current_name = f"{name}.{n}" if name else n
if current_name == self.target_layer:
handle = child.register_forward_hook(shape_hook)
return handle, True
else:
handle, found = find_layer(child, current_name)
if found:
return handle, True
return None, False
# 注册临时钩子
handle, found = find_layer(self.model)
if not found:
raise ValueError(f"未找到目标层: {self.target_layer}")
# 运行一次前向传播
with torch.no_grad():
dummy_input = torch.zeros(1, 3, 32, 32).to(self.device)
self.model(dummy_input)
# 移除临时钩子
handle.remove()
if self.output_shape is None:
raise RuntimeError("无法获取目标层的输出形状")
def register_hooks(self):
"""注册钩子函数,在目标层注入特征向量和监控每层输出"""
def print_tensor_info(name, tensor):
"""打印张量的统计信息"""
print(f"\n[Hook Debug] {name}:")
print(f"- 形状: {tensor.shape}")
print(f"- 数值范围: [{tensor.min().item():.4f}, {tensor.max().item():.4f}]")
print(f"- 均值: {tensor.mean().item():.4f}")
print(f"- 标准差: {tensor.std().item():.4f}")
def hook_fn(module, input, output):
"""钩子函数:输出层信息并在目标层注入特征"""
layer_name = self.layer_name_map.get(module, "未知层")
print(f"\n[Hook Debug] 层: {layer_name}")
print(f"- 类型: {type(module).__name__}")
# 输出输入信息
if input and len(input) > 0:
print_tensor_info("输入张量", input[0])
# 输出原始输出信息
print_tensor_info("输出张量", output)
# 如果是目标层且有注入特征,则替换输出
if layer_name == self.target_layer and self.inject_feature is not None:
print("\n[Hook Debug] 正在注入特征...")
print_tensor_info("注入特征", self.inject_feature)
print(f"[Hook Debug] 将层 {layer_name} 的输出从 {output.shape} 替换为注入特征 {self.inject_feature.shape}")
# 替换输出
output = self.inject_feature
print("[Hook Debug] 特征注入完成,将作为下一层的输入")
return output
return output
def hook_layer(module, name=''):
"""为每一层注册钩子"""
for n, child in module.named_children():
current_name = f"{name}.{n}" if name else n
# 保存层名到模块的映射
self.layer_name_map[child] = current_name
# 注册钩子
handle = child.register_forward_hook(hook_fn)
self.handles.append(handle)
# 递归处理子模块
hook_layer(child, current_name)
# 注册所有层的钩子
hook_layer(self.model)
print(f"[Debug] 钩子注册完成,共注册了 {len(self.handles)} 个钩子")
def reshape_feature(self, feature):
"""调整特征向量的形状"""
if self.output_shape is None:
raise RuntimeError("目标层的输出形状未初始化")
batch_size = feature.shape[0]
expected_dim = np.prod(self.output_shape)
# 检查输入特征维度是否正确
if feature.shape[1] != expected_dim:
raise ValueError(f"特征维度不匹配:预期 {expected_dim},实际 {feature.shape[1]}")
# 使用自动获取的形状重塑特征
new_shape = (batch_size,) + self.output_shape
print(f"[Debug] 调整特征形状: {feature.shape} -> {new_shape}")
return feature.view(new_shape)
def predict(self, feature):
"""使用给定的特征向量进行预测"""
print(f"\n[Debug] 开始预测,输入特征形状: {feature.shape}")
# 检查输入维度
if feature.shape[1] != self.feature_dim:
raise ValueError(f"特征维度不匹配:预期 {self.feature_dim},实际 {feature.shape[1]}")
# 将特征转移到正确的设备并重塑
feature = feature.to(self.device)
self.inject_feature = self.reshape_feature(feature)
# 使用虚拟输入进行预测
dummy_input = torch.zeros(feature.shape[0], 3, 32, 32).to(self.device)
# 进行前向传播(钩子会自动在目标层注入特征)
with torch.no_grad():
output = self.model(dummy_input)
# 清除注入的特征
self.inject_feature = None
return output
def predict_feature(
model: Type[nn.Module],
weight_path: str,
layer_info_path: str,
feature: Union[torch.Tensor, np.ndarray],
device: Optional[str] = None
) -> torch.Tensor:
"""
使用预训练模型预测特征向量的类别。
Args:
model: PyTorch模型类(不是实例)
weight_path: 模型权重文件路径
layer_info_path: 层信息配置文件路径
feature: 输入特征向量,可以是torch.Tensor或numpy.ndarray
device: 运行设备,可选 'cuda' 或 'cpu'。如果为None,将自动选择。
Returns:
torch.Tensor: 模型输出的预测结果
Raises:
ValueError: 如果输入特征维度不正确
FileNotFoundError: 如果权重文件或层信息文件不存在
RuntimeError: 如果模型加载或预测过程出错
"""
try:
# 检查文件是否存在
if not os.path.exists(weight_path):
raise FileNotFoundError(f"权重文件不存在: {weight_path}")
if not os.path.exists(layer_info_path):
raise FileNotFoundError(f"层信息文件不存在: {layer_info_path}")
# 确定设备
if device is None:
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# 转换输入特征为torch.Tensor
if isinstance(feature, np.ndarray):
feature = torch.from_numpy(feature).float()
elif not isinstance(feature, torch.Tensor):
raise ValueError("输入特征必须是numpy数组或torch张量")
# 创建预测器实例
predictor = FeaturePredictor(
model_class=model,
model_weights_path=weight_path,
layer_info_path=layer_info_path,
device=device
)
# 进行预测
with torch.no_grad():
output = predictor.predict(feature)
return output
except Exception as e:
raise RuntimeError(f"预测过程出错: {str(e)}")
def test_predictor():
"""测试特征预测器的功能"""
from AlexNet.code.model import AlexNet
import os
import numpy as np
# 创建预测器实例
predictor = FeaturePredictor(
model_class=AlexNet,
model_weights_path='AlexNet/model/0/epoch_195/subject_model.pth',
layer_info_path='AlexNet/code/layer_info.json'
)
print("\n开始单点测试...")
# 生成一个测试点,使用较大的尺度以增加特征的差异性
feature = torch.randn(1, predictor.feature_dim) * 10.0
output = predictor.predict(feature)
probs = output.softmax(dim=1)
print("\n结果:",output)
# 显示最终预测结果
print("\n最终预测结果:")
top_k = torch.topk(probs[0], k=3)
for idx, (class_idx, prob) in enumerate(zip(top_k.indices.tolist(), top_k.values.tolist())):
print(f"Top-{idx+1}: 类别 {class_idx}, 概率 {prob:.4f}")
def test_predictor_from_train_data():
"""测试特征预测器的批量预测功能"""
from AlexNet.code.model import AlexNet
import numpy as np
import torch
print("\n开始处理训练数据集...")
# 创建预测器实例
predictor = FeaturePredictor(
model_class=AlexNet,
model_weights_path='AlexNet/model/0/epoch_195/subject_model.pth',
layer_info_path='AlexNet/code/layer_info.json'
)
# 加载训练数据
print("\n加载训练数据...")
features = np.load('AlexNet/model/0/epoch_195/train_data.npy')
print(f"数据形状: {features.shape}")
# 转换为tensor
features = torch.from_numpy(features).float()
# 批量处理
batch_size = 100
num_samples = len(features)
num_batches = (num_samples + batch_size - 1) // batch_size
# 用于统计结果
all_predictions = []
class_counts = {}
print("\n开始批量预测...")
with torch.no_grad():
for i in range(num_batches):
start_idx = i * batch_size
end_idx = min((i + 1) * batch_size, num_samples)
batch_features = features[start_idx:end_idx]
# 使用预测器进行预测
outputs = predictor.predict(batch_features)
predictions = outputs.argmax(dim=1).cpu().numpy()
# 更新统计信息
for pred in predictions:
class_counts[int(pred)] = class_counts.get(int(pred), 0) + 1
all_predictions.extend(predictions)
# 打印进度和当前批次的预测分布
if (i + 1) % 10 == 0:
print(f"\n已处理: {end_idx}/{num_samples} 个样本")
batch_unique, batch_counts = np.unique(predictions, return_counts=True)
print("当前批次预测分布:")
for class_idx, count in zip(batch_unique, batch_counts):
print(f"类别 {class_idx}: {count} 个样本 ({count/len(predictions)*100:.2f}%)")
# 打印总体统计结果
print("\n最终预测结果统计:")
total_samples = len(all_predictions)
for class_idx in sorted(class_counts.keys()):
count = class_counts[class_idx]
percentage = (count / total_samples) * 100
print(f"类别 {class_idx}: {count} 个样本 ({percentage:.2f}%)")
def test_train_data():
"""测试训练数据集的预测结果分布"""
from AlexNet.code.model import AlexNet
import numpy as np
import torch
import torch.nn.functional as F
print("\n开始处理训练数据集...")
# 初始化模型
device = 'cuda' if torch.cuda.is_available() else 'cpu'
model = AlexNet().to(device)
model.load_state_dict(torch.load('AlexNet/model/0/epoch_195/subject_model.pth',
map_location=device, weights_only=True))
model.eval()
# 加载训练数据
print("加载训练数据...")
features = np.load('AlexNet/model/0/epoch_195/train_data.npy')
print(f"数据形状: {features.shape}")
# 转换为tensor
features = torch.from_numpy(features).float().to(device)
# 批量处理
batch_size = 100
num_samples = len(features)
num_batches = (num_samples + batch_size - 1) // batch_size
# 用于统计结果
all_predictions = []
class_counts = {}
print("\n开始批量预测...")
with torch.no_grad():
for i in range(num_batches):
start_idx = i * batch_size
end_idx = min((i + 1) * batch_size, num_samples)
batch_features = features[start_idx:end_idx]
# 将特征重塑为[batch_size, 16, 8, 8]
reshaped_features = batch_features.view(-1, 16, 8, 8)
# 使用模型的predict函数
outputs = model.predict(reshaped_features)
predictions = outputs.argmax(dim=1).cpu().numpy()
# 更新统计信息
for pred in predictions:
class_counts[int(pred)] = class_counts.get(int(pred), 0) + 1
all_predictions.extend(predictions)
# 打印进度
if (i + 1) % 10 == 0:
print(f"已处理: {end_idx}/{num_samples} 个样本")
# 打印统计结果
print("\n预测结果统计:")
total_samples = len(all_predictions)
for class_idx in sorted(class_counts.keys()):
count = class_counts[class_idx]
percentage = (count / total_samples) * 100
print(f"类别 {class_idx}: {count} 个样本 ({percentage:.2f}%)")
# 保存详细结果
print("\n保存详细结果...")
results = {
'predictions': all_predictions,
'class_counts': class_counts
}
# np.save('prediction_results.npy', results)
# print("结果已保存到 prediction_results.npy")
if __name__ == "__main__":
test_predictor()
# test_predictor_from_train_data()
# test_train_data() |