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

;;;; Ensemble Learning (Section 19.8) and Online Learning

;;; Random forests, boosting with decision stumps, and the weighted-majority
;;; algorithm, on learning problems with a single discrete goal.

;;;; Random Forests

(defstruct random-forest trees goal)

(defun random-forest-learning (problem &key (n-trees 10) n-attributes)
  "Learn N-TREES decision trees, each from a bootstrap sample of the
  examples and a random subset of N-ATTRIBUTES attributes (by default, the
  square root of their number)."
  (let* ((examples (learning-problem-examples problem))
         (attributes (learning-problem-attributes problem))
         (goal (first (learning-problem-goals problem)))
         (m (or n-attributes (max 1 (round (sqrt (length attributes)))))))
    (make-random-forest
     :goal goal
     :trees (loop repeat n-trees
                  collect (let ((sample (sample-with-replacement (length examples) examples)))
                            (dtl sample (sample-without-replacement m attributes) goal
                                 (majority sample goal)))))))

(defun random-forest-predict (forest e)
  "The plurality vote of the trees of the forest."
  (list (plurality-value
         (or (remove nil (mapcar #'(lambda (tree) (first (dtpredict tree e)))
                                 (random-forest-trees forest)))
             (list nil)))))

;;;; Decision Stumps on Weighted Examples

;;; A stump tests a single attribute: it is (attribute . alist of
;;; (value . class)).

(defun weighted-plurality (examples weights goal)
  "The goal value with the largest total weight in EXAMPLES."
  (the-biggest #'(lambda (v)
                   (sum (mapcar #'(lambda (e w) (if (eq (attribute-value goal e) v) w 0))
                                examples weights)))
               (attribute-values goal)))

(defun stump-learning (examples weights attributes goal)
  "The decision stump with the smallest weighted error on EXAMPLES."
  (let ((default (weighted-plurality examples weights goal)))
    (the-smallest
     #'(lambda (stump) (weighted-error stump #'stump-predict examples weights goal))
     (mapcar #'(lambda (a)
                 (cons a (mapcar #'(lambda (v)
                                     (let ((subset (remove-if-not
                                                    #'(lambda (pair)
                                                        (eq (attribute-value a (car pair)) v))
                                                    (mapcar #'cons examples weights))))
                                       (cons v (if subset
                                                   (weighted-plurality (mapcar #'car subset)
                                                                       (mapcar #'cdr subset)
                                                                       goal)
                                                 default))))
                                 (attribute-values a))))
             attributes))))

(defun stump-predict (stump e)
  (list (cdr (assoc (attribute-value (car stump) e) (cdr stump)))))

(defun weighted-error (h predict examples weights goal)
  "The total weight of the examples that H misclassifies."
  (sum (mapcar #'(lambda (e w)
                   (if (eq (first (funcall predict h e)) (attribute-value goal e)) 0 w))
               examples weights)))

;;;; Boosting [Figure 19.25]

(defstruct boosted-hypothesis hypotheses weights predict goal)

(defun adaboost (problem learner predict K)
  "Boost the weak LEARNER, a function of the examples, their weights, the
  attributes and the goal that returns a hypothesis whose performance
  element is PREDICT, for K rounds.  The result is a weighted-majority
  hypothesis, whose performance element is BOOSTED-PREDICT."
  (let* ((examples (learning-problem-examples problem))
         (attributes (learning-problem-attributes problem))
         (goal (first (learning-problem-goals problem)))
         (n (length examples))
         (w (make-list n :initial-element (/ 1.0 n)))
         (hs nil) (zs nil))
    (loop repeat K
          do (let* ((h (funcall learner examples w attributes goal))
                    (err (weighted-error h predict examples w goal)))
               (when (> err 0.5) (return))
               (push h hs)
               (when (zerop err)          ; a perfect hypothesis outvotes the others
                 (push most-positive-single-float zs)
                 (return))
               (let ((delta (/ err (- 1 err))))
                 (setf w (normalize-vector
                          (mapcar #'(lambda (e wj)
                                      (if (eq (first (funcall predict h e))
                                              (attribute-value goal e))
                                          (* wj delta)
                                        wj))
                                  examples w)))
                 (push (log (/ (- 1 err) err)) zs))))
    (make-boosted-hypothesis :hypotheses (reverse hs) :weights (reverse zs)
                             :predict predict :goal goal)))

(defun boosted-predict (h e)
  "The class with the largest total weight of the hypotheses that vote for it."
  (let ((votes (mapcar #'(lambda (hk) (first (funcall (boosted-hypothesis-predict h) hk e)))
                       (boosted-hypothesis-hypotheses h))))
    (list (the-biggest #'(lambda (v)
                           (sum (mapcar #'(lambda (vote z) (if (eq vote v) z 0))
                                        votes (boosted-hypothesis-weights h))))
                       (attribute-values (boosted-hypothesis-goal h))))))

;;;; The Weighted-Majority Algorithm (online learning)

(defun weighted-majority (experts examples goal &key (beta 0.5))
  "Predict the goal of each example in turn with the weighted vote of the
  EXPERTS (functions of an example), then multiply by BETA the weight of
  every expert that was wrong.  Returns the number of mistakes, the final
  weights, and the number of mistakes of each expert."
  (let ((weights (make-list (length experts) :initial-element 1))
        (expert-mistakes (make-list (length experts) :initial-element 0))
        (mistakes 0))
    (dolist (e examples)
      (let* ((predictions (mapcar #'(lambda (expert) (funcall expert e)) experts))
             (truth (attribute-value goal e))
             (guess (the-biggest #'(lambda (v)
                                     (sum (mapcar #'(lambda (p w) (if (eq p v) w 0))
                                                  predictions weights)))
                                 (attribute-values goal))))
        (unless (eq guess truth) (incf mistakes))
        (setf weights (mapcar #'(lambda (p w) (if (eq p truth) w (* w beta)))
                              predictions weights)
              expert-mistakes (mapcar #'(lambda (p m) (if (eq p truth) m (+ m 1)))
                                      predictions expert-mistakes))))
    (values mistakes weights expert-mistakes)))

;;;; Ensembles of Different Learners (Section 19.8)

(defstruct ensemble hypotheses predictors)

(defun ensemble-learning (problem learners)
  "Learn a hypothesis from PROBLEM with each of the LEARNERS, a list of
  (learning-function . performance-element) pairs, e.g.
  (decision-tree-learning . dtpredict).  The ensemble predicts by the
  plurality vote of the hypotheses (ENSEMBLE-PREDICT)."
  (make-ensemble :hypotheses (mapcar #'(lambda (learner) (funcall (car learner) problem))
                                     learners)
                 :predictors (mapcar #'cdr learners)))

(defun ensemble-predict (ensemble e)
  "The prediction made by the most hypotheses of the ensemble (the first
  learner's, on ties)."
  (plurality-value (mapcar #'(lambda (h predict) (funcall predict h e))
                           (ensemble-hypotheses ensemble)
                           (ensemble-predictors ensemble))))

;;;; Resampling by Weights (weighted-sample-with-replacement is in
;;;; uncertainty/algorithms/random-variables.lisp)

(defun weighted-replicate (seq weights n)
  "N elements of SEQ, each repeated a number of times proportional to its
  weight: the whole parts of weight * N deterministically, and the
  remaining elements drawn at random according to the fractional parts.
  E.g., (weighted-replicate '(a b c) '(1 2 1) 4) is (A B B C)."
  (let* ((total (sum weights))
         (shares (mapcar #'(lambda (w) (/ (* w n) total)) weights))
         (wholes (mapcar #'floor shares))
         (fractions (mapcar #'(lambda (share whole) (- share whole)) shares wholes))
         (rest (- n (sum wholes))))
    (append (loop for x in seq
                  for k in wholes
                  append (make-list k :initial-element x))
            (if (> rest 0)
                (weighted-sample-with-replacement rest seq fractions)
              nil))))
