def main pi = [0.1, 0.4, 0.5]
theta = [[0.8, 0.2], [0.6, 0.4], [0.3, 0.7]]
n = 100 nss = make_trial(n, pi, theta) p nss
ps, tss = infer_params_supervised(nss)
ps.size.times do |i| printf("%2d: %.2f: %s\n", i, ps[i], tss[i].map {|t| sprintf('%.2f', t)}.join(', ')) end end
def infer_params_supervised(nss) n = nss.flatten.sum nis = nss.map(&:sum)
pi = nis.map do |ni| ni.to_f / n end
theta = nss.each_with_index.map do |ns, i| ns.map do |nik| nik.to_f / nis[i] end end
return pi, theta end
def make_trial(n, pi, theta) c = theta.size m = theta[0].size nss = Array.new(c) { Array.new(m) {0} } n.times do st = pick_dice(pi) xt = roll_dice(theta[st]) nss[st][xt] += 1 end return nss end
def pick_dice(pi) random_choise(pi) end
def roll_dice(theta) random_choise(theta) end
def random_choise(probs) r = rand probs.each_with_index do |p, i| return i if r < p r -= p end return probs.size - 1 end
class Array def sum self.inject(:+) end end
main
|