feat(finetune): 新增逐类别评估指标打印与配置项

- 在微调配置文件中新增class_names配置项以指定各分类名称
- 新增print_per_class_metrics函数用于计算并输出逐类别评估指标
- 调整validate函数返回验证/测试集的标签与概率数据
- 在训练主循环中添加验证和测试阶段的逐类别指标打印逻辑
This commit is contained in:
yilv committed 2026-05-29 16:14:54 +08:00
1 parent 096c9c6547
commit b52f1e4c61
2 files changed
+91 -11

No files matched your search

+10
View File
@@ -47,6 +47,16 @@ data:
signal_len: 1000
num_classes: 7
# ===== 类别名称 (用于显示每个类的详细指标) =====
class_names:
- "高血压"
- "高血糖"
- "高血脂"
- "冠心病"
- "心律失常"
- "糖尿病"
- "颈动脉斑块"
# ===== DataLoader =====
num_workers: 4
pin_memory: true
+81 -11
View File
@@ -174,6 +174,62 @@ class MultiLabelFocalLoss(nn.Module):
return loss
def print_per_class_metrics(all_labels_np, all_probs_np, auc_list, class_names, thresholds=None):
"""打印每个类别的详细统计信息和单独的 AUC"""
num_classes = all_labels_np.shape[1]
if class_names is None:
class_names = [f"Class_{i}" for i in range(num_classes)]
max_name_len = max(len(name) for name in class_names)
max_name_len = max(max_name_len, 6)
header = f"{'类别':<{max_name_len}} {'正样本':>6} {'负样本':>6} {'正样本率':>8} {'AUC':>8}"
if thresholds is not None:
header += f" {'阈值':>6}"
header += f" {'Precision':>10} {'Recall':>10} {'F0.5':>8}"
print("-" * len(header))
print(header)
print("-" * len(header))
class_details = []
for i in range(num_classes):
y_true = all_labels_np[:, i]
y_prob = all_probs_np[:, i]
pos_count = int(y_true.sum())
neg_count = len(y_true) - pos_count
pos_ratio = pos_count / len(y_true) * 100
auc_val = auc_list[i]
th = thresholds[i] if thresholds is not None else 0.5
y_pred = (y_prob >= th).astype(int)
tp = int(((y_pred == 1) & (y_true == 1)).sum())
fp = int(((y_pred == 1) & (y_true == 0)).sum())
fn = int(((y_pred == 0) & (y_true == 1)).sum())
prec = tp / (tp + fp) if (tp + fp) > 0 else 0.0
rec = tp / (tp + fn) if (tp + fn) > 0 else 0.0
beta = 0.5
f_beta = (1 + beta**2) * prec * rec / (beta**2 * prec + rec) if (prec + rec) > 0 else 0.0
row = f"{class_names[i]:<{max_name_len}} {pos_count:>6d} {neg_count:>6d} {pos_ratio:>7.1f}% {auc_val:>8.4f}"
if thresholds is not None:
row += f" {th:>6.3f}"
row += f" {prec:>10.4f} {rec:>10.4f} {f_beta:>8.4f}"
print(row)
class_details.append({
'name': class_names[i], 'pos': pos_count, 'neg': neg_count,
'auc': auc_val, 'precision': prec, 'recall': rec, 'f0.5': f_beta
})
print("-" * len(header))
macro_auc = np.mean(auc_list)
print(f"{'Macro':<{max_name_len}} {int(all_labels_np.sum()):>6d} {all_labels_np.size - int(all_labels_np.sum()):>6d} {'':>8} {macro_auc:>8.4f}")
print("-" * len(header))
return class_details
# -------------------------------------------------------------------
# 4. 训练与验证逻辑
# -------------------------------------------------------------------
@@ -281,8 +337,8 @@ def validate(model, loader, criterion, device, num_classes, total_len, use_amp=T
if count == 0 or len(local_labels) == 0:
if is_main_process():
return 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "Empty validation loader.", fixed_threshold, []
return 0, 0, 0, 0, 0, 0, None, 0, []
return 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, "Empty validation loader.", fixed_threshold, [], None, None
return 0, 0, 0, 0, 0, 0, None, 0, [], None, None
if isinstance(total_loss, torch.Tensor):
total_loss = total_loss.item()
@@ -350,9 +406,9 @@ def validate(model, loader, criterion, device, num_classes, total_len, use_amp=T
report_str = classification_report(all_labels_np, final_preds, digits=4, zero_division=0)
avg_loss = total_loss / count
return avg_loss, final_acc, precision, recall, final_f1, auroc, report_str, best_threshold, auc_list
return avg_loss, final_acc, precision, recall, final_f1, auroc, report_str, best_threshold, auc_list, all_labels_np, all_probs_np
else:
return 0, 0, 0, 0, 0, 0, None, 0, []
return 0, 0, 0, 0, 0, 0, None, 0, [], None, None
# -------------------------------------------------------------------
@@ -408,6 +464,8 @@ def main():
if is_main_process():
print(f"Validation: {val_mode} | Test: {test_mode}")
class_names = data_cfg.get('class_names', None)
# Datasets
train_ds = DownstreamClassificationDataset(
data_cfg['data_root'], data_cfg['split_file'], mode='train',
@@ -608,7 +666,7 @@ def main():
scheduler=scheduler
)
val_loss, val_acc, val_prec, val_rec, val_f1, val_auc, val_report, best_th, auc_list = validate(
val_loss, val_acc, val_prec, val_rec, val_f1, val_auc, val_report, best_th, auc_list, val_labels_np, val_probs_np = validate(
model, val_loader, criterion, device, data_cfg['num_classes'],
val_dataset_len, use_amp=use_amp,
search_threshold=True, fixed_threshold=0.5,
@@ -618,13 +676,17 @@ def main():
if is_main_process():
logger.info(f"Epoch {epoch + 1}: Train Loss={train_loss:.4f}, "
f"Val Loss={val_loss:.4f}, Val F0.5={val_f1:.4f}, Val AUC={val_auc:.4f}")
print(f"Train Loss: {train_loss:.4f}")
print(f"\nTrain Loss: {train_loss:.4f}")
print(f"Val Loss: {val_loss:.4f}, Acc: {val_acc:.4f}, "
f"Prec: {val_prec:.4f}, Rec: {val_rec:.4f}, F0.5: {val_f1:.4f}, AUC: {val_auc:.4f}")
if isinstance(best_th, np.ndarray):
print(f"Best Thresholds: {np.round(best_th, 3)}")
current_metric = val_auc # 使用 Macro AUC 作为主要指标
if val_labels_np is not None and val_probs_np is not None and auc_list:
print(f"\n{'='*60}")
print(f"Epoch {epoch + 1} Per-Class Metrics:")
print(f"{'='*60}")
print_per_class_metrics(val_labels_np, val_probs_np, auc_list, class_names, thresholds=best_th)
current_metric = val_auc
if current_metric > best_metric:
best_metric = current_metric
best_threshold = best_th
@@ -652,16 +714,24 @@ def main():
if os.path.exists(best_path):
load_checkpoint(best_path, model)
test_loss, test_acc, test_prec, test_rec, test_f1, test_auc, test_report, _, auc_list = validate(
test_loss, test_acc, test_prec, test_rec, test_f1, test_auc, test_report, _, auc_list, test_labels_np, test_probs_np = validate(
model, test_loader, criterion, device, data_cfg['num_classes'],
test_dataset_len, use_amp=use_amp,
search_threshold=False, fixed_threshold=best_threshold,
save_dir=train_cfg['save_dir'], epoch=None
)
print(f"Test Loss: {test_loss:.4f}")
print(f"\nTest Loss: {test_loss:.4f}")
print(f"Test Acc: {test_acc:.4f}, Prec: {test_prec:.4f}, "
f"Rec: {test_rec:.4f}, F0.5: {test_f1:.4f}, AUC: {test_auc:.4f}")
if test_labels_np is not None and test_probs_np is not None and auc_list:
print(f"\n{'='*60}")
print("Test Per-Class Metrics:")
print(f"{'='*60}")
thresholds_to_use = best_threshold if isinstance(best_threshold, np.ndarray) else None
print_per_class_metrics(test_labels_np, test_probs_np, auc_list, class_names, thresholds=thresholds_to_use)
print(f"\nClassification Report:\n{test_report}")
logger.info(f"Final Test: Acc={test_acc:.4f}, F0.5={test_f1:.4f}, AUC={test_auc:.4f}")