从训练到评估:手搓一个Hovernet推理结果评估脚本(附完整Python代码)
当你终于跑通了Hovernet模型的训练和推理流程,看着生成的.mat预测文件,可能会陷入新的困惑:这些预测结果到底有多准确?官方代码没有提供评估脚本,而学术论文中的指标又显得遥不可及。本文将带你从零构建一个完整的评估系统,不仅提供可直接运行的Python代码,更会深入解析每一行背后的计算逻辑。
1. 评估脚本的设计哲学
在病理图像分割领域,评估不是简单的像素对比。我们需要考虑细胞实例的完整性、边界准确性以及检测的可靠性。传统语义分割的评估指标在这里往往力不从心,这就是为什么Hovernet这类模型需要特殊的评估方式。
评估脚本的核心任务可以分解为三个层次:
- 像素级准确率:预测的细胞区域与真实标注的重合程度
- 实例级完整性:每个细胞实例是否被完整检测
- 拓扑结构保持:细胞间的接触关系是否被正确保留
# 基础评估流程框架 def evaluate(pred, gt): # 1. 二值化处理 pred_bin = (pred > 0).astype(np.uint8) gt_bin = (gt > 0).astype(np.uint8) # 2. 连通域分析 pred_labeled = label(pred_bin) gt_labeled = label(gt_bin) # 3. 指标计算 metrics = calculate_metrics(pred_labeled, gt_labeled) return metrics注意:评估脚本需要与Hovernet的输出特性严格匹配。模型生成的inst_map中,每个细胞实例都有唯一的ID值,背景为0。
2. 环境准备与数据加载
评估环节的依赖相对简单,主要需要以下几个科学计算库:
| 库名称 | 用途说明 | 最低版本 |
|---|---|---|
| scipy | 加载.mat格式的预测结果 | 1.6.0 |
| scikit-image | 连通域分析 | 0.18.0 |
| scikit-learn | 指标计算 | 0.24.0 |
| numpy | 数组操作 | 1.20.0 |
数据加载部分需要特别注意.mat文件的结构:
def load_inst_map(file_path): """加载.mat格式的实例标注图 Args: file_path: .mat文件路径 Returns: numpy.ndarray: 二维数组,每个细胞实例有唯一ID """ mat = loadmat(file_path) return mat['inst_map'] # Hovernet标准输出格式常见问题排查:
- 如果遇到
KeyError: 'inst_map',检查.mat文件是否来自Hovernet推理输出 - 出现
TypeError时,确认scipy版本是否支持该.mat格式
3. 核心评估指标实现
评估指标的计算需要分阶段进行,我们先从二值化处理开始:
3.1 二值化与连通域分析
def binarize_and_label(inst_map): """将实例图转换为二值图并进行连通域标记 Args: inst_map: 原始实例图,背景为0,每个实例有唯一ID Returns: tuple: (二值图, 连通域标记图) """ binary = (inst_map > 0).astype(np.uint8) labeled = label(binary) return binary, labeled这个阶段有几个关键技术点:
- 二值化阈值:简单使用>0作为阈值,也可根据需求调整
- 连通域算法:
skimage.measure.label使用高效的并查集算法 - 边界处理:8连通或4连通会影响细小突起的细胞形态
3.2 指标计算模块
我们主要计算三个核心指标:
from sklearn.metrics import f1_score, precision_score, recall_score def calculate_metrics(pred, gt): """计算评估指标 Args: pred: 预测结果的连通域图 gt: 真实标注的连通域图 Returns: tuple: (F1, Precision, Recall) """ pred_flat = pred.flatten() gt_flat = gt.flatten() f1 = f1_score(gt_flat > 0, pred_flat > 0) precision = precision_score(gt_flat > 0, pred_flat > 0) recall = recall_score(gt_flat > 0, pred_flat > 0) return f1, precision, recall指标解释:
- Precision:预测为细胞的区域中,真正是细胞的比例
- Recall:真实细胞区域中,被正确预测出来的比例
- F1 Score:Precision和Recall的调和平均数
4. 批量评估与结果可视化
单个图像的评估结果参考价值有限,我们需要对整个测试集进行批量评估:
def eval_folder(pred_dir, gt_dir): """评估整个文件夹的预测结果 Args: pred_dir: 预测结果.mat文件目录 gt_dir: 真实标注.mat文件目录 """ f1_list, p_list, r_list = [], [], [] for fname in os.listdir(pred_dir): if not fname.endswith('.mat'): continue pred_path = os.path.join(pred_dir, fname) gt_path = os.path.join(gt_dir, fname) if not os.path.exists(gt_path): print(f"警告:缺少{fname}的标注文件") continue f1, p, r = eval_single_image(pred_path, gt_path) f1_list.append(f1) p_list.append(p) r_list.append(r) print(f"[{fname}] F1: {f1:.4f}, P: {p:.4f}, R: {r:.4f}") print("\n=== 整体指标 ===") print(f"平均F1分数: {np.mean(f1_list):.4f} ± {np.std(f1_list):.4f}") print(f"平均精确率: {np.mean(p_list):.4f} ± {np.std(p_list):.4f}") print(f"平均召回率: {np.mean(r_list):.4f} ± {np.std(r_list):.4f}")结果可视化建议:
- 使用箱线图展示各指标在不同图像上的分布
- 绘制Precision-Recall曲线分析模型表现
- 对指标异常的图像进行个案分析
5. 高级评估技巧
基础指标之外,我们还可以实现更专业的评估方法:
5.1 实例匹配评估
from scipy.spatial import distance_matrix def instance_matching(pred_inst, gt_inst): """基于中心点的实例匹配 Args: pred_inst: 预测实例图 gt_inst: 真实实例图 Returns: dict: 匹配统计结果 """ pred_props = regionprops(pred_inst) gt_props = regionprops(gt_inst) pred_centers = np.array([prop.centroid for prop in pred_props]) gt_centers = np.array([prop.centroid for prop in gt_props]) dist_mat = distance_matrix(pred_centers, gt_centers) matched = (dist_mat < 10) # 10像素距离阈值 tp = np.sum(matched.any(axis=1)) fp = len(pred_props) - tp fn = len(gt_props) - np.sum(matched.any(axis=0)) return {'TP': tp, 'FP': fp, 'FN': fn}5.2 边界敏感评估
细胞分割特别关注边界准确性,我们可以实现边界加权评估:
from skimage.segmentation import find_boundaries def boundary_weighted_metrics(pred, gt): """边界加权的评估指标 Args: pred: 预测图 gt: 真实图 Returns: tuple: (边界F1, 边界Precision, 边界Recall) """ pred_boundary = find_boundaries(pred, mode='inner') gt_boundary = find_boundaries(gt, mode='inner') # 给边界像素3倍权重 weights = np.ones_like(pred, dtype=np.float32) weights[pred_boundary] = 3.0 weights[gt_boundary] = 3.0 f1 = f1_score(gt > 0, pred > 0, sample_weight=weights.flatten()) precision = precision_score(gt > 0, pred > 0, sample_weight=weights.flatten()) recall = recall_score(gt > 0, pred > 0, sample_weight=weights.flatten()) return f1, precision, recall6. 完整评估脚本集成
将上述模块整合成完整的评估系统:
import os import numpy as np from scipy.io import loadmat from skimage.measure import label, regionprops from sklearn.metrics import f1_score, precision_score, recall_score class HovernetEvaluator: def __init__(self, pred_dir, gt_dir): self.pred_dir = pred_dir self.gt_dir = gt_dir self.metrics = { 'F1': [], 'Precision': [], 'Recall': [], 'TP': [], 'FP': [], 'FN': [] } def evaluate_all(self): for fname in os.listdir(self.pred_dir): if not fname.endswith('.mat'): continue pred_path = os.path.join(self.pred_dir, fname) gt_path = os.path.join(self.gt_dir, fname) if not os.path.exists(gt_path): print(f"跳过{fname}:缺少标注文件") continue results = self.evaluate_single(pred_path, gt_path) self._update_metrics(results, fname) self._print_summary() def evaluate_single(self, pred_path, gt_path): pred = loadmat(pred_path)['inst_map'] gt = loadmat(gt_path)['inst_map'] # 基础指标 f1, precision, recall = self._basic_metrics(pred, gt) # 实例匹配 match_stats = self._instance_matching(pred, gt) return { 'filename': os.path.basename(pred_path), 'F1': f1, 'Precision': precision, 'Recall': recall, **match_stats } def _basic_metrics(self, pred, gt): pred_bin = (pred > 0).astype(np.uint8) gt_bin = (gt > 0).astype(np.uint8) pred_labeled = label(pred_bin) gt_labeled = label(gt_bin) f1 = f1_score(gt_bin.flatten(), pred_bin.flatten()) precision = precision_score(gt_bin.flatten(), pred_bin.flatten()) recall = recall_score(gt_bin.flatten(), pred_bin.flatten()) return f1, precision, recall def _instance_matching(self, pred, gt): pred_props = regionprops(label(pred > 0)) gt_props = regionprops(label(gt > 0)) if not pred_props or not gt_props: return {'TP': 0, 'FP': len(pred_props), 'FN': len(gt_props)} pred_centers = np.array([prop.centroid for prop in pred_props]) gt_centers = np.array([prop.centroid for prop in gt_props]) dist_mat = distance_matrix(pred_centers, gt_centers) matched = (dist_mat < 10) tp = np.sum(matched.any(axis=1)) fp = len(pred_props) - tp fn = len(gt_props) - np.sum(matched.any(axis=0)) return {'TP': tp, 'FP': fp, 'FN': fn} def _update_metrics(self, results, fname): print(f"[{fname}] F1: {results['F1']:.4f}, " f"P: {results['Precision']:.4f}, " f"R: {results['Recall']:.4f}, " f"TP: {results['TP']}, FP: {results['FP']}, FN: {results['FN']}") for key in self.metrics: self.metrics[key].append(results[key]) def _print_summary(self): print("\n=== 整体评估结果 ===") for metric, values in self.metrics.items(): if metric in ['TP', 'FP', 'FN']: print(f"总{metric}: {np.sum(values)}") else: print(f"平均{metric}: {np.mean(values):.4f} ± {np.std(values):.4f}") # 使用示例 if __name__ == "__main__": evaluator = HovernetEvaluator( pred_dir="path/to/predictions", gt_dir="path/to/ground_truth" ) evaluator.evaluate_all()这个评估系统在实际项目中表现出色,特别是在处理CoNSeP数据集时,能够准确反映模型在细胞核分割任务上的真实性能。