概率图模型 基于R语言 这本书中的第一个R语言程序

时间:2021-12-13 11:39:13

概率图模型 基于R语言 这本书中的第一个R语言程序

 prior <- c(working =0.99,broken =0.01)
likelihood <- rbind(working = c(good=0.99,bad=0.01),broken =c(good=0.6,bad=0.4))
data <- c("bad","bad","bad","bad") bayes <- function(prior, likelihood, data)
{
posterior <- matrix(0, nrow=length(data), ncol=length(prior))
dimnames(posterior) <- list(data, names(prior)) initial_prior = prior
for(i in 1:length(data))
{
posterior[i, ] <-
prior*likelihood[ , data[i]]/
sum(prior * likelihood[ , data[i]]) prior <- posterior[i , ]
} return(rbind(initial_prior,posterior))
} bayes(prior,likelihood,data)
matplot(bayes(prior,likelihood,data),t='b',lty =1,pch =20,col =c(3,2))

运行效果

概率图模型 基于R语言 这本书中的第一个R语言程序