# Calibrating Scikit-LLM Classifiers: Knowing When to Trust an LLM Prediction

> Source: <https://machinelearningmastery.com/calibrating-scikit-llm-classifiers-knowing-when-to-trust-an-llm-prediction/>
> Published: 2026-12-03 11:00:53+00:00

**Recommendation:** Wrap repeated zero-shot LLM classifications in a self-consistency layer to get class probabilities, verify calibration with a reliability diagram, and route predictions below your confidence threshold to human review.
More in the playbook "Verifying model output": <https://wpnews.pro/playbooks/output-verification>

In this article, you will learn how to turn repeated zero-shot predictions from a local LLM into calibrated confidence scores with scikit-llm, and how to use those scores to route uncertain predictions to human review.

Topics we will cover include:

- How to set up a free, local Llama 3.1 8B model with Ollama and connect it to scikit-llm.
- How to build a self-consistency wrapper that converts repeated zero-shot predictions into class probabilities, and how to check its calibration with a reliability diagram.
- How to use a confidence threshold to send uncertain predictions to human review instead of acting on them automatically.

## Introduction

Most of the latest large language models — commonly referred to by their abbreviation, LLMs — are excellent zero-shot classifiers; i.e. they can accurately classify texts across multiple topics without domain-specific retraining, relying only on a label set and, at most, a few examples.

However, they suffer from a common, potentially dangerous flaw: hallucinations, often delivered with poorly calibrated confidence. Once an LLM becomes part of an automated pipeline, an incorrect classification can turn into misrouted IT support tickets, misdiagnosed medical reports, or legitimate transactions that end up flagged, to name a few situations.

This article teaches you how to safely deploy **LLM-based applications** in a production setting by leveraging **calibrated confidence scores in predictions**. If a model is, say, just 65% sure about a prediction it made, the system routes the edge case to a human — or to a lightweight, classical machine learning model specifically trained for domain text classification. We will implement an example solution that you can easily adapt to your scenario, aided by `scikit-llm` and a self-consistency wrapper that turns raw predictions into calibrated probabilities.

## Initial Setup

To keep the practical tutorial in this article free and open-source, instead of relying on commercial APIs we will use Ollama’s Llama 3.1 8B model. It is large enough to perform decent zero-shot classifications, but not so large that it might overwhelm your local environment or Colab notebook. I ran everything on a Google Colab GPU, which I recommend for a first try, as this way you won’t need to spend several gigabytes of local storage on downloading the model.

With this in mind, let’s start by making sure you are working on Colab’s T4 GPU, then install the Python libraries and system dependencies needed, including the Ollama distribution and `zstd`, which is key for efficiently handling background models in a Colab notebook environment:

```
# Installing system dependencies and Ollama
!sudo apt-get update && sudo apt-get install -y zstd
!curl -fsSL https://ollama.com/install.sh | sh

# Installing Python ML dependencies
!pip install scikit-llm

123456

# Installing system dependencies and Ollama!sudo apt-get update && sudo apt-get install -y zstd!curl -fsSL https://ollama.com/install.sh | sh # Installing Python ML dependencies!pip install scikit-llm
```

The next setup step is booting the Ollama server as a background process and pulling (downloading) the Llama 3.1 8B model.

``` python
import subprocess
import time

# Starting Ollama in the background
subprocess.Popen(["ollama", "serve"])
time.sleep(3)

# Pulling the Llama 3.1 8B model
!ollama pull llama3.1:8b

123456789

import subprocessimport time # Starting Ollama in the backgroundsubprocess.Popen(["ollama", "serve"])time.sleep(3) # Pulling the Llama 3.1 8B model!ollama pull llama3.1:8b
```

Lastly, let’s configure `scikit-llm` to point to your local Ollama instance via its OpenAI-compatible endpoint — we won’t use actual OpenAI models; we are just overriding the default endpoint URL:

``` python
from skllm.config import SKLLMConfig

SKLLMConfig.set_openai_key("ollama-local")
SKLLMConfig.set_gpt_url("http://localhost:11434/v1/")

1234

from skllm.config import SKLLMConfig SKLLMConfig.set_openai_key("ollama-local")SKLLMConfig.set_gpt_url("http://localhost:11434/v1/")
```

## Building the Smart Reliability Engine for an LLM-driven Classifier

The main building block for our reliability-based routing engine is a self-consistency wrapper class around scikit-llm’s `ZeroShotGPTClassifier`, which uses our pulled model to return discrete labels for the texts passed as inputs. To implement the self-consistency mechanism, we prompt the model to classify every single text multiple times (in our example, `n_runs=3`):

``` python
import random
import numpy as np
from collections import Counter
from skllm.models.gpt.classification.zero_shot import ZeroShotGPTClassifier
from sklearn.base import BaseEstimator, ClassifierMixin

class SelfConsistentLLMClassifier(BaseEstimator, ClassifierMixin):
    # Default model: Llama 3.1 8B served by Ollama
    def __init__(self, model="llama3.1:8b", n_runs=3, classes=None):
        self.model = model
        self.n_runs = n_runs
        self.classes_ = classes

    def fit(self, X, y=None):
        return self

    def predict_proba(self, X):
        probs = []

        print(f"Starting {self.n_runs} self-consistency runs for {len(X)} items...")

        for i, x in enumerate(X):
            sample_predictions = []

            for _ in range(self.n_runs):
                clf = ZeroShotGPTClassifier(model=self.model)

                # Test-Time Augmentation: Shuffling class order helps break determinism
                shuffled_classes = list(self.classes_)
                random.shuffle(shuffled_classes)

                clf.fit(None, shuffled_classes)
                pred = clf.predict([x])[0]
                sample_predictions.append(pred)

            counts = Counter(sample_predictions)
            # Calculating the fraction of votes for each class
            row_probs = [counts.get(cls, 0) / self.n_runs for cls in self.classes_]
            probs.append(row_probs)

        return np.array(probs)

    def predict(self, X):
        probs = self.predict_proba(X)
        return np.array([self.classes_[i] for i in np.argmax(probs, axis=1)])

123456789101112131415161718192021222324252627282930313233343536373839404142434445

import randomimport numpy as npfrom collections import Counterfrom skllm.models.gpt.classification.zero_shot import ZeroShotGPTClassifierfrom sklearn.base import BaseEstimator, ClassifierMixin class SelfConsistentLLMClassifier(BaseEstimator, ClassifierMixin):    # Default model: Llama 3.1 8B served by Ollama    def __init__(self, model="llama3.1:8b", n_runs=3, classes=None):        self.model = model        self.n_runs = n_runs        self.classes_ = classes     def fit(self, X, y=None):        return self     def predict_proba(self, X):        probs = []         print(f"Starting {self.n_runs} self-consistency runs for {len(X)} items...")         for i, x in enumerate(X):            sample_predictions = []             for _ in range(self.n_runs):                clf = ZeroShotGPTClassifier(model=self.model)                 # Test-Time Augmentation: Shuffling class order helps break determinism                shuffled_classes = list(self.classes_)                random.shuffle(shuffled_classes)                 clf.fit(None, shuffled_classes)                pred = clf.predict([x])[0]                sample_predictions.append(pred)             counts = Counter(sample_predictions)            # Calculating the fraction of votes for each class            row_probs = [counts.get(cls, 0) / self.n_runs for cls in self.classes_]            probs.append(row_probs)         return np.array(probs)     def predict(self, X):        probs = self.predict_proba(X)        return np.array([self.classes_[i] for i in np.argmax(probs, axis=1)])
```

Note that we shuffle the class labels to force the model to show some uncertainty on ambiguous texts that are trickier to classify, like some of the examples used later on.

Now we write code to evaluate predictions using a reliability diagram. We consider a model to be “well-calibrated” if its 80%-confidence predictions are right 80% of the time. We also define a small labeled dataset for zero-shot classification that includes a few ambiguous edge cases.

``` python
import matplotlib.pyplot as plt
from sklearn.calibration import calibration_curve
from sklearn.metrics import accuracy_score

# Expected classes
classes = ["hardware", "software", "network"]

# Dataset containing examples belonging to the 3 core domains
X_test = [
    "I can't reset my password, the link is broken.",
    "My monitor won't turn on.",
    "The VPN drops every 5 minutes!",
    "Excel keeps crashing when I open large files.",
    "The Wi-Fi is completely down in conference room B.",
    "My mouse is double-clicking on its own.",
    "My monitor won't turn on AND the VPN is completely down.", # Dual-intent (likely causing split reasoning)
    "The cloud storage sync is stuck on 'pending'.", # Ambiguous (Software vs Network)
    "My IP desk phone has no dial tone and the screen is blank." # Ambiguous (Hardware vs Network)
]
y_true = ["software", "hardware", "network", "software", "network", "hardware", "hardware", "software", "hardware"]

# 2. Running the Local Wrapper (27 inferences total, easily handled by Colab GPU)
ensemble = SelfConsistentLLMClassifier(model="llama3.1:8b", n_runs=3, classes=classes)
probs = ensemble.predict_proba(X_test)
y_pred = ensemble.predict(X_test)

print(f"\nZero-Shot Accuracy: {accuracy_score(y_true, y_pred):.2f}")

# 3. Plotting Reliability Diagram
# To get a smoother curve from 9 items, flatten the probabilities across all 3 classes
y_true_binarized = np.array([[1 if y == c else 0 for c in classes] for y in y_true]).flatten()
probs_flattened = probs.flatten()

fraction_of_positives, mean_predicted_value = calibration_curve(
    y_true_binarized, probs_flattened, n_bins=4, strategy='uniform'
)

plt.figure(figsize=(7, 6))
plt.plot(mean_predicted_value, fraction_of_positives, "s-", color="#1f77b4", linewidth=2, label="Llama 3.1 (Self-Consistent)")
plt.plot([0, 1], [0, 1], "k:", linewidth=2, label="Perfectly Calibrated")

plt.ylabel("Actual Correctness (Fraction of Positives)")
plt.xlabel("LLM Stated Confidence (Mean Predicted Probability)")
plt.title("Reliability Diagram: LLM Confidence vs. Reality")
plt.legend(loc="upper left")
plt.grid(True, linestyle="--", alpha=0.7)
plt.show()

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647

import matplotlib.pyplot as pltfrom sklearn.calibration import calibration_curvefrom sklearn.metrics import accuracy_score # Expected classesclasses = ["hardware", "software", "network"] # Dataset containing examples belonging to the 3 core domainsX_test = [    "I can't reset my password, the link is broken.",    "My monitor won't turn on.",    "The VPN drops every 5 minutes!",    "Excel keeps crashing when I open large files.",    "The Wi-Fi is completely down in conference room B.",    "My mouse is double-clicking on its own.",    "My monitor won't turn on AND the VPN is completely down.", # Dual-intent (likely causing split reasoning)    "The cloud storage sync is stuck on 'pending'.", # Ambiguous (Software vs Network)    "My IP desk phone has no dial tone and the screen is blank." # Ambiguous (Hardware vs Network)]y_true = ["software", "hardware", "network", "software", "network", "hardware", "hardware", "software", "hardware"] # 2. Running the Local Wrapper (27 inferences total, easily handled by Colab GPU)ensemble = SelfConsistentLLMClassifier(model="llama3.1:8b", n_runs=3, classes=classes)probs = ensemble.predict_proba(X_test)y_pred = ensemble.predict(X_test) print(f"\nZero-Shot Accuracy: {accuracy_score(y_true, y_pred):.2f}") # 3. Plotting Reliability Diagram# To get a smoother curve from 9 items, flatten the probabilities across all 3 classesy_true_binarized = np.array([[1 if y == c else 0 for c in classes] for y in y_true]).flatten()probs_flattened = probs.flatten() fraction_of_positives, mean_predicted_value = calibration_curve(    y_true_binarized, probs_flattened, n_bins=4, strategy='uniform') plt.figure(figsize=(7, 6))plt.plot(mean_predicted_value, fraction_of_positives, "s-", color="#1f77b4", linewidth=2, label="Llama 3.1 (Self-Consistent)")plt.plot([0, 1], [0, 1], "k:", linewidth=2, label="Perfectly Calibrated") plt.ylabel("Actual Correctness (Fraction of Positives)")plt.xlabel("LLM Stated Confidence (Mean Predicted Probability)")plt.title("Reliability Diagram: LLM Confidence vs. Reality")plt.legend(loc="upper left")plt.grid(True, linestyle="--", alpha=0.7)plt.show()
```

This is the resulting curve, for an overall **zero-shot accuracy of 0.89**:

Looking at the diagram, it is not difficult to notice the classic LLM overconfidence issue. The blue line falls below the dotted diagonal for perfect calibration near the upper end of the diagram. This reveals that when the model reports being 100% confident, it is actually correct only around 85% of the time. The model also seems to self-correct around the middle ranges.

Finally, to add the last but key layer of protection against overconfidence, we implement a threshold-driven abstention mechanism that reroutes uncertain predictions:

``` python
def route_predictions(X, y_pred, probs, threshold=0.8):
    automated_queue = []
    human_review_queue = []

    for i, (text, pred, prob_dist) in enumerate(zip(X, y_pred, probs)):
        confidence = np.max(prob_dist)

        if confidence >= threshold:
            automated_queue.append((text, pred, confidence))
        else:
            human_review_queue.append((text, pred, confidence))

    return automated_queue, human_review_queue

# Strict threshold: with 3 runs, confidence can only be 1/3, 2/3 or 1, so 0.8 requires unanimity to automate
auto, manual = route_predictions(X_test, y_pred, probs, threshold=0.8)

print("--- AUTOMATED ROUTING ---")
for item in auto:
    print(f"[{item[2]*100:.0f}%] {item[1].upper()} <- {item[0]}")

print("\n--- HUMAN REVIEW REQUIRED ---")
for item in manual:
    print(f"[{item[2]*100:.0f}%] Uncertain (Leans {item[1].upper()}) <- {item[0]}")

123456789101112131415161718192021222324

def route_predictions(X, y_pred, probs, threshold=0.8):    automated_queue = []    human_review_queue = []     for i, (text, pred, prob_dist) in enumerate(zip(X, y_pred, probs)):        confidence = np.max(prob_dist)         if confidence >= threshold:            automated_queue.append((text, pred, confidence))        else:            human_review_queue.append((text, pred, confidence))     return automated_queue, human_review_queue # Strict threshold: with 3 runs, confidence can only be 1/3, 2/3 or 1, so 0.8 requires unanimity to automateauto, manual = route_predictions(X_test, y_pred, probs, threshold=0.8) print("--- AUTOMATED ROUTING ---")for item in auto:    print(f"[{item[2]*100:.0f}%] {item[1].upper()} <- {item[0]}") print("\n--- HUMAN REVIEW REQUIRED ---")for item in manual:    print(f"[{item[2]*100:.0f}%] Uncertain (Leans {item[1].upper()}) <- {item[0]}")
```

Results:

```
--- AUTOMATED ROUTING ---
[100%] SOFTWARE <- I can't reset my password, the link is broken.
[100%] HARDWARE <- My monitor won't turn on.
[100%] NETWORK <- The VPN drops every 5 minutes!
[100%] NETWORK <- The Wi-Fi is completely down in conference room B.
[100%] HARDWARE <- My mouse is double-clicking on its own.
[100%] NETWORK <- My monitor won't turn on AND the VPN is completely down.
[100%] HARDWARE <- My IP desk phone has no dial tone and the screen is blank.

--- HUMAN REVIEW REQUIRED ---
[67%] Uncertain (Leans SOFTWARE) <- Excel keeps crashing when I open large files.
[67%] Uncertain (Leans SOFTWARE) <- The cloud storage sync is stuck on 'pending'.

123456789101112

--- AUTOMATED ROUTING ---[100%] SOFTWARE <- I can't reset my password, the link is broken.[100%] HARDWARE <- My monitor won't turn on.[100%] NETWORK <- The VPN drops every 5 minutes![100%] NETWORK <- The Wi-Fi is completely down in conference room B.[100%] HARDWARE <- My mouse is double-clicking on its own.[100%] NETWORK <- My monitor won't turn on AND the VPN is completely down.[100%] HARDWARE <- My IP desk phone has no dial tone and the screen is blank. --- HUMAN REVIEW REQUIRED ---[67%] Uncertain (Leans SOFTWARE) <- Excel keeps crashing when I open large files.[67%] Uncertain (Leans SOFTWARE) <- The cloud storage sync is stuck on 'pending'.
```

## Closing Remarks

The final output, in which most — but not all — class predictions were accepted automatically, nicely illustrates the bottom line of why LLM evaluation is tricky: these models do not think the way humans do. In the example implemented throughout this article, the model split its votes and flagged some ambiguous texts, also showing hesitation in specific instances like the Excel-related IT support ticket.

Meanwhile, the model looked at an obvious dual-intent ticket like **My monitor won’t turn on AND the VPN is completely down** and classified it purely under the network category with total confidence. This exposes additional operational risks and hints at the need for deeper mechanisms to inspect and break down models’ decision-making behavior.
