BayesNetworks

From J Wiki
Jump to navigation Jump to search

Useful: a probability dictionary.

Features:

  • history retention;
  • no initialization, put works immediately;
  • unresolved indecision---long non-conflicting names or new locale?
  • lovely dictionary display;
  • Another associative array;
  • keys have rank 1 or higher;
  • non-entries default to i.0 .

To do:

  • implement a Bayes solver that intelligently reads dictionary keys to solve for unknown conditional probabilities.

Implementation:

dictionary_fix_key=: ,^:('' -: $)
dictionary_initialize=: 3 : 'dictionary_warehouse_=: 2 0$a:'
dictionary_keys=: 3 : '{. dictionary_warehouse_'
dictionary_values=: 3 : '{: dictionary_warehouse_'
dictionary_boolean=: 3 : '(< = dictionary_keys)@:dictionary_fix_key y'
dictionary_index=: I.@:dictionary_boolean
dictionary_getall=: dictionary_boolean # dictionary_values
dictionary_get=: >@:{.@:dictionary_getall
dictionary_items=: 3 :'|:dictionary_warehouse_'
dictionary_compress=: 3 :'EMPTY[dictionary_warehouse_=:(#~"1 ~:@:{.)dictionary_warehouse_'

dictionary_put=: 4 : 0
x=. dictionary_fix_key x
dictionary_get :: dictionary_initialize x
dictionary_warehouse_=: dictionary_warehouse_ ,.~ x;y
y
)
G=:dictionary_get
GA=:1 :'dictionary_get x'
P=:dictionary_put

Example: Orphans R11.1

   NB. Problem:  find P(c|+) the probability of cancer (c) given positive (+) test
   NB. install given and trivially computed probabilities
   '-.c'P-.'c'P 1r100      NB. P(well) is -. P(cancer)
99r100
   '+|-.c'P-.'-|-.c'P 4r5
1r5
   '-|c'P-.'+|c'P 1r10     NB. more binary possibilities
9r10
   '+|c'P'Whoops!'
Whoops!
   '-|c'P-.'+|c'P 9r10
1r10
   dictionary_items''     NB. transposed dictionary
┌─────┬───────┐
│-|c  │1r10   │
├─────┼───────┤
│+|c  │9r10   │
├─────┼───────┤
│+|c  │Whoops!│
├─────┼───────┤
│-|c  │9r10   │
├─────┼───────┤
│+|c  │1r10   │
├─────┼───────┤
│+|-.c│1r5    │
├─────┼───────┤
│-|-.c│4r5    │
├─────┼───────┤
│-.c  │99r100 │
├─────┼───────┤
│c    │1r100  │
└─────┴───────┘

   NB. P(c|+)P(+) = P(+|c)P(c)   quasi-algebraic statement of Bayes' law.
   NB. Need P(+)

   f=: G;._2   NB. Yes!  An adverb would be even better.
   '+'P(f'+|c +|-.c ')+/ .*f'c -.c '  NB. probability to test positive
207r1000

   'c|+' P '+'GA %~ */f'+|c c ' NB. Probability of cancer given this positive test
1r23

   assert (f '+ c ') =/ .* f 'c|+ +|c '   NB. Bayes' law holds.

   NB. finished

   NB. With rank 0 keys,  G'c' succeeds whereas G;._2'c ' fails.
   NB. In this implementation, both succeed.