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

;;;; Learning with Hidden Variables: the EM Algorithm (Sections 20.3.2-20.3.3)

;;;; Bayes Nets with Hidden Variables: a Naive Bayes Model with a Hidden Class

;;; The data are vectors of Boolean features (lists of 1 and 0), and the
;;; class (e.g., the bag of the candies of Section 20.3.2) is hidden.  The
;;; parameters are the K class priors WEIGHTS and THETA, where
;;; (nth f (nth i theta)) is P(feature f = 1 | class i).

(defun feature-likelihood (theta-i x)
  "P(x | class i) = prod_f theta_if^x_f (1 - theta_if)^(1 - x_f)."
  (let ((p 1))
    (loop for th in theta-i
          for xf in x
          do (setf p (* p (if (= xf 1) th (- 1 th)))))
    p))

(defun naive-bayes-em (data k &key weights theta (max-iterations 100) (epsilon 1e-4))
  "Learn the parameters of a naive Bayes model with a hidden K-valued class
  from the list DATA of Boolean vectors, by EM.  The E-step computes the
  responsibilities r_ji = P(class i | x_j), proportional to
  P(class i) prod_f P(x_jf | class i); the M-step sets the priors to the
  average responsibilities and P(feature f = 1 | class i) to the
  responsibility-weighted frequency of the feature.  WEIGHTS and THETA are
  the initial parameters (by default, uniform priors and random
  conditionals: identical classes would be a fixed point).  Stops after
  MAX-ITERATIONS, or when the log likelihood improves by less than
  EPSILON.  Returns the weights, theta and the responsibilities."
  (let* ((n (length data))
         (d (length (first data)))
         (weights (or weights (make-list k :initial-element (/ 1.0 k))))
         (theta (or theta (loop repeat k
                                collect (loop repeat d collect (+ 0.25 (random 0.5))))))
         (responsibilities nil)
         (log-likelihood nil))
    (dotimes (iteration max-iterations)
      ;; E-step
      (let ((new-log-likelihood 0))
        (setf responsibilities
              (mapcar #'(lambda (x)
                          (let* ((joint (mapcar #'(lambda (w theta-i)
                                                    (* w (feature-likelihood theta-i x)))
                                                weights theta))
                                 (total (sum joint)))
                            (incf new-log-likelihood (log total))
                            (mapcar #'(lambda (p) (/ p total)) joint)))
                      data))
        ;; M-step
        (let ((counts (loop for i from 0 below k
                            collect (sum responsibilities #'(lambda (r) (nth i r))))))
          (setf weights (mapcar #'(lambda (c) (/ c n)) counts)
                theta (loop for i from 0 below k
                            for c in counts
                            collect (loop for f from 0 below d
                                          collect (min (- 1 1e-9)
                                                       (max 1e-9
                                                            (/ (loop for r in responsibilities
                                                                     for x in data
                                                                     sum (* (nth i r) (nth f x)))
                                                               c)))))))
        (when (and log-likelihood
                   (< (abs (- new-log-likelihood log-likelihood)) epsilon))
          (return))
        (setf log-likelihood new-log-likelihood)))
    (values weights theta responsibilities)))

;;;; Learning Hidden Markov Models: the Baum-Welch Algorithm

;;; The HMMs are those of uncertainty/algorithms/hmm.lisp: the prior is
;;; P(X_0), and the evidence e_1 ... e_T comes at times 1 to T.

(defun hmm-log-likelihood (hmm ev)
  "log P(e_1:T) under HMM, the sum of the logs of the normalizers of the
  forward messages."
  (let ((f (hmm-prior hmm))
        (log-likelihood 0))
    (dolist (e ev log-likelihood)
      (let* ((unnormalized (mapcar #'* (hmm-sensor-vector hmm e) (hmm-predict hmm f)))
             (total (sum unnormalized)))
        (incf log-likelihood (log total))
        (setf f (mapcar #'(lambda (x) (/ x total)) unnormalized))))))

(defun baum-welch (hmm ev &key (iterations 100))
  "Learn the transition model, sensor model and prior of an HMM from the
  evidence list EV, by EM starting from HMM.  The E-step computes, by
  forward-backward, the smoothed marginals gamma_t(i) = P(X_t = i | e_1:T)
  and xi_t(i, j) = P(X_t = i, X_t+1 = j | e_1:T); the M-step sets each
  parameter to its normalized expected count: the prior to gamma_0,
  T[i][j] to sum_t xi_t(i, j) / sum_t gamma_t(i), and P(e | i) to the
  sum of gamma_t(i) over the times t of evidence e over the sum over all
  times.  Returns the new HMM."
  (let ((n (length (hmm-prior hmm)))
        (big-t (length ev))
        (evidence-values (mapcar #'car (hmm-sensor hmm))))
    (dotimes (iteration iterations hmm)
      (let* ((tt (hmm-transition hmm))
             (sensor (mapcar #'(lambda (e) (hmm-sensor-vector hmm e)) ev))
             (alpha (make-array (+ big-t 1)))
             (beta (make-array (+ big-t 1)))
             (gamma (make-array (+ big-t 1)))
             (xi (make-array big-t)))
        ;; forward messages alpha_0 ... alpha_T, normalized
        (setf (aref alpha 0) (hmm-prior hmm))
        (loop for b in sensor
              for t1 from 1
              do (setf (aref alpha t1)
                       (normalize-vector (mapcar #'* b (hmm-predict hmm (aref alpha (- t1 1)))))))
        ;; backward messages beta_T ... beta_0, normalized
        (setf (aref beta big-t) (make-list n :initial-element 1))
        (loop for t1 from (- big-t 1) downto 0
              do (setf (aref beta t1)
                       (normalize-vector
                        (matrix-vector-multiply tt (mapcar #'* (nth t1 sensor)
                                                           (aref beta (+ t1 1)))))))
        (dotimes (t1 (+ big-t 1))
          (setf (aref gamma t1)
                (normalize-vector (mapcar #'* (aref alpha t1) (aref beta t1)))))
        (dotimes (t1 big-t)
          (let* ((next (mapcar #'* (nth t1 sensor) (aref beta (+ t1 1))))
                 (joint (loop for a-i in (aref alpha t1)
                              for row in tt
                              collect (mapcar #'(lambda (tij nj) (* a-i tij nj)) row next)))
                 (total (sum joint #'sum)))
            (setf (aref xi t1)
                  (mapcar #'(lambda (row) (mapcar #'(lambda (x) (/ x total)) row)) joint))))
        ;; M-step
        (let ((from-counts (loop for i from 0 below n
                                 collect (loop for t1 from 0 below big-t
                                               sum (nth i (aref gamma t1)))))
              (state-counts (loop for i from 0 below n
                                  collect (loop for t1 from 1 to big-t
                                                sum (nth i (aref gamma t1))))))
          (setf hmm
                (make-hmm
                 :prior (aref gamma 0)
                 :transition (loop for i from 0 below n
                                   collect (loop for j from 0 below n
                                                 collect (/ (loop for t1 from 0 below big-t
                                                                  sum (nth j (nth i (aref xi t1))))
                                                            (nth i from-counts))))
                 :sensor (mapcar #'(lambda (value)
                                     (cons value
                                           (loop for i from 0 below n
                                                 collect (/ (loop for e in ev
                                                                  for t1 from 1
                                                                  when (equal e value)
                                                                    sum (nth i (aref gamma t1)))
                                                            (nth i state-counts)))))
                                 evidence-values))))))))
