Sub topic 15
Decision scores and probability estimates
This chapter covers what an SVM outputs besides a class label. It explains how to read the decision score, how the probabilities are produced, and when to trust each one. It assumes you know the soft-margin SVM, support vectors, and the dual form of the decision function. You should also be comfortable with scikit-learn's SVC and with ROC curves.
The decision score
A trained SVM computes a signed number for each input and then takes its sign. In the dual form, that number is:
f(x) = Σᵢ αᵢ yᵢ K(xᵢ, x) + b
The sum runs only over support vectors, because every other αᵢ is zero. In scikit-learn, decision_function returns f(x). predict returns the class on the positive side when f(x) > 0 and the other class otherwise.
For a linear kernel, f(x) = w·x + b. The geometric distance from x to the hyperplane is f(x) / ‖w‖. A score of exactly +1 or −1 puts the point on a margin boundary. Scores between −1 and +1 fall inside the margin.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.svm import SVC
X, y = make_blobs(n_samples=100, centers=2, cluster_std=1.2, random_state=0)
clf = SVC(kernel="linear", C=1.0).fit(X, y)
scores = clf.decision_function(X)
manual = X @ clf.coef_.ravel() + clf.intercept_[0]
print("matches w.x + b:", np.allclose(scores, manual))
distance = scores / np.linalg.norm(clf.coef_)
print("closest point to the plane:", np.abs(distance).min())
labels = clf.classes_[(scores > 0).astype(int)]
print("sign rule matches predict:", np.array_equal(labels, clf.predict(X)))The same identity holds for nonlinear kernels. Here it is in the dual form with an RBF kernel. dual_coef_ stores αᵢyᵢ for each support vector.
from sklearn.metrics.pairwise import rbf_kernel
rbf = SVC(kernel="rbf", gamma=0.5, C=1.0).fit(X, y)
K = rbf_kernel(X, rbf.support_vectors_, gamma=0.5)
manual = K @ rbf.dual_coef_.ravel() + rbf.intercept_[0]
print(np.allclose(manual, rbf.decision_function(X)))With a nonlinear kernel, w lives in an implicit feature space. Dividing f(x) by a norm no longer gives a distance in the original input space. The score is still a useful ranking, and larger magnitude still means more confidence, but it is not a distance you can measure in your data.
What the score is good for
The score is not a probability, but it carries a lot of information.
- Ranking. ROC AUC and precision-recall curves need only an ordering of examples. Passing
decision_functionoutput toroc_auc_scoreis correct and costs nothing extra. - Threshold moves. Predicting positive when f(x) > t, with t not equal to 0, trades precision for recall. This is the usual fix for class imbalance or unequal error costs.
- Margin violations. Points with |f(x)| < 1 sit inside the margin. These are the ambiguous cases to review by hand.
placeholderMulticlass scores
With more than two classes, the shape of decision_function depends on the strategy. SVC trains one-vs-one classifiers internally. By default (decision_function_shape="ovr") it aggregates their votes into one column per class. Those columns are built from vote counts plus a small confidence term, so they are not raw one-vs-rest margins. With "ovo" you get one column per class pair.
| Setting | Columns for k classes | Meaning |
|---|---|---|
| `"ovr"` (default) | k | Aggregated votes with a confidence tie-breaker |
| `"ovo"` | k(k−1)/2 | Raw score of each pairwise classifier |
| `LinearSVC` | k | True one-vs-rest margins |
predict on SVC is always based on one-vs-one voting, even when the score shape is "ovr". Ties in predict can disagree with the argmax of the scores unless you set break_ties=True. That option is slower and only applies when the shape is "ovr".
Probability estimates
SVMs are not trained to model probabilities. Hinge loss is zero for any point beyond the margin, so nothing in the objective pushes scores toward calibrated values. To get probabilities, scikit-learn uses Platt scaling. It fits a sigmoid to the scores:
P(y = 1 | x) = 1 / (1 + exp(A·f(x) + B))
The parameters A and B are fit by maximum likelihood on held-out scores. Setting probability=True on SVC does the following:
- It runs an internal 5-fold cross-validation on the training data.
- It collects out-of-fold scores.
- It fits A and B on those scores.
- It refits the SVM on all data.
This makes training several times slower. It must be set before calling fit, and predict_proba raises an error otherwise. For multiclass problems, the pairwise probabilities are combined by pairwise coupling.
from sklearn.datasets import make_classification
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=600, n_features=10, flip_y=0.15,
class_sep=0.8, random_state=0)
Xtr, Xte, ytr, yte = train_test_split(X, y, random_state=0)
clf = SVC(kernel="rbf", probability=True, random_state=0).fit(Xtr, ytr)
proba = clf.predict_proba(Xte)[:, 1]
pred = clf.predict(Xte)
print("agreement of predict and proba > 0.5:", (pred == (proba > 0.5)).mean())
print("AUC from scores:", roc_auc_score(yte, clf.decision_function(Xte)))
print("Brier score of probabilities:", brier_score_loss(yte, proba))You may see predict and predict_proba > 0.5 disagree on some points. The internal cross-validation is random, so the sigmoid is fit on different scores than the final model produces. predict uses the sign of f(x), while the probabilities use the fitted sigmoid. The two can differ for points near the boundary. random_state makes the probabilities repeatable.
Calibrating without `probability=True`
CalibratedClassifierCV is a more flexible route. It wraps any classifier that has decision_function, fits the calibrator on held-out folds, and supports both "sigmoid" (Platt) and "isotonic" methods. It is also the only practical way to get probabilities from LinearSVC, which has no predict_proba.
from sklearn.calibration import CalibratedClassifierCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
base = make_pipeline(StandardScaler(), LinearSVC(C=1.0, max_iter=10000))
cal = CalibratedClassifierCV(base, method="sigmoid", cv=5).fit(Xtr, ytr)
print("Brier score:", brier_score_loss(yte, cal.predict_proba(Xte)[:, 1]))Isotonic regression is more flexible than a sigmoid, but it needs more data. It tends to overfit below roughly a thousand calibration samples.
Edge cases to remember
- Small data. Platt scaling is fit on cross-validated scores. With a few dozen samples per class, A and B are unstable.
- Class imbalance. The sigmoid reflects the class frequencies of the training data. If deployment frequencies differ, the probabilities are off. Adjust the prior or recalibrate on representative data.
- Check calibration. Plot a reliability curve with
sklearn.calibration.calibration_curveon held-out data, or compare Brier scores. - Scale before scoring. Score magnitudes depend on feature scaling, so unscaled features give unstable scores and probabilities.
Exercise
A classifier trained with SVC(probability=True) gives predict_proba of 0.48 for a test point, yet predict returns the positive class. Give one reason this can happen and say which output you would use to assign the class.
Show answer
predict uses the sign of the decision score, while predict_proba comes from a sigmoid fitted to out-of-fold scores in an internal cross-validation. The sigmoid can place the 0.5 crossing slightly away from score 0, so points near the boundary may disagree. Assign the class with predict (or by thresholding decision_function), and use predict_proba only when you need a probability value.
Exercise
Why can you pass decision_function output straight to roc_auc_score without calibrating it first?
Show answer
ROC AUC depends only on how the scores rank positive examples against negative ones. The scores do not need to be probabilities, only ordered consistently with the likelihood of the positive class.