Sub topic 1
From scores to probabilities
Prerequisites
This chapter assumes you know the following:
- Binary and multiclass classification basics, including what a label and a decision threshold are.
- Train, validation and test splits.
- The sigmoid and softmax functions, and how logistic regression produces a number between 0 and 1.
- Basic Python with NumPy and scikit-learn.
Why the distinction matters
Almost every classifier produces a number before it produces a label. A decision tree reports class fractions in a leaf. A support vector machine reports a signed distance from a hyperplane. A neural network reports logits, which are unbounded real numbers. A naive Bayes model multiplies likelihoods. Each of these numbers ranks examples, and each can be turned into a label with a threshold.
Not every one of these numbers is a probability. A score is any number whose larger values suggest the positive class. A probability estimate is a score that you can read as a degree of belief: a value of 0.8 means that about 80% of cases like this one are positive. Scores only have to be ordered correctly. Probability estimates also have to carry the right magnitude.
Many libraries blur the two. In scikit-learn, predict_proba returns values in [0, 1] that sum to 1 across classes for nearly every classifier, so the output looks like a probability. Whether it behaves like one is a separate question, and it is the question this tutorial studies.
What counts as a probabilistic prediction
A probabilistic classifier maps an input x to a distribution over classes. For binary classification, it outputs a single number p(x), the estimated probability of the positive class. The negative class gets 1 - p(x).
Two properties are needed for the output to be a valid distribution:
- Every value is in [0, 1].
- The values across classes sum to 1.
Validity is cheap to achieve. A sigmoid or softmax layer guarantees it by construction. Validity says nothing about whether the numbers are trustworthy. A model that outputs 0.99 for every example is a valid probabilistic classifier. It is also badly wrong whenever the true positive rate is not 99%.
How common models produce scores
The route from raw output to a number in [0, 1] differs by model family. Knowing the route helps you predict how the numbers will behave.
| Model | Raw output | Conversion to [0, 1] | Typical behavior |
|---|---|---|---|
| Logistic regression | Linear score (log-odds) | Sigmoid | Usually close to calibrated when the model is well specified |
| Neural network | Logits | Sigmoid or softmax | Often overconfident |
| Naive Bayes | Product of class-conditional likelihoods | Normalize by the sum | Pushed toward 0 and 1 |
| Support vector machine | Signed margin distance | None by default | Not a probability at all |
| Random forest | Fraction of trees voting for a class | Average of tree outputs | Pulled away from 0 and 1 |
| Gradient boosting | Sum of tree outputs (log-odds) | Sigmoid | Varies with the number of rounds |
The support vector machine case is the clearest. SVC.decision_function returns margins such as -1.7 or 0.4. These are scores. SVC(probability=True) fits an internal sigmoid on top of them with cross-validation to produce predict_proba. That internal step is already a calibration method, and you will meet it again later in the tutorial as Platt scaling.
A worked example: scores that rank but do not calibrate
The code below trains a logistic regression and a linear support vector machine on the same data. It converts the support vector machine's margin to a number in [0, 1] with a naive sigmoid, and then compares both outputs to the observed positive rate in each score range.
import numpy as np
from scipy.special import expit
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
X, y = make_classification(
n_samples=20000, n_features=20, n_informative=5, random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.5, random_state=0
)
logreg = LogisticRegression(max_iter=1000).fit(X_train, y_train)
svm = LinearSVC(max_iter=10000).fit(X_train, y_train)
p_logreg = logreg.predict_proba(X_test)[:, 1]
margin = svm.decision_function(X_test)
p_naive = expit(margin) # a sigmoid with no fitted parameters
print("AUC logreg:", round(roc_auc_score(y_test, p_logreg), 4))
print("AUC svm :", round(roc_auc_score(y_test, margin), 4))
def show_bins(name, p, y_true, n_bins=5):
edges = np.quantile(p, np.linspace(0, 1, n_bins + 1))
ids = np.clip(np.searchsorted(edges, p, side="right") - 1, 0, n_bins - 1)
print(name)
for b in range(n_bins):
mask = ids == b
print(
f" bin {b}: mean score {p[mask].mean():.2f}, "
f"observed positive rate {y_true[mask].mean():.2f}"
)
show_bins("logistic regression", p_logreg, y_test)
show_bins("svm margin through sigmoid", p_naive, y_test)Run it and compare the two tables. The AUC values should be nearly identical, because both models rank the test examples about equally well. The bin tables will differ. For logistic regression, the mean score in each bin tracks the observed positive rate closely. For the squashed margin, the two columns drift apart, because a margin of 1.0 was never fitted to mean "73% positive". The sigmoid turned a score into something that looks like a probability and does not behave like one.
The exact numbers depend on your library versions, but the pattern holds. Ranking quality and probability quality are separate properties.
Visualizing the pipeline
Treat a classifier as a pipeline in which a probability is an optional last stage. The diagram shows where a score can be turned into a calibrated probability and where it is used.
Ranking and AUC need only the score at node C. Decisions that depend on magnitude, such as "act when the chance of fraud exceeds 2%", need the probability at node F, and they need it to be right.
What you can do only with real probabilities
A probability that is correct in magnitude supports uses that a bare score does not:
- Expected cost. If a missed positive costs 50 and a false alarm costs 1, the best rule is to flag a case when
p > 1 / 51. That threshold is only valid ifpis a true probability. - Combining models or evidence. Multiplying probabilities from independent sources, or feeding one model's output into another, assumes the numbers mean something.
- Reporting uncertainty. Telling a clinician or customer that the chance is 30% is a factual claim.
- Abstention. Sending only low-confidence cases to a human reviewer works when confidence tracks correctness.
A bare score supports only the first kind of use you have already seen: sorting and picking a cutoff by trial.
Common errors to avoid
- Treating
predict_probaas ground truth. The method name promises a probability. The model does not guarantee one. Always test. - Reading the largest class probability as accuracy. A model whose top class probability averages 0.95 is not necessarily 95% accurate.
- Using a score that is not bounded. Passing SVM margins or raw logits into code that expects [0, 1] values produces silent nonsense.
- Assuming that a better AUC implies better probabilities. The example above shows two models with almost equal AUC and different probability quality.
- Assuming that fitting with log loss makes the output calibrated. Training with a proper loss pushes toward calibrated outputs on the training data. Regularization, early stopping, model capacity, and overfitting can all move the result away from it on new data.
Where this chapter leads
The next chapter defines calibration precisely: among all cases that receive a predicted probability of 0.8, about 80% should be positive. After that, you will separate calibration from discrimination, look at why models become miscalibrated, and learn to measure and repair it. The central idea to carry forward is that predict_proba gives you a candidate probability. Whether it is a probability is something you check.
Exercise
A linear support vector machine and a logistic regression have the same AUC on a test set. You pass the SVM margin through expit and compare both outputs with observed positive rates in score bins. The logistic regression bins match closely. The SVM bins do not. Explain why the AUC values are equal but the bins differ, and say which model you could use today for a cost-based threshold rule such as "flag when p > 1/51".
Show answer
AUC depends only on the order of the scores, and expit is a monotonic function, so it cannot change the ranking. The two models rank examples about equally well. The bin comparison depends on magnitude. The SVM margin was never fitted to match positive rates, so a sigmoid of it does not give the right numbers. The logistic regression was trained with log loss, so its outputs are close to the observed rates. For a threshold rule that depends on magnitude, use the logistic regression. You could use the SVM only after fitting a calibration step on held-out data.
Exercise
A model outputs a top-class probability of 0.97 for 90% of its test predictions, but only 85% of its predictions are correct. Is the model well calibrated? Name the failure and one consequence for a deployed system.
Show answer
No. Its confidence is higher than its accuracy, so it is overconfident. If the system sends only low-confidence cases to a human reviewer, almost no cases are sent, and many errors pass through unchecked.