import random
from scipy.stats import norm
import matplotlib.pyplot as plt
def cauchy(theta):
y = 1.0/(1.0 + theta ** 2)
return y
T = 50 #循環的次數
sigma = 1
thetamin = -30
thetamax = 30
theta = [0.0] * (T + 1)
theta[0] = random.uniform(thetamin,thetamax)
t = 0
while t < T:
t += 1
theta_star = norm.rvs(loc=theta[t - 1], scale=sigma, size=1, random_state=None) #生成數據[] 一個
alpha = min(1,cauchy(theta_star[0])/cauchy(theta[t - 1])) #調用上邊的函數
u = random.uniform(0,1)
if u <= alpha: #隨機值小於alpha則接受
theta[t] = theta_star[0]
else:
theta[t] = theta[t-1]
print(theta)
簡單易學的機器學習算法——馬爾可夫鏈蒙特卡羅方法MCMC
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.