R语言使用Metropolis-|R语言使用Metropolis- Hasting抽样算法进行逻辑回归

原文链接:http://tecdat.cn/?p=6761 原文出处:拓端数据部落公众号 在逻辑回归中,我们将二元因变量Y\_i回归到协变量X\_i上。下面的代码使用Metropolis采样来探索 beta\_1和beta\_2 的后验Yi到协变量Xi。
定义expit和分对数链接函数

logit<-function(x){log(x/(1-x))} 此函数计算beta\_1,beta\_2的联合后验。它返回后验的对数以获得数值稳定性。(β1,β2)(β1,β2)。它返回后验的对数获得数值稳定性。 log_post<-function(Y,X,beta){ prob1<- expit(beta\[1\] + beta\[2\]*X) like+prior}

这是MCMC的主要功能.can.sd是候选标准偏差。
Bayes.logistic<-function(y,X, n.samples=10000, can.sd=0.1){ keep.beta<- matrix(0,n.samples,2) keep.beta\[1,\] <- betaacc<- att <- rep(0,2) for(i in 2:n.samples){for(j in 1:2){att\[j\] <- att\[j\] + 1# 抽取候选:canbeta<- beta canbeta\[j\] <- rnorm(1,beta\[j\],can.sd) canlp<- log_post(Y,X,canbeta)# 计算接受率:R <- exp(canlp-curlp) U <- runif(1) if(U

生成模拟数据
set.seed(2008) n<- 100 X<- rnorm(n) true.p<- expit(true.beta\[1\]+true.beta\[2\]*X) Y<- rbinom(n,1,true.p)

拟合模型
burn<- 10000 n.samples <- 50000 fit<- Bayes.logistic(Y,X,n.samples=n.samples,can.sd=0.5) tock <- proc.time()\[3\] tock-tick

## elapsed ##3.72

结果 R语言使用Metropolis-|R语言使用Metropolis- Hasting抽样算法进行逻辑回归
文章图片

abline(true.beta\[1\],0,lwd=2,col=2)

R语言使用Metropolis-|R语言使用Metropolis- Hasting抽样算法进行逻辑回归
文章图片

abline(true.beta\[2\],0,lwd=2,col=2)

R语言使用Metropolis-|R语言使用Metropolis- Hasting抽样算法进行逻辑回归
文章图片

hist(fit$beta\[,1\],main="Intercept",xlab=expression(beta\[1\]),breaks=50)

R语言使用Metropolis-|R语言使用Metropolis- Hasting抽样算法进行逻辑回归
文章图片

hist(fit$beta\[,2\],main="Slope",xlab=expression(beta\[2\]),breaks=50) abline(v=true.beta\[2\],lwd=2,col=2)

R语言使用Metropolis-|R语言使用Metropolis- Hasting抽样算法进行逻辑回归
文章图片

print("Posterior mean/sd") ## \[1\] "Posterior mean/sd" print(round(apply(fit$beta\[burn:n.samples,\],2,mean),3)) ## \[1\] -0.0760.798 print(round(apply(fit$beta\[burn:n.samples,\],2,sd),3)) ## \[1\] 0.214 0.268## ## Deviance Residuals: ##Min1QMedian3QMax ## -1.6990-1.1039-0.61381.09551.8275 ## ## Coefficients: ##Estimate Std. Error z value Pr(>|z|) ## (Intercept) -0.073930.21034-0.3520.72521 ## X0.768070.263702.9130.00358 ** ## --- ## Signif. codes:0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## (Dispersion parameter for binomial family taken to be 1) ## ##Null deviance: 138.47on 99degrees of freedom ## Residual deviance: 128.57on 98degrees of freedom ## AIC: 132.57 ## ## Number of Fisher Scoring iterations: 4

非常感谢您阅读本文,有任何问题请在下面留言! R语言使用Metropolis-|R语言使用Metropolis- Hasting抽样算法进行逻辑回归
文章图片

最受欢迎的见解
1.使用R语言进行METROPLIS-IN-GIBBS采样和MCMC运行
2.R语言中的Stan概率编程MCMC采样的贝叶斯模型
3.R语言实现MCMC中的Metropolis–Hastings算法与吉布斯采样
4.R语言BUGS JAGS贝叶斯分析 马尔科夫链蒙特卡洛方法(MCMC)采样
5.R语言中的block Gibbs吉布斯采样贝叶斯多元线性回归
6.R语言Gibbs抽样的贝叶斯简单线性回归仿真分析
7.R语言用Rcpp加速Metropolis-Hastings抽样估计贝叶斯逻辑回归模型的参数
8.R语言使用Metropolis- Hasting抽样算法进行逻辑回归
【R语言使用Metropolis-|R语言使用Metropolis- Hasting抽样算法进行逻辑回归】9.R语言中基于混合数据抽样(MIDAS)回归的HAR-RV模型预测GDP增长

    推荐阅读