Skip to content

Instantly share code, notes, and snippets.

@alejio
Created July 14, 2016 14:35
Show Gist options
  • Save alejio/e34ec8dbeb66ad1ac882d1cdbb6def0e to your computer and use it in GitHub Desktop.
Save alejio/e34ec8dbeb66ad1ac882d1cdbb6def0e to your computer and use it in GitHub Desktop.
R: implementation of a Bayesian Network classifier using package bnlearn
library(data.table)
library(bnlearn)
df <- fread("file.csv", sep="|", verbose=TRUE)
cols <- colnames(df, 3:24)
df <- as.data.frame(df)
df_temp <- data.frame(apply(df, 2, as.factor))
df <- df_temp
rm(df_temp)
drops <- c(cols[1], cols[25])
training.set = subset(df, Partition==1)
training.set <- training.set[ , !(names(training.set) %in% drops)]
test.set = subset(df, Partition==2)
test.set <- test.set[ , !(names(test.set) %in% drops)]
cols2 = colnames(training.set)
tan <- tree.bayes(training.set, training = c('target'), explanatory = cols2[2:length(cols2)])
score(tan, training.set)
fitted1 <- bn.fit(nb, training.set, method = "bayes")
pred1 <- predict(fitted, test.set, method="parents")
pred2 <- predict(fitted, test.set, method="bayes-lw")
table(test.set[, 'target'], pred1)
table(test.set[, 'target'], pred2)
# Structure specification
e = empty.graph(cols2)
adj = matrix(0L, ncol = 23, nrow = 23, dimnames = list(cols2, cols2))
adj[cols2[1],] = 1L
adj[cols2[2],] = 1L
diag(adj) = 0L
amat(e)=adj
fitted3 <- bn.fit(e, training.set, method='bayes')
pred3 <- predict(fitted2, "target", test.set, method="bayes-lw")
table(test.set[, 'target'], pred3)
@flop71
Copy link

flop71 commented Feb 9, 2017

Hi what csv are you using for your input? Cab you attach the file.csv?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment