修改了验证集正确率问题,之前打印验证集正确率100%,实际测试并不是100%
This commit is contained in:
@@ -499,7 +499,7 @@ def main():
|
||||
# MODEL_PATH = "../model/ProcessedIngredientRecognition/embedding_20251103_172012/best_embedding_model.pth"
|
||||
# MODEL_PATH = "../model/WholeIngredientRecognition/cosface_20251106_134718/best_cosface_model.pth"
|
||||
# MODEL_PATH = "../model/DishClassification/cosface_20251105_200551/best_embedding_model.pth"
|
||||
MODEL_PATH = "../model/DishClassification/cosface_20251110_144822/best_cosface_model.pth"
|
||||
MODEL_PATH = "../model/DishClassification/cosface_20251111_094827/best_cosface_model.pth"
|
||||
# TRAIN_DIR = "../dataset/ProcessedIngredientRecognition/train"
|
||||
# TRAIN_DIR = "../dataset/WholeIngredientRecognition/train"
|
||||
TRAIN_DIR = "../dataset/DishClassification/train"
|
||||
|
||||
@@ -187,9 +187,12 @@ 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 '验证中')
|
||||
for images, labels in pbar:
|
||||
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user