Implement a One-Class SVM in its primal form, trained with subgradient descent, so that points outside the learned boundary are flagged as anomalies. For training points x1,…,xn the objective is
L(w,ρ)=21∥w∥2+νn1∑i=1nmax(0,ρ−w⋅xi)−ρ
where ν∈(0,1] bounds the fraction of training points treated as outliers.
Implement one_class_svm(X_train, X_test, nu=0.1, learning_rate=0.001, max_iter=2000):
- Initialize w=0 (length d) and ρ=0.
- Repeat
max_iter times, using all training points. Let A={i:ρ−w⋅xi>0} (strict inequality: a point exactly on the hinge contributes nothing) and ∣A∣ its size. Use the subgradients gw=w−νn1∑i∈Axi and gρ=νn∣A∣−1, both evaluated at the current (w,ρ), then update w←w−ηgw and ρ←ρ−ηgρ with η = learning_rate.
- For each point in
X_test compute f(x)=w⋅x−ρ and return a Python list of labels: 1 if f(x)≥0 (inlier), -1 otherwise.