| | """ |
| | 特征预测器模块 |
| | |
| | 该模块使用钩子机制从模型的中间层特征向量预测分类结果 |
| | """ |
| |
|
| | 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:] |
| | 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' |
| |
|
| | |
| | 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}") |
| | |
| | |
| | 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}") |
| | |
| | |
| | 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] |
| | |
| | |
| | reshaped_features = batch_features.view(-1, 16, 8, 8) |
| | |
| | |
| | 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 |
| | } |
| | |
| | |
| |
|
| |
|
| |
|
| | if __name__ == "__main__": |
| | test_predictor() |
| | |
| | |