Skip to content

Instantly share code, notes, and snippets.

@LFY
Created November 14, 2011 09:27
Show Gist options
  • Save LFY/1363596 to your computer and use it in GitHub Desktop.
Save LFY/1363596 to your computer and use it in GitHub Desktop.
Inside/Outside algorithm specialized to simple example
(import (printing)
(_srfi :1))
(define start-params
'(1/3 1/3 1/3))
(define (likelihood params)
(* (list-ref params 0)
(list-ref params 0)
(list-ref params 1)
(list-ref params 2)))
(define (exp-counts idx params)
;; Rationale:
;; There are always 2 occurrences of S -> r S, 1 of S -> g S, and 1 of S -> b.
(cond [(equal? 0 idx)
(*
(/ 1 (likelihood params))
(* 2 (likelihood params)))]
[(equal? 1 idx)
(*
(/ 1 (likelihood params))
(* 1 (likelihood params)))]
[(equal? 2 idx)
(*
(/ 1 (likelihood params))
(* 1 (likelihood params)))]))
(define (normalize params)
(let* ([factor (apply + params)])
(map (lambda (p) (/ p factor)) params)))
(define (io-iteration params)
(let* ([exp-counts (map (lambda (i) (exp-counts i params)) (iota (length params)))]
)
(normalize exp-counts)))
(define (io-n-iter n start)
(cond [(= 0 n) start]
[else
(begin
(print "current params ~s" start)
(io-n-iter (- n 1) (io-iteration start)))]))
(print (io-n-iter 10 start-params))
;; output:
;; current params (1/3 1/3 1/3)
;; current params (1/2 1/4 1/4)
;; current params (1/2 1/4 1/4)
;; current params (1/2 1/4 1/4)
;; current params (1/2 1/4 1/4)
;; current params (1/2 1/4 1/4)
;; current params (1/2 1/4 1/4)
;; current params (1/2 1/4 1/4)
;; current params (1/2 1/4 1/4)
;; current params (1/2 1/4 1/4)
;; (1/2 1/4 1/4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment