bnp

Some older Bayesian nonparametrics research.
git clone git://git.jtobin.io/bnp.git
Log | Files | Refs | README | LICENSE

generalized_crp.r (610B)


      1 generalized_crp = function(n, a, b) {
      2   restaurant = data.frame(table = 1, customers = 1)
      3   for (j in seq(n - 1)) {
      4     restaurant = arrival(restaurant, a, b)
      5     }
      6   restaurant
      7   }
      8 
      9 arrival = function(r, a, b) {
     10   k = nrow(r)
     11   p = 1 - (b + k * a) / (sum(r$customers) + b)
     12   if (rbinom(1, 1, p)) {
     13     join_table(r, a)
     14     } else {
     15     start_table(r)
     16     }
     17   }
     18 
     19 join_table = function(r, a) {
     20   probs = r$customers / sum(r$customers)
     21   table = sample(1:nrow(r), size = 1, prob = probs)
     22   r[table, 'customers'] = r[table, 'customers'] + 1
     23   r
     24   }
     25 
     26 start_table = function(r) {
     27   rbind(r, c(nrow(r) + 1, 1))
     28   }
     29