Skip to main content

Time Series Parameter learning in Java

package com.bayesserver.examples;

import com.bayesserver.*;
import com.bayesserver.data.*;
import com.bayesserver.inference.*;
import com.bayesserver.learning.parameters.*;

import java.util.Arrays;

public class ParameterLearningTemporal {

public static void main(String[] args) {

// we manually construct the network here, but it could be loaded from a file
Network network = createNetworkStructure();
Variable x1 = network.getVariables().get("X1");
Variable x2 = network.getVariables().get("X2");

// now learn the parameters from the data in Walkthrough 3 - Time Series network

// This example uses Sql Server as the data source and assumes the data has been copied to
// a table called TimeSeriesWalkthrough
// We will use the RelevanceTree algorithm here, as it is optimized for parameter learning
ParameterLearning learning = new ParameterLearning(network, new RelevanceTreeInferenceFactory());
ParameterLearningOptions learningOptions = new ParameterLearningOptions();
learningOptions.setTimeSeriesMode(TimeSeriesMode.ROLLING);

String connectionUrl = "<connection url to database goes here>";

DataReaderCommand temporalDataReaderCommand = new DatabaseDataReaderCommand(
connectionUrl,
"Select [Case], Time, X1, X2 From TimeSeriesWalkthrough ORDER BY [Case], Time");

TemporalReaderOptions temporalReaderOptions = new TemporalReaderOptions("Case", "Time", TimeValueType.INDEX);

// here we map variables to database columns
// in this case the variables and database columns have the same name
VariableReference[] temporalVariableReferences = new VariableReference[]
{
new VariableReference(x1, ColumnValueType.VALUE, x1.getName()),
new VariableReference(x2, ColumnValueType.VALUE, x2.getName())
};

// note that although this example only has temporal data
// we could have included additional non temporal variables and data

EvidenceReaderCommand evidenceReaderCommand = new DefaultEvidenceReaderCommand(
temporalDataReaderCommand,
Arrays.asList(temporalVariableReferences),
temporalReaderOptions);

ParameterLearningOutput result = learning.learn(evidenceReaderCommand, learningOptions);

System.out.println("Log likelihood = " + result.getLogLikelihood());

}

private static Network createNetworkStructure() {
Network network = new Network();

Variable x1 = new Variable("X1", VariableValueType.CONTINUOUS);
Variable x2 = new Variable("X2", VariableValueType.CONTINUOUS);

// add a temporal (time series) node, with two continuous variables
Node nodeX = new Node("X", new Variable[]{x1, x2});
nodeX.setTemporalType(TemporalType.TEMPORAL);

network.getNodes().add(nodeX);

// add temporal links
for (int order = 1; order <= 4; order++) {
network.getLinks().add(new Link(nodeX, nodeX, order));
}

// at this point the Dynamic Bayesian network structure is fully specified

return network;
}
}