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

;;;; Nonparametric Models: k-Nearest Neighbors (Section 19.7)

;;; The examples are those of a learning problem, alists of
;;; (attribute . value).  Numeric attributes contribute their squared
;;; difference to the distance, and other attributes 1 when they differ.

(defun example-distance (e1 e2 attributes)
  "The Euclidean distance between two examples, on ATTRIBUTES."
  (sqrt (sum attributes
             #'(lambda (a)
                 (let ((x (attribute-value a e1))
                       (y (attribute-value a e2)))
                   (cond ((and (numberp x) (numberp y)) (square (- x y)))
                         ((equal x y) 0)
                         (t 1)))))))

(defstruct knn-hypothesis k examples attributes goal)

(defun nearest-neighbors-learning (problem &key (k 1))
  "The hypothesis of k-nearest-neighbors is just the training examples."
  (make-knn-hypothesis :k k
                       :examples (learning-problem-examples problem)
                       :attributes (learning-problem-attributes problem)
                       :goal (first (learning-problem-goals problem))))

(defun nearest-neighbors (h e)
  "The K examples of the hypothesis that are nearest to E."
  (let ((sorted (sort (copy-list (knn-hypothesis-examples h)) #'<
                      :key #'(lambda (x) (example-distance
                                          x e (knn-hypothesis-attributes h))))))
    (subseq sorted 0 (min (knn-hypothesis-k h) (length sorted)))))

(defun plurality-value (values)
  "The most common element of VALUES (the first one met, on ties)."
  (the-biggest #'(lambda (v) (count v values :test #'equal))
               (remove-duplicates values :test #'equal :from-end t)))

(defun knn-predict (h e)
  "The performance element of k-NN: the plurality class of the K nearest
  examples, or their average value when the goal is numeric."
  (let* ((goal (knn-hypothesis-goal h))
         (values (mapcar #'(lambda (x) (attribute-value goal x))
                         (nearest-neighbors h e))))
    (list (if (attribute-values goal)
              (plurality-value values)
            (average values)))))
