/** * Creates a Bayesian network from the graph connected to the given vertex and uses this to * create a BOBYQA {@link NonGradientOptimizer}. This provides methods for optimizing the * values of latent variables of the Bayesian network to maximise probability. * * @param vertexFromNetwork A vertex in the graph to create the Bayesian network from * @return a {@link NonGradientOptimizer} */ public NonGradientOptimizer ofConnectedGraph(Vertex<?> vertexFromNetwork) { return of(vertexFromNetwork.getConnectedGraph()); }
/** * Creates a {@link ParticleFilterBuilder} by retrieving connected graph from the vertex * @param vertex vertex to retrieve connected graph from * @return this */ public static ParticleFilterBuilder ofVertexInGraph(Vertex vertex) { return new ParticleFilterBuilder(vertex.getConnectedGraph()); }
/** * Creates a Bayesian network from the graph connected to the given vertex and uses this to * create an {@link Optimizer}. This provides methods for optimizing the values of latent variables * of the Bayesian network to maximise probability. * * @param vertexFromNetwork A vertex in the graph to create the Bayesian network from. * @return an {@link Optimizer} */ public Optimizer ofConnectedGraph(Vertex<?> vertexFromNetwork) { return of(vertexFromNetwork.getConnectedGraph()); }
/** * Creates a Bayesian network from the graph connected to the given vertex and uses this to * create a {@link GradientOptimizer}. This provides methods for optimizing the values of latent variables * of the Bayesian network to maximise probability. * * @param vertexFromNetwork A vertex in the graph to create the Bayesian network from * @return a {@link GradientOptimizer} */ public GradientOptimizer ofConnectedGraph(Vertex<?> vertexFromNetwork) { return of(vertexFromNetwork.getConnectedGraph()); }
@BeforeClass public static void setUp() { v = Mockito.mock(Vertex.class); Set<Vertex> parents = new HashSet<>(); parent = Mockito.mock(Vertex.class); parents.add(parent); Set<Vertex> children = new HashSet<>(); child = Mockito.mock(Vertex.class); children.add(child); when(v.getParents()).thenReturn(parents); when(v.getChildren()).thenReturn(children); Set<Vertex> grandParents = new HashSet<>(); grandParent = Mockito.mock(Vertex.class); grandParents.add(grandParent); Set<Vertex> grandChildren = new HashSet<>(); grandChild = Mockito.mock(Vertex.class); grandChildren.add(grandChild); when(parent.getParents()).thenReturn(grandParents); when(child.getChildren()).thenReturn(grandChildren); when(v.getConnectedGraph()).thenReturn(ImmutableSet.of(v, parent, child, grandChild, grandParent)); network = new BayesianNetwork(v.getConnectedGraph()); }
public static double priorProbabilityTrue(Vertex<? extends Tensor<Boolean>> vertex, int sampleCount, KeanuRandom random) { KeanuProbabilisticModel model = new KeanuProbabilisticModel(vertex.getConnectedGraph()); long trueCount = MetropolisHastings.withDefaultConfigFor(model, random) .generatePosteriorSamples(model, Collections.singletonList(vertex)).stream() .limit(sampleCount) .filter(state -> state.get(vertex).scalar()) .count(); return trueCount / (double) sampleCount; }
public LinearRegressionGraph(long[] featureShape, Function<DoubleVertex, OutputVertices<OUTPUT>> outputTransform, DoubleVertex interceptVertex, DoubleVertex weightsVertex) { long featureCount = featureShape[1]; Preconditions.checkArgument(TensorShape.isLengthOne(interceptVertex.getShape())); TensorShapeValidation.checkShapesMatch(weightsVertex.getShape(), new long[]{featureCount, 1}); this.weightsVertex = weightsVertex; this.interceptVertex = interceptVertex; xVertex = new ConstantDoubleVertex(DoubleTensor.zeros(featureShape)); OutputVertices<OUTPUT> outputVertices = outputTransform.apply( TensorShape.isLengthOne(weightsVertex.getShape()) ? weightsVertex.times(xVertex).plus(interceptVertex) : xVertex.matrixMultiply(weightsVertex).plus(interceptVertex) ); yVertex = outputVertices.outputVertex; yObservationVertex = outputVertices.observedVertex; bayesianNetwork = new BayesianNetwork(yVertex.getConnectedGraph()); }
@Test public void whenRunningMetropolisHastingsThenSamplesArePrinted() { final Vertex<DoubleTensor> temperature = new UniformVertex(20., 30.); new PrintVertex<>(temperature); KeanuProbabilisticModel model = new KeanuProbabilisticModel(temperature.getConnectedGraph()); final int nSamples = 100; MetropolisHastings .withDefaultConfigFor(model) .getPosteriorSamples(model, model.getLatentVariables(), nSamples); verify(printStream, atLeast(nSamples)).print(anyString()); }
@Test public void metadataCanBeSavedToProtobuf() throws IOException { Vertex vertex = new ConstantIntegerVertex(1); BayesianNetwork net = new BayesianNetwork(vertex.getConnectedGraph()); Map<String, String> metadata = ImmutableMap.of("Author", "Some Author", "Tag", "MyBayesNet"); ByteArrayOutputStream writer = new ByteArrayOutputStream(); ProtobufSaver protobufSaver = new ProtobufSaver(net); protobufSaver.save(writer, true, metadata); KeanuSavedBayesNet.Model parsedModel = KeanuSavedBayesNet.Model.parseFrom(writer.toByteArray()); KeanuSavedBayesNet.Metadata.Builder metadataBuilder = KeanuSavedBayesNet.Metadata.newBuilder(); String[] metadataKeys = metadata.keySet().toArray(new String[0]); Arrays.sort(metadataKeys); for (String metadataKey : metadataKeys) { metadataBuilder.putMetadataInfo(metadataKey, metadata.get(metadataKey)); } assertEquals(parsedModel.getMetadata().getMetadataInfoMap(), metadataBuilder.getMetadataInfoMap()); }
@BeforeClass public static void setUpComplexNet() { VertexId.ID_GENERATOR.set(0); complexResultVertex = ((new GammaVertex(0, 1)) .lessThan(new ConstantIntegerVertex(-1))) .or((new GaussianVertex(0, 1)) .plus(new ConstantDoubleVertex(5)) .equalTo(new ConstantDoubleVertex(10))); BayesianNetwork complexNet = new BayesianNetwork(complexResultVertex.getConnectedGraph()); complexNetDotSaver = new DotSaver(complexNet); }
@Test public void valuesAreBeingWrittenOut() throws IOException { DoubleVertex unobservedGaussianVertex = new GaussianVertex(0, 1); DoubleVertex observedGammaVertex = new GammaVertex(2, 3); observedGammaVertex.observe(2.5); DoubleVertex gammaMultipliedVertex = observedGammaVertex.times(new ConstantDoubleVertex(4)); Vertex resultVertex = gammaMultipliedVertex.plus(unobservedGaussianVertex); gammaMultipliedVertex.setLabel("Gamma Multiplied"); DotSaver dotSaver = new DotSaver(new BayesianNetwork(resultVertex.getConnectedGraph())); dotSaver.save(outputWriter, true); String expectedOutputWithValues = readFileToString(OUTPUT_WITH_VALUES_FILENAME); checkDotFilesMatch(outputWriter.toString(), expectedOutputWithValues); }
@Test public void youCanChainTwoLoopsTogetherInABayesNet() { Loop loop = Loop .withInitialConditions(startValue) .doNotThrowWhenMaxCountIsReached() .iterateWhile(alwaysTrue) .apply(increment); Vertex<?> outputFromFirstLoop = loop.getOutput(); Loop loop2 = Loop .withInitialConditions((Vertex<?>) loop.getOutput()) .doNotThrowWhenMaxCountIsReached() .iterateWhile(alwaysTrue) .apply(increment); Vertex<?> output = loop2.getOutput(); new BayesianNetwork(output.getConnectedGraph()); }