Search in sources :

Example 76 with Output

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

the class TestUtils method getEvenFeatureModel.

public static PredictionProvider getEvenFeatureModel(int featureIndex) {
    return inputs -> supplyAsync(() -> {
        List<PredictionOutput> predictionOutputs = new LinkedList<>();
        for (PredictionInput predictionInput : inputs) {
            List<Feature> features = predictionInput.getFeatures();
            Feature feature = features.get(featureIndex);
            double v = feature.getValue().asNumber();
            PredictionOutput predictionOutput = new PredictionOutput(List.of(new Output("feature-" + featureIndex, Type.BOOLEAN, new Value(v % 2 == 0), 1d)));
            predictionOutputs.add(predictionOutput);
        }
        return predictionOutputs;
    });
}
Also used : Arrays(java.util.Arrays) LimeExplainer(org.kie.kogito.explainability.local.lime.LimeExplainer) Feature(org.kie.kogito.explainability.model.Feature) Prediction(org.kie.kogito.explainability.model.Prediction) Random(java.util.Random) Mockito.when(org.mockito.Mockito.when) Value(org.kie.kogito.explainability.model.Value) Type(org.kie.kogito.explainability.model.Type) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) ArrayList(java.util.ArrayList) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) List(java.util.List) Pair(org.apache.commons.lang3.tuple.Pair) Output(org.kie.kogito.explainability.model.Output) CompletableFuture.supplyAsync(java.util.concurrent.CompletableFuture.supplyAsync) Optional(java.util.Optional) ValidationUtils(org.kie.kogito.explainability.utils.ValidationUtils) LinkedList(java.util.LinkedList) Assertions.assertDoesNotThrow(org.junit.jupiter.api.Assertions.assertDoesNotThrow) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Mockito.mock(org.mockito.Mockito.mock) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Output(org.kie.kogito.explainability.model.Output) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Value(org.kie.kogito.explainability.model.Value) Feature(org.kie.kogito.explainability.model.Feature) LinkedList(java.util.LinkedList)

Example 77 with Output

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

the class PartialDependencePlotExplainerTest method getMetadata.

private PredictionProviderMetadata getMetadata(Random random) {
    return new PredictionProviderMetadata() {

        @Override
        public DataDistribution getDataDistribution() {
            return DataUtils.generateRandomDataDistribution(3, 100, random);
        }

        @Override
        public PredictionInput getInputShape() {
            List<Feature> features = new LinkedList<>();
            features.add(FeatureFactory.newNumericalFeature("f0", 0));
            features.add(FeatureFactory.newNumericalFeature("f1", 0));
            features.add(FeatureFactory.newNumericalFeature("f2", 0));
            return new PredictionInput(features);
        }

        @Override
        public PredictionOutput getOutputShape() {
            List<Output> outputs = new LinkedList<>();
            outputs.add(new Output("sum-but0", Type.BOOLEAN, new Value(false), 0d));
            return new PredictionOutput(outputs);
        }
    };
}
Also used : PredictionInput(org.kie.kogito.explainability.model.PredictionInput) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Output(org.kie.kogito.explainability.model.Output) PredictionProviderMetadata(org.kie.kogito.explainability.model.PredictionProviderMetadata) Value(org.kie.kogito.explainability.model.Value) Feature(org.kie.kogito.explainability.model.Feature) LinkedList(java.util.LinkedList)

Example 78 with Output

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

the class CounterfactualExplainerTest method testConsumers.

@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testConsumers(int seed) throws ExecutionException, InterruptedException, TimeoutException {
    Random random = new Random();
    random.setSeed(seed);
    final List<Output> goal = List.of(new Output("inside", Type.BOOLEAN, new Value(true), 0.0));
    List<Feature> features = new LinkedList<>();
    features.add(FeatureFactory.newNumericalFeature("f-num1", 100.0, NumericalFeatureDomain.create(0.0, 1000.0)));
    features.add(FeatureFactory.newNumericalFeature("f-num2", 100.0, NumericalFeatureDomain.create(0.0, 1000.0)));
    features.add(FeatureFactory.newNumericalFeature("f-num3", 100.0, NumericalFeatureDomain.create(0.0, 1000.0)));
    features.add(FeatureFactory.newNumericalFeature("f-num4", 100.0, NumericalFeatureDomain.create(0.0, 1000.0)));
    final TerminationConfig terminationConfig = new TerminationConfig().withScoreCalculationCountLimit(10_000L);
    // for the purpose of this test, only a few steps are necessary
    final SolverConfig solverConfig = SolverConfigBuilder.builder().withTerminationConfig(terminationConfig).build();
    solverConfig.setRandomSeed((long) seed);
    solverConfig.setEnvironmentMode(EnvironmentMode.REPRODUCIBLE);
    @SuppressWarnings("unchecked") final Consumer<CounterfactualResult> assertIntermediateCounterfactualNotNull = mock(Consumer.class);
    final CounterfactualConfig counterfactualConfig = new CounterfactualConfig().withSolverConfig(solverConfig).withGoalThreshold(0.01);
    final CounterfactualExplainer counterfactualExplainer = new CounterfactualExplainer(counterfactualConfig);
    PredictionInput input = new PredictionInput(features);
    final double center = 500.0;
    final double epsilon = 10.0;
    final PredictionProvider model = TestUtils.getSumThresholdModel(center, epsilon);
    PredictionOutput output = new PredictionOutput(goal);
    Prediction prediction = new CounterfactualPrediction(input, output, null, UUID.randomUUID(), null);
    final CounterfactualResult counterfactualResult = counterfactualExplainer.explainAsync(prediction, model, assertIntermediateCounterfactualNotNull).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
    for (CounterfactualEntity entity : counterfactualResult.getEntities()) {
        logger.debug("Entity: {}", entity);
    }
    logger.debug("Outputs: {}", counterfactualResult.getOutput().get(0).getOutputs());
    // At least one intermediate result is generated
    verify(assertIntermediateCounterfactualNotNull, atLeast(1)).accept(any());
}
Also used : PredictionInput(org.kie.kogito.explainability.model.PredictionInput) Prediction(org.kie.kogito.explainability.model.Prediction) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Feature(org.kie.kogito.explainability.model.Feature) LinkedList(java.util.LinkedList) 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) Value(org.kie.kogito.explainability.model.Value) SolverConfig(org.optaplanner.core.config.solver.SolverConfig) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 79 with Output

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

the class CounterfactualExplainerTest method testNonEmptyInput.

@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testNonEmptyInput(int seed) throws ExecutionException, InterruptedException, TimeoutException {
    Random random = new Random();
    random.setSeed(seed);
    final List<Output> goal = List.of(new Output("class", Type.NUMBER, new Value(10.0), 0.0d));
    List<Feature> features = new LinkedList<>();
    for (int i = 0; i < 4; i++) {
        features.add(FeatureFactory.newNumericalFeature("f-" + i, random.nextDouble(), NumericalFeatureDomain.create(0.0, 1000.0)));
    }
    final TerminationConfig terminationConfig = new TerminationConfig().withScoreCalculationCountLimit(10L);
    // for the purpose of this test, only a few steps are necessary
    final SolverConfig solverConfig = SolverConfigBuilder.builder().withTerminationConfig(terminationConfig).build();
    solverConfig.setRandomSeed((long) seed);
    solverConfig.setEnvironmentMode(EnvironmentMode.REPRODUCIBLE);
    final CounterfactualConfig counterfactualConfig = new CounterfactualConfig().withSolverConfig(solverConfig);
    final CounterfactualExplainer counterfactualExplainer = new CounterfactualExplainer(counterfactualConfig);
    PredictionProvider model = TestUtils.getSumSkipModel(0);
    PredictionInput input = new PredictionInput(features);
    PredictionOutput output = new PredictionOutput(goal);
    Prediction prediction = new CounterfactualPrediction(input, output, null, UUID.randomUUID(), null);
    final CounterfactualResult counterfactualResult = counterfactualExplainer.explainAsync(prediction, model).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
    for (CounterfactualEntity entity : counterfactualResult.getEntities()) {
        logger.debug("Entity: {}", entity);
    }
    logger.debug("Outputs: {}", counterfactualResult.getOutput().get(0).getOutputs());
    assertNotNull(counterfactualResult);
    assertNotNull(counterfactualResult.getEntities());
}
Also used : PredictionInput(org.kie.kogito.explainability.model.PredictionInput) Prediction(org.kie.kogito.explainability.model.Prediction) CounterfactualPrediction(org.kie.kogito.explainability.model.CounterfactualPrediction) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Feature(org.kie.kogito.explainability.model.Feature) LinkedList(java.util.LinkedList) 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) Value(org.kie.kogito.explainability.model.Value) SolverConfig(org.optaplanner.core.config.solver.SolverConfig) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 80 with Output

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

the class CounterfactualExplainerTest method testCounterfactualCategoricalStrictFail.

/**
 * Search for a counterfactual using categorical features with the Symbolic arithmetic model.
 * The outcome match is strict (goal threshold of zero).
 * The CF should be invalid with this number of iterations.
 *
 * @param seed
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws TimeoutException
 */
@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testCounterfactualCategoricalStrictFail(int seed) throws ExecutionException, InterruptedException, TimeoutException {
    Random random = new Random();
    random.setSeed(seed);
    final List<Output> goal = List.of(new Output("result", Type.NUMBER, new Value(25.0), 0.0d));
    List<Feature> features = new LinkedList<>();
    features.add(FeatureFactory.newNumericalFeature("x-1", 5.0, NumericalFeatureDomain.create(0.0, 100.0)));
    features.add(FeatureFactory.newNumericalFeature("x-2", 40.0, NumericalFeatureDomain.create(0.0, 100.0)));
    features.add(FeatureFactory.newCategoricalFeature("operand", "*", CategoricalFeatureDomain.create("+", "-", "/", "*")));
    final CounterfactualResult result = runCounterfactualSearch((long) seed, goal, features, TestUtils.getSymbolicArithmeticModel(), 0.0);
    final List<CounterfactualEntity> counterfactualEntities = result.getEntities();
    Stream<Feature> counterfactualFeatures = counterfactualEntities.stream().map(CounterfactualEntity::asFeature);
    String operand = counterfactualFeatures.filter(feature -> feature.getName().equals("operand")).findFirst().get().getValue().asString();
    List<Feature> numericalFeatures = counterfactualEntities.stream().map(CounterfactualEntity::asFeature).filter(feature -> !feature.getName().equals("operand")).collect(Collectors.toList());
    double opResult = 0.0;
    for (Feature feature : numericalFeatures) {
        switch(operand) {
            case "+":
                opResult += feature.getValue().asNumber();
                break;
            case "-":
                opResult -= feature.getValue().asNumber();
                break;
            case "*":
                opResult *= feature.getValue().asNumber();
                break;
            case "/":
                opResult /= feature.getValue().asNumber();
                break;
        }
    }
    final double epsilon = 0.1;
    assertFalse(result.isValid());
    assertTrue(opResult <= 25.0 + epsilon);
    assertTrue(opResult >= 25.0 - epsilon);
}
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) Feature(org.kie.kogito.explainability.model.Feature) LinkedList(java.util.LinkedList) CounterfactualEntity(org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity) Random(java.util.Random) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Output(org.kie.kogito.explainability.model.Output) Value(org.kie.kogito.explainability.model.Value) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

Output (org.kie.kogito.explainability.model.Output)120 PredictionOutput (org.kie.kogito.explainability.model.PredictionOutput)109 Feature (org.kie.kogito.explainability.model.Feature)102 Value (org.kie.kogito.explainability.model.Value)63 Random (java.util.Random)61 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)59 PredictionInput (org.kie.kogito.explainability.model.PredictionInput)57 PredictionProvider (org.kie.kogito.explainability.model.PredictionProvider)52 ArrayList (java.util.ArrayList)47 ValueSource (org.junit.jupiter.params.provider.ValueSource)47 Prediction (org.kie.kogito.explainability.model.Prediction)46 Test (org.junit.jupiter.api.Test)42 List (java.util.List)39 Type (org.kie.kogito.explainability.model.Type)36 LinkedList (java.util.LinkedList)35 CounterfactualEntity (org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity)23 Mockito.mock (org.mockito.Mockito.mock)20 Optional (java.util.Optional)19 ExecutionException (java.util.concurrent.ExecutionException)19 Collectors (java.util.stream.Collectors)18