你的模型会承认自己不确定吗?保形预测指南

一种实用且不依赖分布假设的方法,让任何模型都能报告自身的不确定性。
作者:Nate Rosidi,KDnuggets 市场趋势与 SQL 内容专家,2026 年 12 月 2 日,机器学习
大多数已部署的模型只返回一个答案,别的什么都没有。
一个评论分类器输出“新鲜”。一个定价模型输出“$412”。下游代码读取这个值后继续往下走,无论模型当时是几乎确定还是纯靠猜。一旦只剩下最高分的标签,51% 的预测和 99% 的预测看起来一模一样。输出中没有任何信息说明哪些答案可信、哪些需要再看一眼。
保形预测(conformal prediction)无需改动模型本身就能解决这个问题。
它能包裹任何已训练好的分类器或回归器,使其返回一组可能的答案,或一个区间,并带有一个我们预先选定、且可证明成立的覆盖率。我们先从理论及其来源论文讲起:保形预测是在哪里提出的、它保证了什么、以及它是如何工作的。然后我们把它应用到一个真实 take-home 作业的官方解法上,即 Meta 的 Rotten Tomatoes 电影评分预测项目。
单一自信答案的麻烦
一个被强制只输出一个标签的模型,即便面对与其训练数据不同的输入,也仍然必须选出某个结果。一篇称赞演技却猛批剧本的影评。一张位于决策边界上的肿瘤扫描图像。一笔既像正常消费又像欺诈消费的交易。
在每种情况下,模型都会选定一个类别,而读者无法分辨这究竟是有把握的判断还是抛硬币。这一点在医疗和信贷决策中最为重要,因为把一个错误答案当作确定结论,代价要高于诚实地承认“我不确定”。
在实践中,“我不确定”会触发不同的处理动作。模型无法判读的扫描影像会交给放射科医生二次阅片。模型无法判定的贷款申请会转给信贷审核员,而不是被自动拒绝。有把握的案例仍走自动化流程,因此人们只需复核不确定的那些。借助共形预测(conformal prediction),“不确定”有了具体形式:一个包含多个标签的预测集。
为什么预测概率不是真实概率
常见的修正办法是查看模型自身的置信度分数:对神经网络来说是 softmax 输出,对随机森林来说是投票占比,无论哪种情况都是一个 predict_proba 值。
问题在于,这些数字默认都没有经过校准。
Guo 等人 2017 年的研究表明,现代神经网络经常过度自信:一个报告 90% 置信度的模型,其实际正确的比例往往远低于 90%。
其他类型的模型也有各自的校准偏差。Niculescu-Mizil 和 Caruana 在 2005 年发现,随机森林——也就是该项目官方解法所用的模型——倾向于把概率推离 0 和 1。
Platt scaling 和 isotonic regression 平均而言能改善校准效果,但它们不提供有限样本保证。共形预测则为其预测集的覆盖率提供了这样的保证。
共形预测的保证
共形预测由 Vladimir Vovk、Alexander Gammerman 和 Glenn Shafer 在 2005 年出版的《Algorithmic Learning in a Random World》一书中提出。
本文使用的分类方法,通常称为阈值法或最小模糊集方法,来自 Sadinle、Lei 和 Wasserman 在 2019 年发表的论文《Least Ambiguous Set-Valued Classifiers With Bounded Error Levels》。
这个保证是这样表述的:对于选定的错误率 alpha,预测集包含真实答案的概率至少为 1 减去 alpha(当 alpha 为 0.1 时为 90%),这是对来自同一分布的重复样本取平均而言。
这对任何模型、数据集和类别数量都成立,只要校准数据和新数据是可交换的:如果我们打乱这些点,它们的联合分布不会改变。这比独立同分布更弱,而这是该保证所依赖的唯一假设。
共形预测根据模型在留出数据上的实际错误模式进行校准,因此无论模型的概率输出如何,该保证都成立。
分割共形预测的工作原理
分割共形预测是最简单的变体,其工作分为四步:
将标注数据划分为训练集和一个单独的校准集。
仅在训练集上正常训练模型。
在校准集上,为每个样本计算一个非一致性分数:模型输出偏离正确结果的程度。对于分类任务,一个简单的选择是 1 减去真实类别的预测概率。
取这些分数的经验分位数,水平为 ceil((n + 1)(1 - alpha)) / n,其中 n 是校准集大小。相对于普通的 (1 - alpha) 分位数,这一微小修正使该保证在有限样本下仍然有效。
要对新输入进行预测,就纳入所有非一致性分数小于等于该阈值的候选标签。置信度高的输入最终在集合中只有一个标签。模棱两可的输入最终会有多个标签,偶尔一个也没有。
一个完整示例:教会电影评论分类器说“我不确定”
Rotten Tomatoes 项目给了我们 50,000 条影评人评论,并要求构建一个模型,预测一部电影是 Fresh、Rotten 还是 Certified-Fresh。
该项目包含两条路线。
基于特征的路径预测一部电影的 Tomatometer 三分类状态:Rotten、Fresh 或 Certified-Fresh。
基于文本的路径则预测单条影评是 Fresh 还是 Rotten。我们对这个二元评论分类器应用保形预测,然后将评论级集合聚合为电影级的 Fresh/Rotten 判定结果。
基于特征的路径达到约 99% 的准确率,这得益于与状态本身紧密相关的 Tomatometer 衍生特征。基于文本的路径对于不确定性估计来说是更有意思的案例:它仅从语言预测评论情感,在评论文本词上训练随机森林,并在 1,000 条留出评论上达到约 69% 的准确率。这留下了怀疑空间,因此我们使用它。
下面的代码复用了官方纯代码解决方案 notebook 中的变量名,并在构建 df_feature_critics 和 class_weight_dict_crit 的单元格之后运行。
第 1 步:从项目模型开始
我们复用了该解决方案的四个部分:5,000 条评论的子集、80/20 划分、名为 vectorizer_crit_weight 的 CountVectorizer,以及名为 rf_weighted_crit 的加权随机森林。
有一处改动:官方 notebook 根据全部 5,000 个标签计算类别权重,这会让留出标签影响模型。我们仅根据训练标签计算它们,因此模型在看到任何校准标签之前就固定下来。
# 来自官方解决方案:前 5,000 条评论按 80/20 划分 X_train_crit, X_test_crit, y_train_crit, y_test_crit = train_test_split( df_feature_critics["review_content"], df_feature_critics["review_type"], test_size=0.2, random_state=42 ) # 我们的改动:仅从训练标签计算类别权重 import numpy as np from sklearn.utils.class_weight import compute_class_weight classes = np.unique(y_train_crit) class_weights = compute_class_weight( class_weight="balanced", classes=classes, y=y_train_crit ) class_weight_dict_crit = dict(zip(classes, class_weights)) vectorizer_crit_weight = CountVectorizer(min_df=1) X_train_vec_weight = vectorizer_crit_weight.fit_transform(X_train_crit) rf_weighted_crit = RandomForestClassifier( random_state=2, class_weight=class_weight_dict_crit ) rf_weighted_crit.fit(X_train_vec_weight, y_train_crit)
这 1,000 条测试评论从未参与训练,因此可作为校准数据。
第 2 步:添加校准步骤
这是唯一新增的代码,模型保持不变。我们将 1,000 条测试评论分为 500 条校准评论和 500 条评估评论,并将 alpha 设为 0.1,即 90% 的覆盖率目标。
import numpy as np from sklearn.model_selection import train_test_split # 我们的补充:将项目的测试评论拆分为校准和评估两半 X_cal, X_eval, y_cal, y_eval = train_test_split( X_test_crit, y_test_crit.astype(int), test_size=0.5, random_state=42, stratify=y_test_crit ) alpha = 0.1 # 我们的目标:集合在 90% 的情况下包含真实评论标签 cal_probs = rf_weighted_crit.predict_proba(vectorizer_crit_weight.transform(X_cal)) cal_scores = 1 - cal_probs[np.arange(len(y_cal)), y_cal.values] n = len(cal_scores) q_hat = np.quantile(cal_scores, np.ceil((n + 1) * (1 - alpha)) / n, method="higher") print("概率阈值:", round(1 - q_hat, 3)) eval_probs = rf_weighted_crit.predict_proba(vectorizer_crit_weight.transform(X_eval)) pred_sets = [np.where(row >= 1 - q_hat)[0] for row in eval_probs] covered = np.mean([y in s for y, s in zip(y_eval.values, pred_sets)]) print("经验覆盖率:", round(covered, 3))
校准后的阈值为 0.37。达到或高于该阈值的标签会加入集合。
在两个类别且阈值为 0.37 的情况下,不可能出现空集,因为其中一个类别的概率必须至少为 0.5。
当类别更多时,或者只要校准后的阈值高于模型的最高类别概率,就可能出现空集。
第 3 步:检查结果
500 条评估评论上的结果:
原文较长,译文为节选;译文由英文原文机器翻译,术语按行业惯例统一,可在文末展开原文核对。
查看英文原文(Can Your Model Admit When It’s Unsure? A Guide to Conformal Prediction)
A practical, distribution-free way to make any model report its own uncertainty.
By Nate Rosidi, KDnuggets Market Trends & SQL Content Specialist on December 2, 2026 in Machine Learning

Most deployed models hand back one answer and nothing else.
A review classifier says "Fresh." A pricing model says "\$412." Downstream code reads that value and moves on, whether the model was nearly certain or barely guessing. A 51% prediction and a 99% prediction look identical once only the top label survives. Nothing in the output says which answers to trust and which need a second look.
Conformal prediction fixes this without touching the model itself.
It wraps any trained classifier or regressor so it returns a set of plausible answers, or an interval, with a coverage rate we choose in advance and can prove holds. We start with the theory and the papers it comes from: where conformal prediction was introduced, what it guarantees, and how it works. Then we apply it to the official solution of a real take-home assignment, the Rotten Tomatoes Movies Rating Prediction project from Meta.
The Trouble with a Single Confident Answer
A model forced to output one label still has to pick something, even on inputs unlike its training data. A critic review that praises the acting and pans the script. A tumor scan on the decision boundary. A transaction that resembles both normal and fraudulent spending.
In each case, the model commits to one class, and the reader can't tell a confident call from a coin flip. That matters most in medicine and credit decisions, where a wrong answer taken as certain costs more than an honest "I'm not sure."
In practice, "I'm not sure" triggers a different action. A scan the model can't call goes to a radiologist for a second read. A loan application it can't call goes to an underwriter instead of being auto-declined. The confident cases stay automated, so people only review the uncertain ones. With conformal prediction, "not sure" has a concrete form: a prediction set with more than one label.
Why Predicted Probabilities Are Not Real Probabilities
The usual fix is to look at the model's own confidence score: a softmax output for a neural network, a vote fraction for a random forest, a predict_proba value either way.
The problem is that none of these numbers are calibrated by default.
Guo et al. showed in 2017 that modern neural networks are frequently overconfident: a model that reports 90% confidence is often right far less than 90% of the time.
Other families miscalibrate in their own way. Niculescu-Mizil and Caruana found in 2005 that random forests, the model in the project's official solution, tend to push probabilities away from 0 and 1.
Platt scaling and isotonic regression improve calibration on average, but they come with no finite-sample guarantee. Conformal prediction supplies one for the coverage of its sets.
The Conformal Prediction Guarantee
Conformal prediction was introduced by Vladimir Vovk, Alexander Gammerman, and Glenn Shafer in their 2005 book "Algorithmic Learning in a Random World."
The classification method used in this article, often called the threshold or least-ambiguous-set approach, comes from Sadinle, Lei, and Wasserman's 2019 paper "Least Ambiguous Set-Valued Classifiers With Bounded Error Levels."
The guarantee reads like this: for a chosen error rate alpha, the prediction set contains the true answer at least 1 minus alpha of the time (90% for an alpha of 0.1), averaged over repeated samples from the same distribution.
That holds for any model, dataset, and number of classes, as long as the calibration data and the new data are exchangeable: their joint distribution wouldn't change if we shuffled the points. That's weaker than independent and identically distributed, and it's the one assumption the guarantee rests on.
Conformal prediction calibrates against the model's actual error pattern on held-out data, so the guarantee holds whatever the model's probabilities say.
How Split Conformal Prediction Works
Split conformal prediction, the simplest variant, works in four steps:
Split the labeled data into a training set and a separate calibration set.
Train the model normally on the training set only.
On the calibration set, compute a nonconformity score for every example: how far the model's output is from being right. For classification, a simple choice is 1 minus the predicted probability of the true class.
Take the empirical quantile of those scores at level ceil((n + 1)(1 - alpha)) / n, where n is the calibration set size. That small correction over the plain (1 - alpha) quantile keeps the guarantee valid in finite samples.
To predict on a new input, include every candidate label whose nonconformity score falls at or below that threshold. Confident inputs end up with one label in the set. Ambiguous inputs end up with several, or occasionally none.
A Worked Example: Teaching a Movie Review Classifier to Say "I'm Not Sure"
The Rotten Tomatoes project gives us 50,000 critic reviews and asks for a model that predicts whether a movie is Fresh, Rotten, or Certified-Fresh.
The project contains two routes.
The feature-based route predicts a movie's three-way Tomatometer status: Rotten, Fresh, or Certified-Fresh.
The text-based route instead predicts whether an individual critic review is Fresh or Rotten. We apply conformal prediction to this binary review classifier, then aggregate the review-level sets into a movie-level Fresh/Rotten readout.
The feature-based route reaches about 99% accuracy, helped by Tomatometer-derived features that are closely tied to the status itself. The text route is the more interesting case for uncertainty estimation: it predicts review sentiment from language alone, trains a random forest on review words, and reaches about 69% accuracy on 1,000 held-out reviews. That leaves room for doubt, so we use it.
The code below reuses the variable names from the official code-only solution notebook and runs after the cells that build df_feature_critics and class_weight_dict_crit.
Step 1: Starting from the Project's Model
We reuse four pieces of the solution: the 5,000-review subset, the 80/20 split, the CountVectorizer named vectorizer_crit_weight, and the weighted random forest named rf_weighted_crit.
One change: the official notebook computes the class weights from all 5,000 labels, which lets the held-out labels influence the model. We compute them from the training labels only, so the model is fixed before it sees any calibration label.
# from the official solution: 80/20 split of the first 5,000 reviews
X_train_crit, X_test_crit, y_train_crit, y_test_crit = train_test_split(
df_feature_critics["review_content"],
df_feature_critics["review_type"],
test_size=0.2, random_state=42
)
# our change: class weights from the training labels only
import numpy as np
from sklearn.utils.class_weight import compute_class_weight
classes = np.unique(y_train_crit)
class_weights = compute_class_weight(
class_weight="balanced", classes=classes, y=y_train_crit
)
class_weight_dict_crit = dict(zip(classes, class_weights))
vectorizer_crit_weight = CountVectorizer(min_df=1)
X_train_vec_weight = vectorizer_crit_weight.fit_transform(X_train_crit)
rf_weighted_crit = RandomForestClassifier(
random_state=2, class_weight=class_weight_dict_crit
)
rf_weighted_crit.fit(X_train_vec_weight, y_train_crit)
The 1,000 test reviews never touched training, so they work as calibration data.
Step 2: Adding the Calibration Step
This is the only new code, and the model stays untouched. We split the 1,000 test reviews into 500 calibration and 500 evaluation reviews and set alpha to 0.1, a 90% coverage target.
import numpy as np
from sklearn.model_selection import train_test_split
# our addition: split the project's test reviews into calibration and evaluation halves
X_cal, X_eval, y_cal, y_eval = train_test_split(
X_test_crit, y_test_crit.astype(int),
test_size=0.5, random_state=42, stratify=y_test_crit
)
alpha = 0.1 # our target: sets contain the true review label 90% of the time
cal_probs = rf_weighted_crit.predict_proba(vectorizer_crit_weight.transform(X_cal))
cal_scores = 1 - cal_probs[np.arange(len(y_cal)), y_cal.values]
n = len(cal_scores)
q_hat = np.quantile(cal_scores, np.ceil((n + 1) * (1 - alpha)) / n, method="higher")
print("probability threshold:", round(1 - q_hat, 3))
eval_probs = rf_weighted_crit.predict_proba(vectorizer_crit_weight.transform(X_eval))
pred_sets = [np.where(row >= 1 - q_hat)[0] for row in eval_probs]
covered = np.mean([y in s for y, s in zip(y_eval.values, pred_sets)])
print("empirical coverage:", round(covered, 3))
The calibrated threshold is 0.37. Labels at or above it join the set.
With two classes and a 0.37 threshold, an empty set cannot occur, because one class must have probability of at least 0.5.
Empty sets can occur with more classes, or whenever the calibrated threshold rises above the model's highest class probability.
Step 3: Checking the Results
Results on the 500 evaluation reviews:
The sets reach 91.8% empirical coverage, but that coverage has a cost: 53.4% of evaluation reviews receive {Fresh, Rotten} instead of a single label.
In a binary problem, that set contains every possible class, so it is valid but doesn't separate the two outcomes for that review.
Conformal prediction exposes how much uncertainty already sits inside the underlying 69%-accuracy classifier.
The 91.8% is the empirical coverage on this particular 500-review evaluation sample. The 90% is a marginal guarantee under exchangeability, so a single sample can land slightly below it as easily as above it.
Reading the Prediction Sets
Two reviews from the evaluation half, with the model's point prediction (the single label predict returns) next to the conformal set:
The first row is the easy case: the model is right, and the conformal set contains only that label. In the second row, the point classifier commits to Rotten and is wrong.
The conformal set reports both labels instead, flagging the review as ambiguous under the model while still containing the true label.
From Review Sets to a Movie Verdict
The project labels a movie Fresh if at least 60% of its reviews are predicted positive. We can run the sets through the same rule for a best case and a worst case: the share of reviews whose set is {Fresh}, and the share whose set includes Fresh.
# our movie-level read-out: share of Fresh-only sets vs sets that include Fresh
def movie_fresh_range(reviews):
probs = rf_weighted_crit.predict_proba(vectorizer_crit_weight.transform(reviews))
sets = [np.where(row >= 1 - q_hat)[0] for row in probs]
fresh_only = np.mean([list(s) == [1] for s in sets]) * 100
any_fresh = np.mean([1 in s for s in sets]) * 100
return fresh_only, any_fresh
We ran it on the three movies the solution already uses:
The call is Fresh if the Fresh-only share reaches 60%, Rotten if even the sets-with-Fresh share stays below 60%, and Uncertain in between.
Here, "Uncertain" does not mean the model failed or that the movie has no prediction. It means the conformal range crosses the 60% Fresh cutoff: enough ambiguous review sets contain both Fresh and Rotten that the movie could fall on either side of the decision threshold.
All three ranges cross the 60% decision threshold, so the conformal readout can't certify any of these movies as definitely Fresh or definitely Rotten. That is useful information in itself: the review-level uncertainty is wide enough to make the aggregate movie decision unstable.
The Duchess makes this especially clear. The project's plain pipeline gives it 60.74% positive reviews, only 0.74 percentage points above the Fresh cutoff, while the conformal readout spans both sides of 60%.
This readout is a heuristic built on the review-level marginal guarantee. Across exchangeable reviews, the true label is covered at least 90% of the time on average. That is not a 90% guarantee for each individual review. Reviews from the same movie may also be dependent, so the review-level guarantee doesn't automatically become a coverage guarantee for the aggregated movie verdict.
Common Mistakes and Edge Cases
Treating the Guarantee as Per-Input Instead of Marginal
The 90% coverage is an average over the whole test distribution. Fresh reviews can have better coverage than Rotten ones while the average hits the target. Class-conditional (Mondrian) conformal prediction fixes this when per-group guarantees matter.
Letting the Calibration Data Drift from Production Data
The exchangeability assumption breaks once live inputs shift away from the calibration set. The movies above sit beyond the first 5,000 reviews the model and calibration data came from, so formally the guarantee covers the random held-out split, not them.
Using Too Small a Calibration Set
A handful of calibration points gives a noisy quantile and missed coverage. The 500 calibration reviews used here are a reasonable floor.
Chasing Higher Coverage Without Checking Set Size
Lowering alpha raises coverage but inflates set size. Returning {Fresh, Rotten} for every review is valid and useless.
Not Planning for an Empty Set
With two classes and our threshold, an empty set can't occur, but a stricter alpha or more classes can. It's informative, but it needs a plan: route to a human, fall back to a simpler rule, or flag the input for retraining data.
Conformal prediction wraps whatever model we already have, classifier or regressor, in a calibration step that turns raw scores into prediction sets or intervals backed by a coverage guarantee. It needs no retraining and no architecture changes.
On the Rotten Tomatoes reviews, this gave a random forest with about 69% accuracy a way to flag the reviews it can't call. Confident reviews get one label. Borderline reviews get both Fresh and Rotten, and across exchangeable reviews the true label sits inside the set at least 90% of the time.
The cost shows up in set size. To reach that coverage, the classifier returned both labels for 53.4% of evaluation reviews, and none of the three example movies could be certified as Fresh or Rotten by the movie-level readout. Those are the most informative results in the example.
Two limits matter when we use it. The 90% is an average over the whole test distribution, so Fresh reviews can be covered better than Rotten ones. And coverage only means something next to set size: a model that returns every label for every input meets the guarantee and tells us nothing.
Before shipping, we decide what happens to an ambiguous or empty set: a human review, a simpler fallback rule, or a request for more labeled data. The ambiguous sets are the useful output, because they show which predictions need a second look.
Nate Rosidi is a data scientist and in product strategy. He's also an adjunct professor teaching analytics, and is the founder of StrataScratch, a platform helping data scientists prepare for their interviews with real interview questions from top companies. Nate writes on the latest trends in the career market, gives interview advice, shares data science projects, and covers everything SQL.
原文为英文,正文由自动抓取并保留原文。
原文发布于 KDnuggets(Can Your Model Admit When It’s Unsure? A Guide to Conformal Prediction),标题、摘要与正文由机器翻译,术语按行业惯例统一,未经人工逐句校订。