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

;;;; Model Selection by Cross-Validation [Figure 19.8]

;;; A learner is a function of a size (the complexity of the model, e.g.
;;; the k of k-nearest-neighbors) and a list of examples, which returns a
;;; hypothesis; PREDICT is the performance element of that hypothesis, and
;;; GOALS are the goal attributes of the examples.

(defun error-rate (h predict examples goals)
  "The fraction of EXAMPLES that the hypothesis H misclassifies."
  (- 1 (accuracy h predict examples goals)))

(defun cross-validation (learner size examples k predict goals)
  "The average error rate on the validation sets of K-fold cross-validation:
  each fold in turn is the validation set, and the other examples are the
  training set."
  (let ((n (length examples))
        (errs 0))
    (dotimes (i k)
      (let* ((start (floor (* i n) k))
             (end (floor (* (+ i 1) n) k))
             (validation-set (subseq examples start end))
             (training-set (append (subseq examples 0 start) (subseq examples end))))
        (incf errs (error-rate (funcall learner size training-set)
                               predict validation-set goals))))
    (/ errs k)))

(defun shuffle-list (list)
  "A random permutation of LIST."
  (let ((v (coerce list 'vector)))
    (loop for i from (- (length v) 1) downto 1
          do (rotatef (aref v i) (aref v (random (+ i 1)))))
    (coerce v 'list)))

(defun model-selection (learner examples k predict goals
                        &key (max-size 20) (patience 3) (test-fraction 1/4))
  "Partition the examples at random into a training and a test set, find
  the size with the lowest K-fold cross-validation error on the training
  set, growing the size until the error has not improved for PATIENCE
  sizes (the error is starting to increase), and return the hypothesis of
  that size learned from the whole training set, its error rate on the
  test set, and the best size."
  (let* ((shuffled (shuffle-list examples))
         (n-test (round (* test-fraction (length examples))))
         (test-set (subseq shuffled 0 n-test))
         (training-set (subseq shuffled n-test))
         (err (make-array (+ max-size 1) :initial-element nil))
         (best-size 1))
    (loop for size from 1 to max-size
          do (setf (aref err size)
                   (cross-validation learner size training-set k predict goals))
             (when (< (aref err size) (aref err best-size))
               (setf best-size size))
          until (>= (- size best-size) patience))
    (let ((h (funcall learner best-size training-set)))
      (values h (error-rate h predict test-set goals) best-size))))
