PasteRack.org
Paste # 47300
2018-11-11 19:43:17

Fork as a new paste.

Paste viewed 2145 times.


Embed:

  1. #lang racket
  2.  
  3. (provide  bayes set-prob-computer!)
  4.  
  5. ; probability of A given a list of B's;
  6. ;   start with an initial P(A)
  7. ;   update it with the first B
  8. ;     use that result as the new P(A) and update it with the second B...
  9. ;
  10. ; This algorithm gives me results that are sometimes WAY larger than 1, which seems wrong to me...
  11.  
  12.  
  13. ;           P(B|A) P(A)
  14. ; P(A|B) = --------------
  15. ;            P(B)
  16. (define (bayes a b-list [p-a (P a)])
  17.   (if (empty? b-list)
  18.     p-a
  19.     (let ([b (first b-list)])
  20.       (bayes a
  21.              (rest b-list)
  22.              (/
  23.                (* (P b a)
  24.                   p-a)
  25.                (P b))))))
  26.  
  27.  
  28.  
  29.  
  30.  
  31. (define probablitliy-cache  (make-hash))
  32. (define prob-compute (λ (c) (cons 0 1)))
  33. (define (set-prob-computer! proc) (set! prob-compute proc)) ; yeah yeah I know
  34.  
  35. (define (P x . y)
  36.   (let* ([c (if (empty? y) x (cons x (first y)))]
  37.          [prob (hash-ref! probablitliy-cache c
  38.                           (thunk (prob-compute c)))]
  39.  
  40.          [res (max 0.0000001  ; hitherto unseen conditions shouldn't totally trash our results
  41.                   (/ (mcar prob) (mcdr prob)))])
  42.  
  43.     (if (> res 1.0)
  44.       (raise 'impossible-probability)
  45.       res)))
  46.  
  47.  
  48.  
  49. (module* main #f
  50.   (define test-probs '((fruit . (461   . 59494)) ; percentage of files that are fruit
  51.                        (food  . (32327 . 59494)) ; percentage of files that food
  52.                        (tasty . (8662  . 59494)) ; percentage of files that are tasty
  53.  
  54.                        ((fruit . tasty) . (390  . 8662))  ; percentage of tasty things that are fruit
  55.                        ((food  . tasty) . (8644 . 8662))  ; percentage of tasty things that food
  56.                        ((fruit . food)  . (461  . 32327)) ; percentage of food things that are fruit
  57.                        ))
  58.   (define (cons-to-mcons c)
  59.     (mcons (car c) (cdr c)))
  60.  
  61.   (set-prob-computer! (λ (c) (cons-to-mcons (cdr (assoc c test-probs)))))
  62.  
  63.   (printf "Probability that fruit is edible         : ~a~n" (bayes 'food '(fruit)))
  64.   (printf "Probability that an edible fruit is tasty: ~a~n" (bayes 'tasty '(fruit food))))

=>