mtpnet_image_models / ttv_utils /feature_predictor.py
RRFRRF's picture
修改钩子机制 修改训练文件保存格式
d5dac94
"""
特征预测器模块
该模块使用钩子机制从模型的中间层特征向量预测分类结果
"""
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()