-
Notifications
You must be signed in to change notification settings - Fork 0
/
val_multi-head.py
171 lines (159 loc) · 7.48 KB
/
val_multi-head.py
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
from time import sleep
import os
import sys
import matplotlib.pyplot as plt
import torch
import torchvision
from torchvision import transforms
from torch.utils.data import DataLoader
from tqdm import tqdm
from DataLoaders.LoadPartASCAD import Datasetloader
from config import *
def val():
test_loader, _ = Datasetloader(test_data_path)(bs, is_shuffle, dataset_mode, left, right)
# 加载模型
if (saveModel == False):
if (save_weight == True):
if (net_structure == 'cs3'):
from Nets.cnn_single_head_3layer import CNNNet
model = CNNNet().to(device)
model.load_state_dict(torch.load(modelsaveName, map_location=device))
elif (net_structure == 'resnet18'):
from Nets.Resnet import ResNet_18
model = ResNet_18().to(device)
model.load_state_dict(torch.load(modelsaveName, map_location=device))
elif (net_structure == 'cs4'):
from Nets.cnn_single_head import CNNNet
model = CNNNet().to(device)
model.load_state_dict(torch.load(modelsaveName, map_location=device))
elif (net_structure == 'ms5'):
from Nets.mlp_5layer import MLPNet
model = MLPNet().to(device)
model.load_state_dict(torch.load(modelsaveName, map_location=device))
if (net_structure == 'cm3'):
from Nets.cnn_multi_head import CNNNet
model = CNNNet().to(device)
model.load_state_dict(torch.load(modelsaveName, map_location=device))
if (net_structure == 'mm5'):
from Nets.mlp_mutil_head_5layer import MLPNet
model = MLPNet().to(device)
model.load_state_dict(torch.load(modelsaveName, map_location=device))
if (net_structure == 'mm7'):
from Nets.mlp_mutil_head_7layer import MLPNet
model = MLPNet().to(device)
model.load_state_dict(torch.load(modelsaveName, map_location=device))
if (net_structure == 'cmp3'):
from Nets.cnn_mutil_head_pca import CNNNet
model = CNNNet().to(device)
model.load_state_dict(torch.load(modelsaveName, map_location=device))
else:
model = torch.load(modelsaveName, map_location=device)
model.eval()
model = model.to(device)
acc_num_sub_heads = []
# 随着曲线增加的准确率
for i in range(num_sub_heads):
if (i != chosen_head):
continue
correct = 0
total = 0
acc_traces = []
t_total = 0
t_correct = 0
with torch.no_grad():
for data in tqdm(test_loader):
images, images2, labels = data
images, images2, labels = images.to(device), images2.to(device), labels.to(device)
outputs = model(images)
# 交换输出顺序
for i_bs, output in enumerate(outputs[i]):
output_temp = output.clone()
for j in range(len(output_order)):
outputs[i][i_bs][j] = output_temp[output_order[j]]
# 对输出进行阈值筛选,计算准确率
threshold_true_index = []
for bs_i, bs_data in enumerate(outputs[i]):
if (bs_data[0] > threshold or bs_data[1] > threshold):
threshold_true_index.append(bs_i)
_, predicted = torch.max(outputs[i].data, 1)
for p_i, p_data in enumerate(predicted):
if (p_i in threshold_true_index):
t_total += 1
if (p_data == labels[p_i]):
t_correct += 1
total += labels.size(0)
correct += (predicted == labels).sum().item()
acc_traces.append(correct / total)
acc_num_sub_heads.append(acc_traces)
accuracy = correct / total
if (t_total != 0):
threshold_accuracy = t_correct / t_total
else:
threshold_accuracy = 0
print(f"正确个数:{correct}/{total} {i}头测试总准确率: {accuracy * 100:.2f}%")
print(f"正确个数:{t_correct}/{t_total} {i}头测试阈值准确率: {threshold_accuracy * 100:.2f}%")
# 绘制acc-traces曲线
# for i in range(num_sub_heads):
# plt.plot(acc_num_sub_heads[i], label=f"{i} head")
# plt.xlabel("Traces")
# plt.ylabel("Accuracy")
# plt.legend()
# plt.show()
print()
else:
m = os.listdir(saveModelPath)
model_file = ["model_" + str(i) + ".pth" for i in range(0, len(m))]
max_accuracy = 0.0
max_model = ""
accuracy_all = []
for file in model_file:
model = torch.load(saveModelPath + file, map_location=device)
model.eval()
model = model.to(device)
acc_epoch = []
for i in range(num_sub_heads):
correct = 0
total = 0
t_correct = 0
t_total = 0
with torch.no_grad():
for data in tqdm(test_loader):
images, _, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
# 交换输出顺序
for i_bs, output in enumerate(outputs[i]):
output_temp = output.clone()
for j in range(len(output_order)):
outputs[i][i_bs][j] = output_temp[output_order[j]]
# 对输出进行阈值筛选,计算准确率
threshold_true_index = []
for bs_i, bs_data in enumerate(outputs[i]):
if (bs_data[0] > threshold or bs_data[1] > threshold):
threshold_true_index.append(bs_i)
_, predicted = torch.max(outputs[i].data, 1)
for p_i, p_data in enumerate(predicted):
if (p_i in threshold_true_index):
t_total += 1
if (p_data == labels[p_i]):
t_correct += 1
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = correct / total
threshold_accuracy = t_correct / t_total
acc_epoch.append(accuracy)
if (accuracy > max_accuracy):
max_accuracy = accuracy
max_model = file
print(f"{file} {i}头测试准确率: {accuracy * 100:.2f}%")
print(f"{file} {i}头测试阈值准确率: {threshold_accuracy * 100:.2f}%")
accuracy_all.append(acc_epoch)
print()
# 将每个epoch的准确率保存到文件
with open(accSavePath, "w") as f:
for acc_epochs in accuracy_all:
for acc in acc_epochs:
f.write(str(acc) + " ")
f.write("\n")
print(f"最高准确率模型: {max_model} 准确率: {max_accuracy * 100:.2f}%")
val()