File size: 2,914 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
from AlexNet.code.model import AlexNet
import torch
import numpy as np
from feature_predictor import predict_feature

def test_single_feature():
    """测试单个特征向量的预测"""
    print("\n开始单特征测试...")
    
    # 生成测试特征
    feature_dim = 1024  # 特征维度
    feature = torch.randn(1, feature_dim) * 10.0  # 使用较大的尺度
    
    # 使用predict_feature函数进行预测
    output = predict_feature(
        model=AlexNet,
        weight_path='AlexNet/model/0/epoch_195/subject_model.pth',
        layer_info_path='AlexNet/code/layer_info.json',
        feature=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_train_data():
    """测试训练数据集的预测"""
    print("\n开始训练数据测试...")
    
    # 加载训练数据
    print("加载训练数据...")
    features = np.load('AlexNet/model/0/epoch_195/train_data.npy')
    print(f"数据形状: {features.shape}")
    
    # 批量处理
    batch_size = 100
    num_samples = len(features)
    num_batches = (num_samples + batch_size - 1) // batch_size
    
    # 用于统计结果
    all_predictions = []
    class_counts = {}
    
    print("\n开始批量预测...")
    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]
        
        # 使用predict_feature函数进行预测
        outputs = predict_feature(
            model=AlexNet,
            weight_path='AlexNet/model/0/epoch_195/subject_model.pth',
            layer_info_path='AlexNet/code/layer_info.json',
            feature=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}%)")
     

if __name__ == "__main__":
    # 测试单个特征
    test_single_feature()
    # 测试训练数据
    # test_train_data()