;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: learning/algorithms/svm.lisp

;;;; Support Vector Machines (Section 19.7.5)

;;; The examples are vectors (lists of numbers) XS; for classification
;;; their labels YS are +1 or -1, for regression real numbers.  A kernel is
;;; a function of two vectors.

(defun linear-kernel (x y) (dot-product x y))

(defun make-polynomial-kernel (degree)
  "The kernel K(x, y) = (1 + x.y)^DEGREE."
  #'(lambda (x y) (expt (+ 1 (dot-product x y)) degree)))

(defun make-rbf-kernel (gamma)
  "The Gaussian kernel K(x, y) = exp(-GAMMA |x - y|^2)."
  #'(lambda (x y) (exp (- (* gamma (sum (mapcar #'(lambda (a b) (square (- a b))) x y)))))))

(defun gram-matrix (kernel xs)
  (let* ((n (length xs))
         (k (make-array (list n n))))
    (loop for x in xs
          for i from 0
          do (loop for y in xs
                   for j from 0
                   do (setf (aref k i j) (funcall kernel x y))))
    k))

;;;; Classification

(defstruct svm alphas b xs ys kernel)

(defun svm-learning (xs ys &key (kernel #'linear-kernel) (c 1.0) (tolerance 1e-6)
                             (max-iterations 1000))
  "The maximum-margin separator of the examples XS with labels YS: the
  solution of the dual problem, maximize sum_j alpha_j - 1/2 sum_jk
  alpha_j alpha_k y_j y_k K(x_j, x_k) subject to 0 <= alpha_j <= C and
  sum_j alpha_j y_j = 0 (Equation 19.11, with the soft margin C), by
  sequential minimal optimization: repeatedly optimize a pair of alphas
  analytically, keeping the others fixed.  The second alpha of a pair is
  the one with the largest error difference, then the others in turn."
  (let* ((n (length xs))
         (y (coerce ys 'vector))
         (k (gram-matrix kernel xs))
         (alpha (make-array n :initial-element 0))
         (b 0))
    (flet ((err (i)
             (- (+ b (loop for j from 0 below n
                           sum (* (aref alpha j) (aref y j) (aref k j i))))
                (aref y i))))
      (dotimes (iteration max-iterations)
        (let ((changed 0))
          (dotimes (i n)
            (let ((ei (err i)))
              (when (or (and (< (* (aref y i) ei) (- tolerance)) (< (aref alpha i) c))
                        (and (> (* (aref y i) ei) tolerance) (> (aref alpha i) 0)))
                (dolist (j (stable-sort (remove i (iota n)) #'>
                                 :key #'(lambda (j) (abs (- ei (err j))))))
                  (let* ((ej (err j))
                         (ai (aref alpha i)) (aj (aref alpha j))
                         (low (if (/= (aref y i) (aref y j))
                                  (max 0 (- aj ai))
                                (max 0 (- (+ ai aj) c))))
                         (high (if (/= (aref y i) (aref y j))
                                   (min c (+ c (- aj ai)))
                                 (min c (+ ai aj))))
                         (eta (- (* 2 (aref k i j)) (aref k i i) (aref k j j))))
                    (when (and (> (- high low) 1e-12) (< eta 0))
                      (let ((new-aj (min high (max low (- aj (/ (* (aref y j) (- ei ej)) eta))))))
                        (when (> (abs (- new-aj aj)) 1e-9)
                          (let* ((new-ai (+ ai (* (aref y i) (aref y j) (- aj new-aj))))
                                 (b1 (- b ei (* (aref y i) (- new-ai ai) (aref k i i))
                                        (* (aref y j) (- new-aj aj) (aref k i j))))
                                 (b2 (- b ej (* (aref y i) (- new-ai ai) (aref k i j))
                                        (* (aref y j) (- new-aj aj) (aref k j j)))))
                            (setf b (cond ((< 0 new-ai c) b1)
                                          ((< 0 new-aj c) b2)
                                          (t (/ (+ b1 b2) 2)))
                                  (aref alpha i) new-ai
                                  (aref alpha j) new-aj)
                            (incf changed)
                            (return))))))))))
          (when (zerop changed) (return)))))
    (make-svm :alphas (coerce alpha 'list) :b b :xs xs :ys ys :kernel kernel)))

(defun svm-score (h x)
  "sum_j alpha_j y_j K(x_j, x) + b."
  (+ (svm-b h)
     (loop for alpha in (svm-alphas h)
           for xj in (svm-xs h)
           for yj in (svm-ys h)
           unless (zerop alpha)
             sum (* alpha yj (funcall (svm-kernel h) xj x)))))

(defun svm-predict (h x)
  "The class, +1 or -1, of the vector X."
  (if (>= (svm-score h x) 0) 1 -1))

(defun svm-weights (h)
  "The weight vector w = sum_j alpha_j y_j x_j of a linear SVM."
  (reduce #'(lambda (w v) (mapcar #'+ w v))
          (mapcar #'(lambda (alpha xj yj) (mapcar #'(lambda (x) (* alpha yj x)) xj))
                  (svm-alphas h) (svm-xs h) (svm-ys h))))

(defun support-vectors (h)
  "The examples with a nonzero alpha."
  (loop for alpha in (svm-alphas h)
        for x in (svm-xs h)
        when (> alpha 1e-6) collect x))

;;;; Regression

;;; Support vector regression fits f(x) = sum_j beta_j K'(x_j, x) with the
;;; epsilon-insensitive loss: the errors within EPSILON cost nothing.  The
;;; bias is folded into the kernel, K' = K + 1, so the dual problem,
;;; minimize 1/2 sum_jk beta_j beta_k K'(x_j, x_k) - sum_j y_j beta_j
;;; + epsilon sum_j |beta_j| subject to -C <= beta_j <= C, has no equality
;;; constraint, and is solved by coordinate descent: each beta_j has a
;;; closed-form optimum, given the others.

(defstruct svr betas xs kernel)

(defun svr-learning (xs ys &key (kernel #'linear-kernel) (c 1.0) (epsilon 0.1)
                             (max-iterations 1000) (tolerance 1e-9))
  "Support vector regression of the values YS on the vectors XS."
  (let* ((n (length xs))
         (y (coerce ys 'vector))
         (k (gram-matrix #'(lambda (a b) (+ 1 (funcall kernel a b))) xs))
         (beta (make-array n :initial-element 0)))
    (dotimes (iteration max-iterations)
      (let ((delta 0))
        (dotimes (i n)
          (let* ((z (- (aref y i)
                       (loop for j from 0 below n
                             unless (= j i) sum (* (aref k i j) (aref beta j)))))
                 (shrunk (cond ((> z epsilon) (- z epsilon))
                               ((< z (- epsilon)) (+ z epsilon))
                               (t 0)))
                 (new (max (- c) (min c (/ shrunk (aref k i i))))))
            (setf delta (max delta (abs (- new (aref beta i))))
                  (aref beta i) new)))
        (when (< delta tolerance) (return))))
    (make-svr :betas (coerce beta 'list) :xs xs :kernel kernel)))

(defun svr-predict (h x)
  "The value predicted for the vector X."
  (loop for beta in (svr-betas h)
        for xj in (svr-xs h)
        sum (* beta (+ 1 (funcall (svr-kernel h) xj x)))))
