aima.core.probability.bayes.approx.PriorSample Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of aima-core Show documentation
Show all versions of aima-core Show documentation
AIMA-Java Core Algorithms from the book Artificial Intelligence a Modern Approach 3rd Ed.
The newest version!
package aima.core.probability.bayes.approx;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import aima.core.probability.RandomVariable;
import aima.core.probability.bayes.BayesianNetwork;
import aima.core.probability.util.ProbUtil;
import aima.core.util.JavaRandomizer;
import aima.core.util.Randomizer;
/**
* Artificial Intelligence A Modern Approach (3rd Edition): page 531.
*
*
*
* function PRIOR-SAMPLE(bn) returns an event sampled from the prior specified by bn
* inputs: bn, a Bayesian network specifying joint distribution P(X1,...,Xn)
*
* x <- an event with n elements
* foreach variable Xi in X1,...,Xn do
* x[i] <- a random sample from P(Xi | parents(Xi))
* return x
*
*
* Figure 14.13 A sampling algorithm that generates events from a Bayesian
* network. Each variable is sampled according to the conditional distribution
* given the values already sampled for the variable's parents.
*
* @author Ciaran O'Reilly
* @author Ravi Mohan
*/
public class PriorSample {
private Randomizer randomizer = null;
public PriorSample() {
this(new JavaRandomizer(new Random()));
}
public PriorSample(Randomizer r) {
this.randomizer = r;
}
// function PRIOR-SAMPLE(bn) returns an event sampled from the prior
// specified by bn
/**
* The PRIOR-SAMPLE algorithm in Figure 14.13. A sampling algorithm that
* generates events from a Bayesian network. Each variable is sampled
* according to the conditional distribution given the values already
* sampled for the variable's parents.
*
* @param bn
* a Bayesian network specifying joint distribution
* P(X1,...,Xn)
* @return an event sampled from the prior specified by bn
*/
public Map priorSample(BayesianNetwork bn) {
// x <- an event with n elements
Map x = new LinkedHashMap();
// foreach variable Xi in X1,...,Xn do
for (RandomVariable Xi : bn.getVariablesInTopologicalOrder()) {
// x[i] <- a random sample from
// P(Xi | parents(Xi))
x.put(Xi, ProbUtil.randomSample(bn.getNode(Xi), x, randomizer));
}
// return x
return x;
}
}