Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```{r}
- library(bnlearn)
- library(gRain)
- prediction <- function(junctree, data, observed_var, predicted_var) {
- predictions <- NULL
- X <- NULL
- #loop through rows in data
- for (i in 1:nrow(data)) {
- #loop through observed variables and set vector X to corresponding value
- for (j in observed_var) {
- X[j] <- if(data[i, j] == "yes") "yes" else "no" }
- #Get the list of potentials
- evidence <- setFinding(object = junctree, nodes = observed_var,states = X)
- #Get the probabilities for the values of the predicted value
- prob <- querygrain(object = evidence,nodes = predicted_var)$S
- predictions[i] <- if (prob["yes"] > 0.5) "yes" else "no"
- }
- return (predictions)
- }
- ```
- ```{r}
- set.seed(567)
- data("asia")
- ind <- sample(1:5000, 4000)
- tr <- asia[ind,]
- te <- asia[-ind,]
- #Create the native bayesian network
- BN <-model2network("[S][A|S][T|S][L|S][B|S][E|S][X|S][D|S]")
- trainingPoints <- c(10,20,50,100,1000,2000)
- accuracys <- matrix(NA, length(trainingPoints))
- for (i in 1:length(trainingPoints)) {
- trainData <- tr[1:trainingPoints[i],]
- #Fit parameters of network to train data
- BN_fit <- bn.fit(x = BN, data = trainData, method="bayes")
- #Convert to gRain-object
- BN_grain <- as.grain(BN_fit)
- #Get junctiontree
- junctree <- compile(BN_grain)
- # #Make predictions
- pred <- prediction(junctree = junctree, data = te, observed_var = c("A", "T", "L", "B", "E", "X", "D"),predicted_var = c("S"))
- # Calculate confusion matricies
- confusion_matrix<- table(pred, te$S)
- accuracys[i] <- sum(diag(confusion_matrix))/ sum(confusion_matrix)
- }
- print(accuracys)
- ```
- ```{r}
- #Create the native bayesian network
- BN <-model2network("[A][T][L][B][E][X][D][S|A:T:L:B:E:X:D]")
- trainingPoints <- c(10,20,50,100,1000,2000)
- accuracys <- matrix(NA, length(trainingPoints))
- for (i in 1:length(trainingPoints)) {
- trainData <- tr[1:trainingPoints[i],]
- #Fit parameters of network to train data
- BN_fit <- bn.fit(x = BN, data = trainData, method="bayes")
- #Convert to gRain-object
- BN_grain <- as.grain(BN_fit)
- #Get junctiontree
- junctree_naive <- compile(BN_grain)
- # #Make predictions
- pred <- prediction(junctree = junctree_naive, data = te, observed_var = c("A", "T", "L", "B", "E", "X", "D"),predicted_var = c("S"))
- # Calculate confusion matricies
- confusion_matrix<- table(pred, te$S)
- accuracys[i] <- sum(diag(confusion_matrix))/ sum(confusion_matrix)
- }
- print(accuracys)
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement