add tensor test for Metropolis Hastings
@@ -5,10 +5,12 @@ import io.improbable.keanu.network.BayesianNetwork;
import io.improbable.keanu.vertices.bool.BoolVertex;
import io.improbable.keanu.vertices.bool.probabilistic.Flip;
import io.improbable.keanu.vertices.dbl.DoubleVertex;
-import io.improbable.keanu.vertices.dbl.nonprobabilistic.ConstantDoubleVertex;
import io.improbable.keanu.vertices.dbl.nonprobabilistic.operators.unary.DoubleUnaryOpLambda;
import io.improbable.keanu.vertices.dbl.probabilistic.GaussianVertex;
+import io.improbable.keanu.vertices.dbltensor.DoubleTensor;
+import io.improbable.keanu.vertices.dbltensor.DoubleTensorVertex;
import io.improbable.keanu.vertices.dbltensor.KeanuRandom;
+import io.improbable.keanu.vertices.dbltensor.probabilistic.TensorGaussianVertex;
import org.junit.Before;
import org.junit.Test;
@@ -34,9 +36,9 @@ public class MetropolisHastingsTest {
DoubleVertex B = new GaussianVertex(20.0, 1.0);
A.setValue(20.0);
- B.setAndCascade(20.0);
+ B.setValue(20.0);
- DoubleVertex Cobserved = new GaussianVertex(A.plus(B), new ConstantDoubleVertex(1.0));
+ DoubleVertex Cobserved = new GaussianVertex(A.plus(B), 1.0);
Cobserved.observe(46.0);
@@ -58,7 +60,46 @@ public class MetropolisHastingsTest {
.mapToDouble(sample -> sample)
.average();
- assertEquals(44.0, averagePosteriorA.getAsDouble() + averagePosteriorB.getAsDouble(), 0.1);
+ double actual = averagePosteriorA.getAsDouble() + averagePosteriorB.getAsDouble();
+ assertEquals(44.0, actual, 0.1);
+ }
+
+ @Test
+ public void samplesContinuousTensorPrior() {
+
+ int[] shape = new int[]{1, 1};
+ DoubleTensorVertex A = new TensorGaussianVertex(shape, 20.0, 1.0);
+ DoubleTensorVertex B = new TensorGaussianVertex(shape, 20.0, 1.0);
+
+ A.setValue(20.0);
+ B.setValue(20.0);
+
+ DoubleTensorVertex Cobserved = new TensorGaussianVertex(A.plus(B), 1.0);
+ Cobserved.observe(46.0);
+
+ BayesianNetwork bayesNet = new BayesianNetwork(Arrays.asList(A, B, Cobserved));
+ bayesNet.probeForNonZeroMasterP(100, random);
+
+ NetworkSamples posteriorSamples = MetropolisHastings.getPosteriorSamples(
+ bayesNet,
+ Arrays.asList(A, B),
+ 100000,
+ random
+ );
+
+ DoubleTensor averagePosteriorA = posteriorSamples.get(A).asList().stream()
+ .reduce(DoubleTensor.zeros(shape), DoubleTensor::plusInPlace)
+ .divInPlace(100000);
+
+ DoubleTensor averagePosteriorB = posteriorSamples.get(B).asList().stream()
+ .reduce(DoubleTensor.zeros(shape), DoubleTensor::plusInPlace)
+ .divInPlace(100000);
+
+ DoubleTensor allActuals = averagePosteriorA.plus(averagePosteriorB);
+
+ for (double actual : allActuals.getFlattenedView().asArray()) {
+ assertEquals(44.0, actual, 0.1);
+ }
}
@Test
@@ -135,6 +176,8 @@ public class MetropolisHastingsTest {
double postProbTrue = posteriorSamples.get(A).probability(v -> v);
+ System.out.println(postProbTrue);
+
assertEquals(0.5, postProbTrue, 0.01);
}
