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.



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.

Conformal Prediction

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.

Conformal Prediction

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.

Conformal Prediction

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.

Conformal Prediction

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:

  1. Split the labeled data into a training set and a separate calibration set.
  2. Train the model normally on the training set only.
  3. 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.
  4. 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.

Conformal Prediction

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.

Conformal Prediction

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.

Conformal Prediction

# 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.

Conformal Prediction

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:

Conformal Prediction

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:

Conformal Prediction

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.

Conformal Prediction

# 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:

Conformal Prediction

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.

Conformal Prediction

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.

Conclusion

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.

Conformal Prediction

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.


Get the FREE ebook 'KDnuggets Artificial Intelligence Pocket Dictionary' along with the leading newsletter on Data Science, Machine Learning, AI & Analytics straight to your inbox.

By subscribing you accept KDnuggets Privacy Policy


Get the FREE ebook 'KDnuggets Artificial Intelligence Pocket Dictionary' along with the leading newsletter on Data Science, Machine Learning, AI & Analytics straight to your inbox.

By subscribing you accept KDnuggets Privacy Policy

Get the FREE ebook 'KDnuggets Artificial Intelligence Pocket Dictionary' along with the leading newsletter on Data Science, Machine Learning, AI & Analytics straight to your inbox.

By subscribing you accept KDnuggets Privacy Policy

No, thanks!