Skip to main content

Parameter tuning in C#

using BayesServer.Analysis;
using BayesServer.Inference;
using BayesServer.Inference.RelevanceTree;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BayesServer.HelpSamples
{
public static class ParameterTuningExample
{
public static void Main()
{
var network = new Network();

// TODO download the network from the Bayes Server User Interface (or Bayes Server Online)
// and adjust the following path
network.Load(@"Asia.bayes");

var visitToAsia = network.Variables["Visit to Asia", true];
var hasLungCancer = network.Variables["Has Lung Cancer", true];
var tuberculosisOrCancer = network.Variables["Tuberculosis or Cancer", true];
var smoker = network.Variables["Smoker", true];
var hasTuberculosis = network.Variables["Has Tuberculosis", true];
var dyspnea = network.Variables["Dyspnea", true];
var xRayResult = network.Variables["XRay Result", true];
var hasBronchitis = network.Variables["Has Bronchitis", true];

var xRayResultAbnormal = xRayResult.States["Abnormal", true];
var smokerFalse = smoker.States["False", true];
var hasLungCancerFalse = hasLungCancer.States["False", true];

var evidence = new Evidence(network);

// TODO set any evidence here if you need to...


var sensitivity = new SensitivityToParameters(network, new RelevanceTreeInferenceFactory());

var parametersToTest = new List<ParameterReference>();
parametersToTest.Add(new ParameterReference(
hasLungCancer.Node,
new State[] { hasLungCancerFalse, smokerFalse }
));

Console.WriteLine($"Node\tParameter\tMin\tMax");

foreach(var parameter in parametersToTest)
{
var oneWay = sensitivity.OneWay(
evidence,
xRayResultAbnormal,
parameter
);

try
{
var output = ParameterTuning.OneWaySimple(
oneWay,
new Interval<double>(0.2, 0.25, IntervalEndPoint.Closed, IntervalEndPoint.Closed));

var paramStatesText = "[" + string.Join(",", parameter.States.Select(s => s.Variable.Name + " = " + s.Name)) + "]";
Console.WriteLine($"{parameter.Node.Name}\t{paramStatesText}\t{output.Interval.Minimum}\t{output.Interval.Maximum}");
}
catch (ConstraintNotSatisfiedException)
{
Console.WriteLine("Ignoring here as solution not found for this parameter.");
}
}

// Expected output...

// Node Parameter Min Max
// Has Lung Cancer[Has Lung Cancer = False, Smoker = False] 0.686390938882659 0.795047852504759

}
}
}