(defvar *r* (make-random-state t)) (defmacro rand () (let ((n most-positive-fixnum)) `(coerce (/ (random ,n *r*) ,n) 'float))) (defstruct relation cols name klass want (instances 0)) (defstruct col name f) (defun cols (l) (let (out) (dolist (field l out) (push (make-col :name field) out)))) (defun train (rel l) (incf (relation-instances rel)) (setf (relation-cols rel) (mapcar 'train1 l (relation-cols rel)))) (defun train1 (val col) (setf (col-f col) (inc val (col-f col))) col) (defun inc (key counts &key (n 1) (test 'equalp)) (let ((old (cdr (assoc key counts :test test)))) (if old (setf (cdr (assoc key counts :test test)) (+ n (or old 0))) (push (cons key n) counts)) counts)) (defun l () (load "bayes.lsp")) (defun sort-data (data) (format t "b4 [~a]~%" data) (sort data #'< :key #'car) (format t "2b [~a]~%" data)) (defun row0(one klass about) (let* ((tmp (nth (1- klass) one)) (score (+ (rand) (cdr (assoc tmp about))))) `(,score ,tmp ,one))) (defun klass-pos (klass arity) (cond ((null klass) arity) ((< klass 0) (+ arity 1 klass)) (t klass))) (defstruct row cells class score) (defun relation (&key (name 'relation) about klass names data) (print `(data ,data)) (let* ((arity (length names)) (klass1 (klass-pos klass arity)) (r (make-relation :name name :klass klass1 :cols (cols names))) (data1 '()) (n 0) (total 0) (enough 0.2) ) (dolist (one data) (incf n) (let ((new (row0 one klass1 about))) (setf total (+ total (car new))) (push new data1))) (sort data1 #'> :key #'car) (setf done 0) (dolist (one data) (setf done (+ done (car one))) (setf best (<= (/ done total) 0.1) ( (return-from relation data1) (dolist (one data1 r) (incf n) (if (eql (length one) arity) (train r one) (error "~a at ~a found ~a fileds, expected ~a~n" name n (length one) arity))))) (defun d2() (let* ((a '(4.3 a aa )) (b '(2.7 aa cc )) (c '(1.9 aa cc)) (l `(,a ,b ,c))) (sort-data l))) ; #'< :key #'car))) (defun d3() (let* ((a '(4.7071676 HAPPY (TIM 19 HAPPY))) (b '(4.3655496 HAPPY (TIM 29 HAPPY))) (c '(2.3062155 SAD (TOM 29 SAD))) (l `(,a ,b ,c))) (sort l #'< :key #'car))) (defun d1 () (relation :name 'golf :about '((happy . 4) (sad . 2)) :names '(name age mood) :data '((tim 19 happy) (tim 29 happy) (tom 29 sad))))