概率图模型 基于R语言 这本书中的第一个R语言程序
1 prior <- c(working =0.99,broken =0.01) 2 likelihood <- rbind(working = c(good=0.99,bad=0.01),broken =c(good=0.6,bad=0.4)) 3 data <- c("bad","bad","bad","bad") 4 5 bayes <- function(prior, likelihood, data) 6 { 7 posterior <- matrix(0, nrow=length(data), ncol=length(prior)) 8 dimnames(posterior) <- list(data, names(prior)) 9 10 initial_prior = prior 11 for(i in 1:length(data)) 12 { 13 posterior[i, ] <- 14 prior*likelihood[ , data[i]]/ 15 sum(prior * likelihood[ , data[i]]) 16 17 prior <- posterior[i , ] 18 } 19 20 return(rbind(initial_prior,posterior)) 21 } 22 23 24 bayes(prior,likelihood,data) 25 matplot(bayes(prior,likelihood,data),t=\'b\',lty =1,pch =20,col =c(3,2))
运行效果