require(reshape)
source("PM1.R")
#FactorMarginalization Sums given variables out of a factor.
ComputeJointDistribution <- function(F) {
# Check for empty factor list
if (length(F) == 0){
cat('Error: empty factor list');
Joint = list(var = NA, card = NA, val = NA);
return(Joint);
}
Joint = F[[1]];
for (i in 2:length(F)){
Joint = FactorProduct(Joint, F[[i]]);
}
return(Joint);
}
#ComputeMarginal Computes the marginal over a set of given variables
ComputeMarginal <- function(V, F, E) {
# Check for empty factor list
if (length(F) == 0){
cat('Error: empty factor list');
M = list(var = NA, card = NA, val = NA);
return(M);
}
M = list(var = NA, card = NA, val = NA);
joint = ComputeJointDistribution(F);
joint = list(joint);
evidence = ObserveEvidence(joint, E);
evidence = evidence[[1]];
evidence$val = evidence$val / sum(evidence$val);
var = setdiff(evidence$var, V);
M = FactorMarginalization(evidence, var);
return(M);
}
V <- c(2, 3);
A <- list(var = c(1), card = c(2), val = c(0.11, 0.89));
B <- list(var = c(2, 1), card = c(2, 2), val = c(0.59, 0.41, 0.22, 0.78));
C <- list(var = c(3, 2), card = c(2, 2), val = c(0.39, 0.61, 0.06, 0.94));
F <- list(A, B, C);
E <- matrix(c(1, 2), byrow = T, nrow = 1)
ComputeMarginal(V, F, E)
thanks for posting - looking to implement liblinear in r so great to see a full example
ReplyDelete