狄利克雷分佈的三維實現和狄利克雷過程中的stick—breaking算法的實現

轉載請標明作者

首先是狄利克雷分佈的三維實現,由於沒法保證下面的座標值加起來唯一,所以我採用了抽樣的方法,從dirchidirichlet~(1,1,1)中抽的三維圖像的座標值,我只去前兩個作爲我的x,y值,代碼如下:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from scipy import stats
global LEN
LEN=1000
#抽樣
rv=stats.dirichlet.rvs([1,1,1],3000)
#將前兩個值作爲我的x,y值
rvs=rv[:,0:2]
list=[]
for x in rv:
    #計算其對應的pdf值
    pdf=stats.dirichlet.pdf(x,alpha=[5,10,7])
    list.append(float(pdf))
fig=plt.figure()
ax=fig.gca(projection="3d")
ax.scatter(rvs[:,0],rvs[:,1],list)
plt.show()

由於,我採用的是抽樣的方式,所以如果數據少的話,會出現空白部位,得到的圖像爲: 

接下來介紹一下 stick-breaking的實現,一般用於狄利克雷過程中數據的抽樣,代碼如下 :

import matplotlib.pyplot as plt
import numpy as np
#my stick breaking sampling
#使用的基函數是高斯
#dp~dp(alpha,gaussian(0,1))
def stick_breaking(alpha,sample_num):
    x_list=[]
    y_list=[]
    for x in range(sample_num):
        data_x=np.random.normal(0,1,1)
        beta=np.random.beta(1,alpha,1)
        y=(1-sum(y_list))*beta
        x_list.append(data_x)
        y_list.append(y)
    return x_list,y_list
alpha=1000
sample_num=500#樣本數
x_list,y_list=stick_breaking(alpha,sample_num)
plt.stem(x_list,y_list)
plt.show()

得到的圖像如下:

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章