Skip to main content

Parameter learning in R


source("bayesserver.R")

# This example uses an R DataFrame as the data source for parameter learning.
# You can also connect to databases using DatabaseDataReaderCommand

df <- data.frame(
A = c(3.0, 10.0, 14.3, 12.2),
B = c(16, 12, 3, 6),
C = c("A", "B", "A", "B"),
D = I(c("X", "Y", "X", "X")))

dt <- toDataTable(df)

network <- new(Network)
links <- network$getLinks()
nodes <- network$getNodes()

a <- new (Node, "A", VariableValueType$CONTINUOUS)
nodes$add(a)
b <- new (Node, "B", VariableValueType$CONTINUOUS)
nodes$add(b)
c <- new (Node, "C", .jarray(c("A", "B")))
nodes$add(c)
d <- new (Node, "D", .jarray(c("X", "Y")))
nodes$add(d)

links$add(new (Link, c, a))
links$add(new (Link, c, b))
links$add(new (Link, c, d))

learning <- new (ParameterLearning, network, new (RelevanceTreeInferenceFactory))
options <- new (ParameterLearningOptions)

# You can also use DatabaseDataReaderCommand to connect to databases

dataReaderCommand <- new (DataTableDataReaderCommand, dt)

variableReferences <- lapply(network$getVariables(), function(v)
{
isDiscrete <- v$getValueType() == VariableValueType$DISCRETE
columnValueType <- if(isDiscrete) ColumnValueType$NAME else ColumnValueType$VALUE # ifelse not working

return(new(VariableReference, v, columnValueType, v$getName()))
})

evidenceReaderCommand <- new (DefaultEvidenceReaderCommand,
dataReaderCommand,
toVariableReferenceList(variableReferences),
new(ReaderOptions))

output <- learning$learn(evidenceReaderCommand, options)

print(output$getIterationCount())