Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 53

One-Class SVM

Learn a boundary around the normal rows and treat anything outside that boundary as an anomaly. One example is on this page.

Intermediate12 min
One-Class SVM MahiDev

What You Will Learn

  • Idea
  • Example
  • When to use it

Idea

One-class SVM sees examples of the normal class only. It learns a boundary that encloses them in a kernel space. A new row inside the boundary is normal, scored 1. A row outside is an anomaly, scored -1. nu is an upper bound on the fraction of training rows left outside.

Example

python
import numpy as np
from sklearn.svm import OneClassSVM

rng = np.random.default_rng(0)
normal = rng.normal(loc=0, scale=0.1, size=(20, 2))
X = np.vstack([normal, [[5.0, 5.0]]])
pred = OneClassSVM(nu=0.1, gamma="scale").fit_predict(X)
print(f"last point: {int(pred[-1])}")
print(f"anomalies: {int((pred == -1).sum())}")

Output:

text
last point: -1
anomalies: 1

When to use it

  • Use it when you have many normal rows and almost no labelled anomalies.
  • Scale the inputs. The boundary is built from distances.
  • nu too high treats normal rows as anomalies. Too low misses the odd ones.

Loading playground…