import random
from scipy.stats import norm
import matplotlib.pyplot as plt
def cauchy(theta):#从柯西分布p中采样数据
y = 1.0 / (1.0 + theta ** 2)
return y
T = 5000
sigma = 1
thetamin = -30
thetamax = 30
theta = [0.0] * (T+1)
theta[0] = random.uniform(thetamin, thetamax)
t = 0
while t < T:
t = t + 1
theta_star = norm.rvs(loc=theta[t - 1], scale=sigma, size=1, random_state=None)#从已知正态分布q中生成候选状态
alpha = min(1, (cauchy(theta_star[0]) / cauchy(theta[t - 1])) )
u = random.uniform(0, 1)
if u <= alpha:#接受
theta[t] = theta_star[0]
else:
theta[t] = theta[t - 1]
#print (theta)
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)
plt.sca(ax1)
plt.ylim(thetamin, thetamax)
plt.plot(range(T+1), theta, 'g-')
plt.sca(ax2)
num_bins = 50
plt.hist(theta, num_bins, normed=1, facecolor='red', alpha=0.5)
plt.show()
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
MCMC.zip (3个子文件)
Caucypythonrandom.py 943B
p.m 232B
MCMCtest.m 1KB
共 3 条
- 1
kikikuka
- 粉丝: 66
- 资源: 4774
下载权益
C知道特权
VIP文章
课程特权
开通VIP
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
前往页