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

;;;; Unsupervised Learning: k-Means and EM for Mixtures of Gaussians

;;; The data are points, lists of real numbers.  Both algorithms start from
;;; the farthest-first choice of K points (a random point, then each time
;;; the point farthest from those already chosen).

(defun point-distance (p q)
  (sqrt (sum (mapcar #'(lambda (x y) (square (- x y))) p q))))

(defun farthest-first-centers (points k)
  (let ((centers (list (random-element points))))
    (loop repeat (- k 1)
          do (push (the-biggest #'(lambda (p)
                                    (reduce #'min (mapcar #'(lambda (c) (point-distance p c))
                                                          centers)))
                                points)
                   centers))
    (reverse centers)))

(defun mean-point (points)
  "The componentwise average of a non-empty list of points."
  (mapcar #'(lambda (xs) (average xs)) (transpose points)))

(defun nearest-center (p centers)
  "The index of the center nearest to the point P."
  (the-smallest #'(lambda (i) (point-distance p (nth i centers)))
                (iota (length centers))))

(defun k-means (points k &key (max-iterations 100))
  "Cluster POINTS around K centers: assign each point to its nearest
  center and move each center to the mean of its points, until the
  assignment does not change.  Returns the centers and the list of the
  cluster indices of the points."
  (let* ((centers (farthest-first-centers points k))
         (assignment nil))
    (loop repeat max-iterations
          do (let ((new (mapcar #'(lambda (p) (nearest-center p centers)) points)))
               (when (equal new assignment) (return))
               (setf assignment new
                     centers (loop for i below k
                                   for c in centers
                                   collect (let ((members (loop for p in points
                                                                for a in assignment
                                                                when (= a i) collect p)))
                                             (if members (mean-point members) c))))))
    (values centers assignment)))

;;;; EM for a Mixture of Gaussians (Section 20.3.1)

;;; Each component has a weight, a mean and a vector of variances, one for
;;; each dimension (a diagonal covariance matrix).

(defun diagonal-gaussian-density (x mean variances)
  (reduce #'* (mapcar #'(lambda (xi mi vi) (gaussian-density xi mi (sqrt vi)))
                      x mean variances)))

(defun em-gaussian-mixture (points k &key (iterations 100) (min-variance 1e-3))
  "Fit a mixture of K Gaussians to POINTS by expectation maximization.
  Returns the weights, the means and the variances of the components, and
  the responsibilities (for each point, the list of the probabilities
  that it was generated by each component)."
  (let* ((dimension (length (first points)))
         (weights (make-list k :initial-element (/ 1.0 k)))
         (means (farthest-first-centers points k))
         (variances (loop repeat k collect (make-list dimension :initial-element 1.0)))
         (responsibilities nil))
    (dotimes (iteration iterations)
      ;; E step: p_ij = P(C = i | x_j), normalized over the components
      (setf responsibilities
            (mapcar #'(lambda (x)
                        (normalize-vector
                         (mapcar #'(lambda (w m v) (* w (diagonal-gaussian-density x m v)))
                                 weights means variances)))
                    points))
      ;; M step: the weights, means and variances that maximize the likelihood
      (let ((columns (transpose responsibilities)))
        (setf weights (mapcar #'(lambda (column) (/ (sum column) (length points))) columns)
              means (mapcar #'(lambda (column)
                                (let ((total (sum column)))
                                  (mapcar #'(lambda (xs) (/ (sum (mapcar #'* column xs)) total))
                                          (transpose points))))
                            columns)
              variances (mapcar #'(lambda (column mean)
                                    (let ((total (sum column)))
                                      (mapcar #'(lambda (xs mi)
                                                  (max min-variance
                                                       (/ (sum (mapcar #'(lambda (p xi)
                                                                           (* p (square (- xi mi))))
                                                                       column xs))
                                                          total)))
                                              (transpose points) mean)))
                                columns means))))
    (values weights means variances responsibilities)))
