Skip to content

Instantly share code, notes, and snippets.

@dmarx
Created April 3, 2017 22:56
Show Gist options
  • Select an option

  • Save dmarx/fc40b8e47af19e6e5a3aa04e21cc51aa to your computer and use it in GitHub Desktop.

Select an option

Save dmarx/fc40b8e47af19e6e5a3aa04e21cc51aa to your computer and use it in GitHub Desktop.
Demonstration of a Chinese Restaurant Process, with an optional parameter to push the tables towards a uniform distribution rather than dirichlet (i.e. preferential attachment)
# chinese restuarant process
chinese_restaurant = function(n, uniform=FALSE){
tables = c(1) # running counts of people at tables. Start by seating first person at their own table
U = runif(n)
for (i in 2:n){
if(U[i]<1/i){
tables = c(tables, 1)
} else {
p = tables/(i) # sum(tables) = i-1
# Invert probabilities for more uniform allocation
if (uniform & (length(p)>1)) p = 1-p
ix = sample(length(tables), 1, prob=p)
tables[ix] = tables[ix]+1
}
}
tables
}
sort(chinese_restaurant(1e2), decreasing=TRUE)
sort(chinese_restaurant(1e4, uniform=TRUE), decreasing=TRUE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment