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

;;;; Naive Bayes Models (Section 20.2.2)

;;; The class is the (single) goal of a learning problem.  An attribute
;;; with a list of values is discrete, and P(value | class) is estimated
;;; from counts with Laplace (add-one) smoothing; an attribute without
;;; values is real-valued, with a Gaussian P(value | class).

(defstruct nb-hypothesis
  goal
  priors                ; alist of (class . P(class))
  models)               ; alist of (class . alist of (attribute . model))

(defun naive-bayes-learning (problem)
  "Estimate the prior of each class and the distribution of each attribute
  given the class, from the examples of PROBLEM."
  (let* ((examples (learning-problem-examples problem))
         (goal (first (learning-problem-goals problem)))
         (classes (remove-if-not
                   #'(lambda (c) (find c examples :key #'(lambda (e) (attribute-value goal e))))
                   (attribute-values goal))))
    (make-nb-hypothesis
     :goal goal
     :priors (mapcar #'(lambda (c)
                         (cons c (/ (count c examples
                                           :key #'(lambda (e) (attribute-value goal e)))
                                    (length examples))))
                     classes)
     :models (mapcar
              #'(lambda (c)
                  (let ((in-class (remove-if-not
                                   #'(lambda (e) (eq (attribute-value goal e) c))
                                   examples)))
                    (cons c (mapcar #'(lambda (a)
                                        (cons (attribute-name a)
                                              (attribute-model a in-class)))
                                    (learning-problem-attributes problem)))))
              classes))))

(defun attribute-model (attribute examples)
  "The distribution of ATTRIBUTE in EXAMPLES: an alist of smoothed
  probabilities for a discrete attribute, or (mean . standard-deviation)."
  (let ((values (mapcar #'(lambda (e) (attribute-value attribute e)) examples)))
    (if (attribute-values attribute)
        (mapcar #'(lambda (v)
                    (cons v (/ (+ 1 (count v values :test #'equal))
                               (+ (length values) (length (attribute-values attribute))))))
                (attribute-values attribute))
      (let ((mean (average values)))
        (cons mean (max 1e-3 (sqrt (average (mapcar #'(lambda (x) (square (- x mean)))
                                                    values)))))))))

(defun nb-log-likelihood (model value)
  (if (numberp (car model))
      ;; the log of the Gaussian density, computed directly to avoid underflow
      (let ((mean (car model)) (sd (cdr model)))
        (- (/ (square (- value mean)) (* -2 (square sd)))
           (log (* sd (sqrt (* 2 pi))))))
    (log (or (cdr (assoc value model :test #'equal)) 1))))

(defun nb-predict (h e)
  "The performance element: the class with the highest posterior
  probability, log P(class) + sum_i log P(x_i | class)."
  (list (the-biggest
         #'(lambda (c)
             (+ (log (cdr (assoc c (nb-hypothesis-priors h))))
                (sum (cdr (assoc c (nb-hypothesis-models h)))
                     #'(lambda (attribute-model)
                         (let ((value (cdr (assoc (car attribute-model) e))))
                           (if (null value)
                               0
                             (nb-log-likelihood (cdr attribute-model) value)))))))
         (mapcar #'car (nb-hypothesis-priors h)))))

(defun gaussian-naive-bayes-learning (problem)
  "Naive Bayes with a Gaussian P(value | class) for every attribute, even
  those with a list of (numeric) values, as for the iris data."
  (naive-bayes-learning
   (make-learning-problem
    :examples (learning-problem-examples problem)
    :attributes (mapcar #'(lambda (a) (list (attribute-name a)))
                        (learning-problem-attributes problem))
    :goals (learning-problem-goals problem))))

;;;; Probability Distributions Estimated by Counting

;;; A counting distribution is formed by observing values one at a time:
;;; P(o) is the count of o over the total count.  With a DEFAULT count k,
;;; every value starts with k observations (add-k, e.g., Laplace, smoothing),
;;; including a value first met when its probability is asked for.

(defstruct (counting-distribution (:constructor new-counting-distribution))
  (counts nil)       ; alist of (value . count), latest new value first
  (total 0)
  (default 0))

(defun make-counting-distribution (&optional observations (default 0))
  "A distribution that has observed the list of OBSERVATIONS."
  (let ((distribution (new-counting-distribution :default default)))
    (dolist (o observations distribution)
      (counting-distribution-add distribution o))))

(defun counting-distribution-smooth-for (distribution o)
  "Include O among the possible values, with the default count, if it is new;
  return its entry."
  (or (assoc o (counting-distribution-counts distribution) :test #'equal)
      (let ((entry (cons o (counting-distribution-default distribution))))
        (push entry (counting-distribution-counts distribution))
        (incf (counting-distribution-total distribution)
              (counting-distribution-default distribution))
        entry)))

(defun counting-distribution-add (distribution o)
  "Observe the value O once more."
  (incf (cdr (counting-distribution-smooth-for distribution o)))
  (incf (counting-distribution-total distribution))
  distribution)

(defun counting-probability (distribution o)
  "The estimate of P(O): its count over the total count."
  (let ((entry (counting-distribution-smooth-for distribution o)))
    (if (zerop (counting-distribution-total distribution))
        0
      (/ (cdr entry) (counting-distribution-total distribution)))))

(defun counting-distribution-top (distribution n)
  "The N most frequent values, as (count . value) pairs."
  (let ((pairs (stable-sort (mapcar #'(lambda (entry) (cons (cdr entry) (car entry)))
                                    (reverse (counting-distribution-counts distribution)))
                            #'> :key #'car)))
    (subseq pairs 0 (min n (length pairs)))))

(defun counting-distribution-sample (distribution)
  "A value drawn at random with probability proportional to its count."
  (let ((r (random (float (counting-distribution-total distribution) 1.0))))
    (dolist (entry (counting-distribution-counts distribution)
                   (car (first (counting-distribution-counts distribution))))
      (decf r (cdr entry))
      (when (< r 0) (return (car entry))))))
