cross_val_predict评分审查:折外预测合并后,为什么不等于逐折分数平均

10-10 5阅读

cross_val_predict评分审查:折外预测合并后,为什么不等于逐折分数平均

配图为独立模型生成概念示意,折大小仅作结构说明,不对应下方具体测试编号。

AI把交叉验证脚本改成“先拿到全部折外预测,再算一次指标”,看起来只是代码简化,结果却可能变化。原因不一定是数据泄漏:折大小不同会改变样本权重,F1这类非线性指标还会受到聚合顺序影响。审查时应把这两层机制分开。

两个接口返回的东西不同

cross_val_score返回每个验证折的评分数组,简单平均是调用方再执行的操作。cross_val_predict则把每个样本的折外预测放回原位置;每个样本须恰好属于一个测试折。

官方文档特别提醒,合并预测后评分可能不同于逐折评估,除非测试折等大且指标可按样本分解。这里的可分解,是指能把分数写成独立样本贡献的平均值。准确率满足这个结构:每个样本贡献一次命中或未命中。

要核对两条路径,还必须保证划分、模型参数及随机状态一致。如果两次调用重新随机分折或重新随机训练,预测本身就可能不同,不能把所有差异都归咎于汇总公式。下面复用同一份划分和确定性基线,专门隔离聚合问题。

不等长折:准确率需要按人数加权

八个样本中有三个正例,模型始终预测正类。第一折有两个样本,全部预测正确;第二折有六个样本,只预测正确一个。逐折准确率是1和1/6,简单均值为7/12,约0.583333。

但合并八个样本后总共只命中三个,准确率为3/8。按测试折大小计算(2×1+6×1/6)/8,也得到3/8。简单平均让小折中的单个样本获得了更大权重,因此两种数字并不相等。

F1:按折大小加权仍不够

二分类正类F1为2TP/(2TP+FP+FN)。本例两折的F1分别为1和2/7,简单均值是9/14;按样本数加权得到13/28。合并后TP=3、FP=5、FN=0,F1却是6/11。

这里应先合并混淆计数,再做除法。各折分母由真实标签和预测共同决定,不等于折样本数;平均已经算好的比值,通常无法恢复合并后的比值。因此“把折大小当权重”只能解决第一层问题,不能作为所有指标的通用修补。

完整可运行例子

代码锁定scikit-learn 1.8.0和NumPy 2.3.5,保存为test.py即可运行,安装命令见首行。使用DummyClassifier固定预测为1,目的只是验证评分机制。

"""Reproduce with: pip install scikit-learn==1.8.0 numpy==2.3.5"""
from fractions import Fraction as F
import numpy as np
import sklearn
from sklearn.dummy import DummyClassifier
from sklearn.metrics import accuracy_score, f1_score, make_scorer
from sklearn.model_selection import (cross_val_predict, cross_val_score,
                                     RepeatedKFold, TimeSeriesSplit)

assert sklearn.__version__ == "1.8.0", "This audit pins scikit-learn 1.8.0"
X = np.arange(8).reshape(-1, 1)
y = np.array([1, 1, 0, 0, 1, 0, 0, 0])
model = DummyClassifier(strategy="constant", constant=1)
f1_scorer = make_scorer(f1_score, zero_division=0)


def make_splits(test_parts):
    all_rows = np.arange(len(y))
    return [(np.setdiff1d(all_rows, test), np.asarray(test))
            for test in test_parts]


def evaluate(name, splits):
    # Reuse exactly the same splits and deterministic model for all calls.
    oof = cross_val_predict(model, X, y, cv=splits, method="predict")
    fold_accuracy = cross_val_score(model, X, y, cv=splits, scoring="accuracy")
    fold_f1 = cross_val_score(model, X, y, cv=splits, scoring=f1_scorer)
    sizes = np.array([len(test) for _, test in splits])
    assert np.array_equal(np.sort(np.concatenate([t for _, t in splits])),
                          np.arange(len(y)))
    assert np.all(oof == 1)

    pooled_accuracy = accuracy_score(y, oof)
    pooled_f1 = f1_score(y, oof)
    weighted_accuracy = np.average(fold_accuracy, weights=sizes)
    weighted_f1 = np.average(fold_f1, weights=sizes)
    counts = []
    for i, (_, test) in enumerate(splits):
        truth, pred = y[test], oof[test]
        tp = int(np.sum((truth == 1) & (pred == 1)))
        fp = int(np.sum((truth == 0) & (pred == 1)))
        fn = int(np.sum((truth == 1) & (pred == 0)))
        counts.append((tp, fp, fn))
        assert np.isclose(fold_f1[i], 2 * tp / (2 * tp + fp + fn))
    tp, fp, fn = np.sum(counts, axis=0)
    count_f1 = F(2 * int(tp), int(2 * tp + fp + fn))
    assert np.isclose(pooled_accuracy, weighted_accuracy)
    assert count_f1 == F(6, 11)
    assert np.isclose(pooled_f1, float(count_f1))
    assert not np.isclose(pooled_f1, weighted_f1)
    if name == "unequal_folds":
        assert np.allclose(fold_accuracy, [1, 1 / 6])
        assert np.isclose(fold_accuracy.mean(), float(F(7, 12)))
        assert np.isclose(fold_f1.mean(), float(F(9, 14)))
        assert np.isclose(weighted_f1, float(F(13, 28)))
    else:
        assert np.isclose(fold_accuracy.mean(), pooled_accuracy)
        assert np.isclose(fold_f1.mean(), float(F(8, 15)))
        assert not np.isclose(fold_f1.mean(), pooled_f1)

    print(f"\n{name}: test_sizes={sizes.tolist()}")
    print("fold_accuracy=", np.round(fold_accuracy, 6).tolist())
    print(f"accuracy: fold_mean={fold_accuracy.mean():.6f}, "
          f"size_weighted={weighted_accuracy:.6f}, pooled={pooled_accuracy:.6f}")
    print("fold_F1=", np.round(fold_f1, 6).tolist())
    print(f"F1: fold_mean={fold_f1.mean():.6f}, "
          f"size_weighted={weighted_f1:.6f}, pooled={pooled_f1:.6f}")
    print(f"pooled_counts: TP={tp}, FP={fp}, FN={fn}, exact_F1={count_f1}")


print(f"NumPy={np.__version__}, scikit-learn={sklearn.__version__}")
evaluate("unequal_folds", make_splits([np.arange(2), np.arange(2, 8)]))
evaluate("equal_folds", make_splits([np.arange(4), np.arange(4, 8)]))
for unsupported_cv in [RepeatedKFold(n_splits=2, n_repeats=2, random_state=0),
                       TimeSeriesSplit(n_splits=2)]:
    try:
        cross_val_predict(model, X, y, cv=unsupported_cv)
    except ValueError as exc:
        assert "partitions" in str(exc)
    else:
        raise AssertionError("A non-partition splitter was unexpectedly accepted")
print("\nOOF partition, fold-size weighting and nonlinear F1 checks: PASS")

实际输出

NumPy=2.3.5, scikit-learn=1.8.0

unequal_folds: test_sizes=[2, 6]
fold_accuracy= [1.0, 0.166667]
accuracy: fold_mean=0.583333, size_weighted=0.375000, pooled=0.375000
fold_F1= [1.0, 0.285714]
F1: fold_mean=0.642857, size_weighted=0.464286, pooled=0.545455
pooled_counts: TP=3, FP=5, FN=0, exact_F1=6/11

equal_folds: test_sizes=[4, 4]
fold_accuracy= [0.5, 0.25]
accuracy: fold_mean=0.375000, size_weighted=0.375000, pooled=0.375000
fold_F1= [0.666667, 0.4]
F1: fold_mean=0.533333, size_weighted=0.533333, pooled=0.545455
pooled_counts: TP=3, FP=5, FN=0, exact_F1=6/11

OOF partition, fold-size weighting and nonlinear F1 checks: PASS

第二轮改成两个四样本折,准确率的均值与合并值完全一致;F1的均值仍为8/15,而合并值仍为6/11。这个对照排除了折大小差异,直接展示F1非线性带来的影响。全部F1分母都为正,差异也不是未定义值的补救规则造成的。

报告时保留汇总口径

应提前确定是逐折等权平均、按样本数加权,还是合并折外预测后评分,并明确正类、指标平均方式及异常处理规则。最好同时保留每折人数、逐折成绩和必要的混淆计数,不要因为某种汇总得到更高分就临时换口径。

折外预测来自多个分别训练的模型,不是最终模型在独立测试集上的一次预测。即使某个指标能够精确按样本分解,也不能据此宣称它已经等同于最终部署性能;预处理、调参和数据分组仍须遵守验证边界。

此外,重复交叉验证会让样本多次进入测试折,常见时间序列切分又可能让前部样本从未进入测试折,这些划分不能原样塞进要求单次完整分区的cross_val_predict。需要按所选验证设计显式收集预测,再说明重复样本和覆盖范围如何处理。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。