修改了验证集正确率问题,之前打印验证集正确率100%,实际测试并不是100%

This commit is contained in:
2025-11-11 14:03:31 +08:00
parent fc594181ed
commit 78cb1d72e1
2 changed files with 21 additions and 7 deletions
+20 -6
View File
@@ -187,8 +187,11 @@ def run_epoch(model, head, loader, criterion, optimizer=None, train: bool = True
model.eval(); head.eval()
running_loss = 0.0
running_acc = 0.0
n_batches = 0
# 改为统计总样本数和正确样本数(全局准确率)
total_samples = 0
correct_samples = 0
with torch.set_grad_enabled(train):
pbar = tqdm(loader, desc='训练中' if train else '验证中')
@@ -202,17 +205,28 @@ def run_epoch(model, head, loader, criterion, optimizer=None, train: bool = True
else:
logits = head(feats) # 不加边距
loss = criterion(logits, labels)
acc = accuracy_top1(logits, labels)
# 统计样本级别的正确数
pred = logits.argmax(dim=1)
correct = (pred == labels).sum().item()
batch_size = labels.size(0)
total_samples += batch_size
correct_samples += correct
running_loss += loss.item()
running_acc += acc
n_batches += 1
# 计算当前的全局准确率
current_acc = 100.0 * correct_samples / total_samples
pbar.set_postfix({
'Loss': f'{running_loss / n_batches:.4f}',
'Acc': f'{running_acc / n_batches:.2f}%'
'Acc': f'{current_acc:.2f}%'
})
return running_loss / max(n_batches, 1), running_acc / max(n_batches, 1)
avg_loss = running_loss / max(n_batches, 1)
global_acc = 100.0 * correct_samples / max(total_samples, 1)
return avg_loss, global_acc
def collect_max_cos_scores(model, head, loader) -> torch.Tensor: