1

私は CRP 問題のために Python でコードを書きました。問題自体はここにあります: http://cog.brown.edu/~mj/classes/cg168/slides/ChineseRestaurants.pdf

簡単に説明すると、レストランに入る人々を無数のテーブルに割り当てたいとします。$z_i$ がレストランに入る $i$ 番目の人に割り当てられた確率変数を表す場合、次のようになります。

$p(z_i=a|z_1,...,z_{i-1})=\frac{n_a}{i-1+\alpha} for $n_a>0$ の確率で、$i$ 番目の人はテーブル $a$ に座り、確率 $p(z_i=a|z_1,...,z_{i-1})=\frac{\alpha}{i-1+\alpha} $i$ 番目の人新しいテーブルの周りに座ります。

私のコードが正しいかどうかはよくわかりませんが、テーブルの最終的な数がどれほど少ないかに驚いています。

実装が正しいかどうか、もしそうなら改善の可能性があるかどうか誰かが言ってくれたら嬉しいです.

import numpy as np
def CRP(alpha,N):
    """Chinese Restaurant Process with alpha as concentration parameter and N 
    the number of sample"""
    #Array which will save for each i, the number of people people sitting
    #until table i
    summed=np.ones(1) #first person assigned to the first table
    for i in range(1,N):
        #A loop that assigns the people to tables

        #randind represent the random number from the interval [1,i-1+alpha]
        randind=(float(i)+alpha)*np.random.uniform(low=0.0, high=1.0, size=1)
        #update is the index for the table that the person should be placed which
        #if greater than the total number, will be placed in a new table
        update=np.searchsorted(summed,randind,side='left')
        if randind>i:
            summed=np.append(summed,i+1)
        else:
            zerovec=np.zeros(update)
            onevec=np.ones(summed.size-update)
            summed+=np.append(zerovec,onevec)
    #This part converts summed array to tables array which indicates the number
    #of persons assigned to that table
    tables=np.zeros(summed.size)
    tables[0]=summed[0]
    for i in range(1,summed.size):
        tables[i]=summed[i]-summed[i-1]
    return tables
a=CRP(0.9999,1000)
print a
4

1 に答える 1