Search in sources :

Example 6 with PredictionOutput

use of org.kie.kogito.explainability.model.PredictionOutput in project kogito-apps by kiegroup.

the class CounterfactualExplainerTest method mockExplainerInvocation.

@SuppressWarnings("unchecked")
CounterfactualResult mockExplainerInvocation(Consumer<CounterfactualResult> intermediateResultsConsumer, Long maxRunningTimeSeconds) throws ExecutionException, InterruptedException, TimeoutException {
    // Mock SolverManager and SolverJob to guarantee deterministic test behaviour
    SolverJob<CounterfactualSolution, UUID> solverJob = mock(SolverJob.class);
    CounterfactualSolution solution = mock(CounterfactualSolution.class);
    BendableBigDecimalScore score = BendableBigDecimalScore.zero(0, 0);
    when(solverManager.solveAndListen(any(), any(), any(), any())).thenReturn(solverJob);
    when(solverJob.getFinalBestSolution()).thenReturn(solution);
    when(solution.getScore()).thenReturn(score);
    when(solverManagerFactory.apply(any())).thenReturn(solverManager);
    // Setup Explainer
    final CounterfactualConfig counterfactualConfig = new CounterfactualConfig().withSolverManagerFactory(solverManagerFactory);
    final CounterfactualExplainer counterfactualExplainer = new CounterfactualExplainer(counterfactualConfig);
    // Setup mock model, what it does is not important
    Prediction prediction = new CounterfactualPrediction(new PredictionInput(Collections.emptyList()), new PredictionOutput(Collections.emptyList()), null, UUID.randomUUID(), maxRunningTimeSeconds);
    return counterfactualExplainer.explainAsync(prediction, (List<PredictionInput> inputs) -> CompletableFuture.completedFuture(Collections.emptyList()), intermediateResultsConsumer).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
}
Also used : PredictionInput(org.kie.kogito.explainability.model.PredictionInput) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Prediction(org.kie.kogito.explainability.model.Prediction) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) BendableBigDecimalScore(org.optaplanner.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore) UUID(java.util.UUID) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction)

Example 7 with PredictionOutput

use of org.kie.kogito.explainability.model.PredictionOutput in project kogito-apps by kiegroup.

the class CounterfactualExplainerTest method testIntermediateUniqueIds.

@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testIntermediateUniqueIds(int seed) throws ExecutionException, InterruptedException, TimeoutException {
    Random random = new Random();
    random.setSeed(seed);
    final List<Output> goal = new ArrayList<>();
    List<Feature> features = List.of(FeatureFactory.newNumericalFeature("f-num1", 10.0, NumericalFeatureDomain.create(0, 20)));
    PredictionProvider model = TestUtils.getFeaturePassModel(0);
    final TerminationConfig terminationConfig = new TerminationConfig().withScoreCalculationCountLimit(100_000L);
    final SolverConfig solverConfig = SolverConfigBuilder.builder().withTerminationConfig(terminationConfig).build();
    solverConfig.setRandomSeed((long) seed);
    solverConfig.setEnvironmentMode(EnvironmentMode.REPRODUCIBLE);
    final List<UUID> intermediateIds = new ArrayList<>();
    final List<UUID> executionIds = new ArrayList<>();
    final Consumer<CounterfactualResult> captureIntermediateIds = counterfactual -> {
        intermediateIds.add(counterfactual.getSolutionId());
    };
    final Consumer<CounterfactualResult> captureExecutionIds = counterfactual -> {
        executionIds.add(counterfactual.getExecutionId());
    };
    final CounterfactualConfig counterfactualConfig = new CounterfactualConfig().withSolverConfig(solverConfig);
    solverConfig.withEasyScoreCalculatorClass(MockCounterFactualScoreCalculator.class);
    final CounterfactualExplainer counterfactualExplainer = new CounterfactualExplainer(counterfactualConfig);
    PredictionInput input = new PredictionInput(features);
    PredictionOutput output = new PredictionOutput(goal);
    final UUID executionId = UUID.randomUUID();
    Prediction prediction = new CounterfactualPrediction(input, output, null, executionId, null);
    final CounterfactualResult counterfactualResult = counterfactualExplainer.explainAsync(prediction, model, captureIntermediateIds.andThen(captureExecutionIds)).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
    for (CounterfactualEntity entity : counterfactualResult.getEntities()) {
        logger.debug("Entity: {}", entity);
    }
    // all intermediate Ids must be distinct
    assertEquals((int) intermediateIds.stream().distinct().count(), intermediateIds.size());
    assertEquals(1, (int) executionIds.stream().distinct().count());
    assertEquals(executionIds.get(0), executionId);
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) FeatureFactory(org.kie.kogito.explainability.model.FeatureFactory) Feature(org.kie.kogito.explainability.model.Feature) LoggerFactory(org.slf4j.LoggerFactory) Assertions.assertNotEquals(org.junit.jupiter.api.Assertions.assertNotEquals) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) CounterfactualEntity(org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity) Value(org.kie.kogito.explainability.model.Value) TerminationConfig(org.optaplanner.core.config.solver.termination.TerminationConfig) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) FeatureDistribution(org.kie.kogito.explainability.model.FeatureDistribution) EmptyFeatureDomain(org.kie.kogito.explainability.model.domain.EmptyFeatureDomain) Mockito.atLeast(org.mockito.Mockito.atLeast) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) CategoricalFeatureDomain(org.kie.kogito.explainability.model.domain.CategoricalFeatureDomain) DataUtils(org.kie.kogito.explainability.utils.DataUtils) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) Test(org.junit.jupiter.api.Test) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) List(java.util.List) Stream(java.util.stream.Stream) NormalDistribution(org.apache.commons.math3.distribution.NormalDistribution) Output(org.kie.kogito.explainability.model.Output) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) SolverJob(org.optaplanner.core.api.solver.SolverJob) Mockito.mock(org.mockito.Mockito.mock) IntStream(java.util.stream.IntStream) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) SolverConfig(org.optaplanner.core.config.solver.SolverConfig) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) PerturbationContext(org.kie.kogito.explainability.model.PerturbationContext) Prediction(org.kie.kogito.explainability.model.Prediction) DataDomain(org.kie.kogito.explainability.model.DataDomain) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) EnvironmentMode(org.optaplanner.core.config.solver.EnvironmentMode) CompletableFuture(java.util.concurrent.CompletableFuture) SolverManager(org.optaplanner.core.api.solver.SolverManager) Function(java.util.function.Function) ArrayList(java.util.ArrayList) MockCounterFactualScoreCalculator(org.kie.kogito.explainability.local.counterfactual.score.MockCounterFactualScoreCalculator) ArgumentCaptor(org.mockito.ArgumentCaptor) NumericFeatureDistribution(org.kie.kogito.explainability.model.NumericFeatureDistribution) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) LinkedList(java.util.LinkedList) BendableBigDecimalScore(org.optaplanner.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore) ValueSource(org.junit.jupiter.params.provider.ValueSource) Logger(org.slf4j.Logger) Mockito.when(org.mockito.Mockito.when) Type(org.kie.kogito.explainability.model.Type) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) TestUtils(org.kie.kogito.explainability.TestUtils) NumericalFeatureDomain(org.kie.kogito.explainability.model.domain.NumericalFeatureDomain) Config(org.kie.kogito.explainability.Config) Collections(java.util.Collections) FeatureDomain(org.kie.kogito.explainability.model.domain.FeatureDomain) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) Prediction(org.kie.kogito.explainability.model.Prediction) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) ArrayList(java.util.ArrayList) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Feature(org.kie.kogito.explainability.model.Feature) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) CounterfactualEntity(org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity) TerminationConfig(org.optaplanner.core.config.solver.termination.TerminationConfig) Random(java.util.Random) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Output(org.kie.kogito.explainability.model.Output) UUID(java.util.UUID) SolverConfig(org.optaplanner.core.config.solver.SolverConfig) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 8 with PredictionOutput

use of org.kie.kogito.explainability.model.PredictionOutput in project kogito-apps by kiegroup.

the class CounterfactualExplainerTest method runCounterfactualSearch.

private CounterfactualResult runCounterfactualSearch(Long randomSeed, List<Output> goal, List<Feature> features, PredictionProvider model, double goalThresold) throws InterruptedException, ExecutionException, TimeoutException {
    final TerminationConfig terminationConfig = new TerminationConfig().withScoreCalculationCountLimit(steps);
    final SolverConfig solverConfig = SolverConfigBuilder.builder().withTerminationConfig(terminationConfig).build();
    solverConfig.setRandomSeed(randomSeed);
    solverConfig.setEnvironmentMode(EnvironmentMode.REPRODUCIBLE);
    final CounterfactualConfig counterfactualConfig = new CounterfactualConfig();
    counterfactualConfig.withSolverConfig(solverConfig).withGoalThreshold(goalThresold);
    final CounterfactualExplainer explainer = new CounterfactualExplainer(counterfactualConfig);
    final PredictionInput input = new PredictionInput(features);
    PredictionOutput output = new PredictionOutput(goal);
    Prediction prediction = new CounterfactualPrediction(input, output, null, UUID.randomUUID(), null);
    return explainer.explainAsync(prediction, model).get(predictionTimeOut, predictionTimeUnit);
}
Also used : TerminationConfig(org.optaplanner.core.config.solver.termination.TerminationConfig) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Prediction(org.kie.kogito.explainability.model.Prediction) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) SolverConfig(org.optaplanner.core.config.solver.SolverConfig) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction)

Example 9 with PredictionOutput

use of org.kie.kogito.explainability.model.PredictionOutput in project kogito-apps by kiegroup.

the class CounterfactualScoreCalculatorTest method BooleanDistanceNull.

@Test
void BooleanDistanceNull() {
    // Null as a goal
    Feature predictionFeature = FeatureFactory.newBooleanFeature("x", true);
    Feature goalFeature = FeatureFactory.newBooleanFeature("y", null);
    Output predictionOutput = outputFromFeature(predictionFeature);
    Output goalOutput = outputFromFeature(goalFeature);
    double distance = CounterFactualScoreCalculator.outputDistance(predictionOutput, goalOutput);
    assertEquals(Type.BOOLEAN, goalOutput.getType());
    assertEquals(1.0, distance);
    // Null as a prediction
    predictionFeature = FeatureFactory.newBooleanFeature("x", null);
    goalFeature = FeatureFactory.newBooleanFeature("y", false);
    predictionOutput = outputFromFeature(predictionFeature);
    goalOutput = outputFromFeature(goalFeature);
    distance = CounterFactualScoreCalculator.outputDistance(predictionOutput, goalOutput);
    assertEquals(Type.BOOLEAN, predictionOutput.getType());
    assertEquals(1.0, distance);
    // Null as both prediction and goal
    predictionFeature = FeatureFactory.newBooleanFeature("x", null);
    goalFeature = FeatureFactory.newBooleanFeature("y", null);
    predictionOutput = outputFromFeature(predictionFeature);
    goalOutput = outputFromFeature(goalFeature);
    distance = CounterFactualScoreCalculator.outputDistance(predictionOutput, goalOutput);
    assertEquals(Type.BOOLEAN, predictionOutput.getType());
    assertEquals(0.0, distance);
}
Also used : PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Output(org.kie.kogito.explainability.model.Output) Feature(org.kie.kogito.explainability.model.Feature) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 10 with PredictionOutput

use of org.kie.kogito.explainability.model.PredictionOutput in project kogito-apps by kiegroup.

the class CounterfactualScoreCalculatorTest method IntegerDistanceNull.

@ParameterizedTest
@ValueSource(ints = { 0, 1, 2, 3, 4 })
void IntegerDistanceNull(int seed) {
    final Random random = new Random(seed);
    final int value = random.nextInt(1000);
    // Null as a goal
    IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
        Feature predictionFeature = FeatureFactory.newNumericalFeature("x", value);
        Feature goalFeature = FeatureFactory.newNumericalFeature("x", null);
        Output predictionOutput = outputFromFeature(predictionFeature);
        Output goalOutput = outputFromFeature(goalFeature);
        CounterFactualScoreCalculator.outputDistance(predictionOutput, goalOutput);
    });
    assertEquals("Unsupported NaN or NULL for numeric feature 'x'", exception.getMessage());
    // Null as a prediction
    exception = assertThrows(IllegalArgumentException.class, () -> {
        Feature predictionFeature = FeatureFactory.newNumericalFeature("x", null);
        Feature goalFeature = FeatureFactory.newNumericalFeature("x", value);
        Output predictionOutput = outputFromFeature(predictionFeature);
        Output goalOutput = outputFromFeature(goalFeature);
        CounterFactualScoreCalculator.outputDistance(predictionOutput, goalOutput);
    });
    assertEquals("Unsupported NaN or NULL for numeric feature 'x'", exception.getMessage());
    // Null as both prediction and goal
    exception = assertThrows(IllegalArgumentException.class, () -> {
        Feature predictionFeature = FeatureFactory.newNumericalFeature("x", null);
        Feature goalFeature = FeatureFactory.newNumericalFeature("x", null);
        Output predictionOutput = outputFromFeature(predictionFeature);
        Output goalOutput = outputFromFeature(goalFeature);
        CounterFactualScoreCalculator.outputDistance(predictionOutput, goalOutput);
    });
    assertEquals("Unsupported NaN or NULL for numeric feature 'x'", exception.getMessage());
}
Also used : Random(java.util.Random) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Output(org.kie.kogito.explainability.model.Output) Feature(org.kie.kogito.explainability.model.Feature) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

PredictionOutput (org.kie.kogito.explainability.model.PredictionOutput)155 PredictionInput (org.kie.kogito.explainability.model.PredictionInput)137 PredictionProvider (org.kie.kogito.explainability.model.PredictionProvider)124 Prediction (org.kie.kogito.explainability.model.Prediction)122 Random (java.util.Random)90 Test (org.junit.jupiter.api.Test)90 SimplePrediction (org.kie.kogito.explainability.model.SimplePrediction)89 Feature (org.kie.kogito.explainability.model.Feature)80 ArrayList (java.util.ArrayList)74 Output (org.kie.kogito.explainability.model.Output)65 PerturbationContext (org.kie.kogito.explainability.model.PerturbationContext)65 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)55 LimeConfig (org.kie.kogito.explainability.local.lime.LimeConfig)52 LimeExplainer (org.kie.kogito.explainability.local.lime.LimeExplainer)50 Saliency (org.kie.kogito.explainability.model.Saliency)48 Value (org.kie.kogito.explainability.model.Value)47 LinkedList (java.util.LinkedList)37 List (java.util.List)36 LimeConfigOptimizer (org.kie.kogito.explainability.local.lime.optim.LimeConfigOptimizer)33 ValueSource (org.junit.jupiter.params.provider.ValueSource)32