Search in sources :

Example 41 with CounterfactualEntity

use of org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity in project kogito-apps by kiegroup.

the class CounterfactualExplainerTest method testCounterfactualMatchThreshold.

@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testCounterfactualMatchThreshold(int seed) throws ExecutionException, InterruptedException, TimeoutException {
    Random random = new Random();
    random.setSeed(seed);
    final double scoreThreshold = 0.9;
    final List<Output> goal = List.of(new Output("inside", Type.BOOLEAN, new Value(true), scoreThreshold));
    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 double center = 500.0;
    final double epsilon = 10.0;
    final PredictionProvider model = TestUtils.getSumThresholdModel(center, epsilon);
    final CounterfactualResult result = runCounterfactualSearch((long) seed, goal, features, model, DEFAULT_GOAL_THRESHOLD);
    final List<CounterfactualEntity> counterfactualEntities = result.getEntities();
    double totalSum = 0;
    for (CounterfactualEntity entity : counterfactualEntities) {
        totalSum += entity.asFeature().getValue().asNumber();
        logger.debug("Entity: {}", entity);
    }
    assertTrue(totalSum <= center + epsilon);
    assertTrue(totalSum >= center - epsilon);
    final List<Feature> cfFeatures = counterfactualEntities.stream().map(CounterfactualEntity::asFeature).collect(Collectors.toList());
    final PredictionInput cfInput = new PredictionInput(cfFeatures);
    final PredictionOutput cfOutput = model.predictAsync(List.of(cfInput)).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit()).get(0);
    final double predictionScore = cfOutput.getOutputs().get(0).getScore();
    logger.debug("Prediction score: {}", predictionScore);
    assertTrue(predictionScore >= scoreThreshold);
    assertTrue(result.isValid());
}
Also used : PredictionInput(org.kie.kogito.explainability.model.PredictionInput) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) 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) 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)

Example 42 with CounterfactualEntity

use of org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity in project kogito-apps by kiegroup.

the class CounterfactualExplainerTest method testCounterfactualMatchNoThreshold.

@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testCounterfactualMatchNoThreshold(int seed) throws ExecutionException, InterruptedException, TimeoutException {
    Random random = new Random();
    random.setSeed(seed);
    final double scoreThreshold = 0.0;
    final List<Output> goal = List.of(new Output("inside", Type.BOOLEAN, new Value(true), scoreThreshold));
    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 double center = 500.0;
    final double epsilon = 10.0;
    final PredictionProvider model = TestUtils.getSumThresholdModel(center, epsilon);
    final CounterfactualResult result = runCounterfactualSearch((long) seed, goal, features, model, DEFAULT_GOAL_THRESHOLD);
    final List<CounterfactualEntity> counterfactualEntities = result.getEntities();
    double totalSum = 0;
    for (CounterfactualEntity entity : counterfactualEntities) {
        totalSum += entity.asFeature().getValue().asNumber();
        logger.debug("Entity: {}", entity);
    }
    assertTrue(totalSum <= center + epsilon);
    assertTrue(totalSum >= center - epsilon);
    final List<Feature> cfFeatures = counterfactualEntities.stream().map(CounterfactualEntity::asFeature).collect(Collectors.toList());
    final PredictionInput cfInput = new PredictionInput(cfFeatures);
    final PredictionOutput cfOutput = model.predictAsync(List.of(cfInput)).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit()).get(0);
    final double predictionScore = cfOutput.getOutputs().get(0).getScore();
    logger.debug("Prediction score: {}", predictionScore);
    assertTrue(predictionScore < 0.5);
    assertTrue(result.isValid());
}
Also used : PredictionInput(org.kie.kogito.explainability.model.PredictionInput) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) 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) 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)

Example 43 with CounterfactualEntity

use of org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity in project kogito-apps by kiegroup.

the class CounterfactualScoreCalculatorTest method testNullBooleanInput.

/**
 * Null values for input Boolean features should be accepted as valid
 */
@Test
void testNullBooleanInput() throws ExecutionException, InterruptedException {
    final CounterFactualScoreCalculator scoreCalculator = new CounterFactualScoreCalculator();
    PredictionProvider model = TestUtils.getFeatureSkipModel(0);
    List<Feature> features = new ArrayList<>();
    List<FeatureDomain> featureDomains = new ArrayList<>();
    List<Boolean> constraints = new ArrayList<>();
    // f-1
    features.add(FeatureFactory.newNumericalFeature("f-1", 1.0));
    featureDomains.add(NumericalFeatureDomain.create(0.0, 10.0));
    constraints.add(false);
    // f-2
    features.add(FeatureFactory.newBooleanFeature("f-2", null));
    featureDomains.add(EmptyFeatureDomain.create());
    constraints.add(false);
    // f-3
    features.add(FeatureFactory.newBooleanFeature("f-3", true));
    featureDomains.add(EmptyFeatureDomain.create());
    constraints.add(false);
    PredictionInput input = new PredictionInput(features);
    PredictionFeatureDomain domains = new PredictionFeatureDomain(featureDomains);
    List<CounterfactualEntity> entities = CounterfactualEntityFactory.createEntities(input);
    List<Output> goal = new ArrayList<>();
    goal.add(new Output("f-2", Type.BOOLEAN, new Value(null), 0.0));
    goal.add(new Output("f-3", Type.BOOLEAN, new Value(true), 0.0));
    final CounterfactualSolution solution = new CounterfactualSolution(entities, features, model, goal, UUID.randomUUID(), UUID.randomUUID(), 0.0);
    BendableBigDecimalScore score = scoreCalculator.calculateScore(solution);
    List<PredictionOutput> predictionOutputs = model.predictAsync(List.of(input)).get();
    assertTrue(score.isFeasible());
    assertEquals(2, goal.size());
    // A single prediction is expected
    assertEquals(1, predictionOutputs.size());
    // Single prediction with two features
    assertEquals(2, predictionOutputs.get(0).getOutputs().size());
    assertEquals(0, score.getHardScore(0).compareTo(BigDecimal.ZERO));
    assertEquals(0, score.getHardScore(1).compareTo(BigDecimal.ZERO));
    assertEquals(0, score.getHardScore(2).compareTo(BigDecimal.ZERO));
    assertEquals(0, score.getSoftScore(0).compareTo(BigDecimal.ZERO));
    assertEquals(0, score.getSoftScore(1).compareTo(BigDecimal.ZERO));
    assertEquals(3, score.getHardLevelsSize());
    assertEquals(2, score.getSoftLevelsSize());
}
Also used : PredictionInput(org.kie.kogito.explainability.model.PredictionInput) ArrayList(java.util.ArrayList) BendableBigDecimalScore(org.optaplanner.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore) EmptyFeatureDomain(org.kie.kogito.explainability.model.domain.EmptyFeatureDomain) PredictionFeatureDomain(org.kie.kogito.explainability.model.PredictionFeatureDomain) NumericalFeatureDomain(org.kie.kogito.explainability.model.domain.NumericalFeatureDomain) FeatureDomain(org.kie.kogito.explainability.model.domain.FeatureDomain) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Feature(org.kie.kogito.explainability.model.Feature) CounterfactualEntity(org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity) PredictionFeatureDomain(org.kie.kogito.explainability.model.PredictionFeatureDomain) 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) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 44 with CounterfactualEntity

use of org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity in project kogito-apps by kiegroup.

the class CounterfactualScoreCalculatorTest method testGoalSizeLarger.

/**
 * Using a larger number of features in the goals (3) than the model's output (2) should
 * throw an {@link IllegalArgumentException} with the appropriate message.
 */
@Test
void testGoalSizeLarger() throws ExecutionException, InterruptedException {
    final CounterFactualScoreCalculator scoreCalculator = new CounterFactualScoreCalculator();
    PredictionProvider model = TestUtils.getFeatureSkipModel(0);
    List<Feature> features = new ArrayList<>();
    List<FeatureDomain> featureDomains = new ArrayList<>();
    List<Boolean> constraints = new ArrayList<>();
    // f-1
    features.add(FeatureFactory.newNumericalFeature("f-1", 1.0));
    featureDomains.add(NumericalFeatureDomain.create(0.0, 10.0));
    constraints.add(false);
    // f-2
    features.add(FeatureFactory.newNumericalFeature("f-2", 2.0));
    featureDomains.add(NumericalFeatureDomain.create(0.0, 10.0));
    constraints.add(false);
    // f-3
    features.add(FeatureFactory.newBooleanFeature("f-3", true));
    featureDomains.add(EmptyFeatureDomain.create());
    constraints.add(false);
    PredictionInput input = new PredictionInput(features);
    PredictionFeatureDomain domains = new PredictionFeatureDomain(featureDomains);
    List<CounterfactualEntity> entities = CounterfactualEntityFactory.createEntities(input);
    List<Output> goal = new ArrayList<>();
    goal.add(new Output("f-1", Type.NUMBER, new Value(1.0), 0.0));
    goal.add(new Output("f-2", Type.NUMBER, new Value(2.0), 0.0));
    goal.add(new Output("f-3", Type.BOOLEAN, new Value(true), 0.0));
    List<PredictionOutput> predictionOutputs = model.predictAsync(List.of(input)).get();
    assertEquals(3, goal.size());
    // A single prediction is expected
    assertEquals(1, predictionOutputs.size());
    // Single prediction with two features
    assertEquals(2, predictionOutputs.get(0).getOutputs().size());
    final CounterfactualSolution solution = new CounterfactualSolution(entities, features, model, goal, UUID.randomUUID(), UUID.randomUUID(), 0.0);
    IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
        scoreCalculator.calculateScore(solution);
    });
    assertEquals("Prediction size must be equal to goal size", exception.getMessage());
}
Also used : PredictionInput(org.kie.kogito.explainability.model.PredictionInput) ArrayList(java.util.ArrayList) EmptyFeatureDomain(org.kie.kogito.explainability.model.domain.EmptyFeatureDomain) PredictionFeatureDomain(org.kie.kogito.explainability.model.PredictionFeatureDomain) NumericalFeatureDomain(org.kie.kogito.explainability.model.domain.NumericalFeatureDomain) FeatureDomain(org.kie.kogito.explainability.model.domain.FeatureDomain) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Feature(org.kie.kogito.explainability.model.Feature) CounterfactualEntity(org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity) PredictionFeatureDomain(org.kie.kogito.explainability.model.PredictionFeatureDomain) 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) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 45 with CounterfactualEntity

use of org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity in project kogito-apps by kiegroup.

the class CounterfactualScoreCalculatorTest method testPrimarySoftScore.

/**
 * Test precision errors for primary soft score.
 * When the primary soft score is calculated between features with the same numerical
 * value a similarity of 1 is expected. For a large number of features, due to floating point errors this distance may be
 * in some cases slightly larger than 1, which will cause the distance (Math.sqrt(1.0-similarity)) to cause an exception.
 * The score calculation method should not let this should not occur.
 */
@ParameterizedTest
@ValueSource(ints = { 0, 1, 2, 3, 4 })
void testPrimarySoftScore(int seed) {
    final Random random = new Random(seed);
    final List<Feature> features = new ArrayList<>();
    final List<FeatureDomain> featureDomains = new ArrayList<>();
    final List<Boolean> constraints = new ArrayList<>();
    final int nFeatures = 1000;
    // Create a large number of identical features
    for (int n = 0; n < nFeatures; n++) {
        features.add(FeatureFactory.newNumericalFeature("f-" + n, random.nextDouble() * 1e-100));
        featureDomains.add(NumericalFeatureDomain.create(0.0, 10.0));
        constraints.add(false);
    }
    final PredictionInput input = new PredictionInput(features);
    final PredictionFeatureDomain domain = new PredictionFeatureDomain(featureDomains);
    final List<CounterfactualEntity> entities = CounterfactualEntityFactory.createEntities(input);
    // Create score calculator and model
    final CounterFactualScoreCalculator scoreCalculator = new CounterFactualScoreCalculator();
    PredictionProvider model = TestUtils.getFeatureSkipModel(0);
    // Create goal
    final List<Output> goal = new ArrayList<>();
    for (int n = 1; n < nFeatures; n++) {
        goal.add(new Output("f-" + n, Type.NUMBER, features.get(n).getValue(), 1.0));
    }
    final CounterfactualSolution solution = new CounterfactualSolution(entities, features, model, goal, UUID.randomUUID(), UUID.randomUUID(), 0.0);
    final BendableBigDecimalScore score = scoreCalculator.calculateScore(solution);
    assertEquals(0.0, score.getSoftScore(0).doubleValue(), 1e-5);
}
Also used : PredictionInput(org.kie.kogito.explainability.model.PredictionInput) ArrayList(java.util.ArrayList) BendableBigDecimalScore(org.optaplanner.core.api.score.buildin.bendablebigdecimal.BendableBigDecimalScore) EmptyFeatureDomain(org.kie.kogito.explainability.model.domain.EmptyFeatureDomain) PredictionFeatureDomain(org.kie.kogito.explainability.model.PredictionFeatureDomain) NumericalFeatureDomain(org.kie.kogito.explainability.model.domain.NumericalFeatureDomain) FeatureDomain(org.kie.kogito.explainability.model.domain.FeatureDomain) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Feature(org.kie.kogito.explainability.model.Feature) CounterfactualEntity(org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity) PredictionFeatureDomain(org.kie.kogito.explainability.model.PredictionFeatureDomain) Random(java.util.Random) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Output(org.kie.kogito.explainability.model.Output) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

CounterfactualEntity (org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity)45 Feature (org.kie.kogito.explainability.model.Feature)45 Test (org.junit.jupiter.api.Test)34 EmptyFeatureDomain (org.kie.kogito.explainability.model.domain.EmptyFeatureDomain)23 NumericalFeatureDomain (org.kie.kogito.explainability.model.domain.NumericalFeatureDomain)23 Output (org.kie.kogito.explainability.model.Output)22 PredictionOutput (org.kie.kogito.explainability.model.PredictionOutput)22 FeatureDomain (org.kie.kogito.explainability.model.domain.FeatureDomain)21 PredictionProvider (org.kie.kogito.explainability.model.PredictionProvider)18 Value (org.kie.kogito.explainability.model.Value)18 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)17 PredictionInput (org.kie.kogito.explainability.model.PredictionInput)17 LinkedList (java.util.LinkedList)16 CategoricalFeatureDomain (org.kie.kogito.explainability.model.domain.CategoricalFeatureDomain)16 Random (java.util.Random)14 ValueSource (org.junit.jupiter.params.provider.ValueSource)13 BinaryFeatureDomain (org.kie.kogito.explainability.model.domain.BinaryFeatureDomain)12 CurrencyFeatureDomain (org.kie.kogito.explainability.model.domain.CurrencyFeatureDomain)12 DurationFeatureDomain (org.kie.kogito.explainability.model.domain.DurationFeatureDomain)12 ObjectFeatureDomain (org.kie.kogito.explainability.model.domain.ObjectFeatureDomain)12