Search in sources :

Example 21 with Feature

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

the class CounterfactualExplainerTest method testCounterfactualMatch.

@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testCounterfactualMatch(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.0d));
    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", 150.0, NumericalFeatureDomain.create(0.0, 1000.0)));
    features.add(FeatureFactory.newNumericalFeature("f-num3", 1.0, NumericalFeatureDomain.create(0.0, 1000.0)));
    features.add(FeatureFactory.newNumericalFeature("f-num4", 2.0, NumericalFeatureDomain.create(0.0, 1000.0)));
    final double center = 500.0;
    final double epsilon = 10.0;
    final CounterfactualResult result = runCounterfactualSearch((long) seed, goal, features, TestUtils.getSumThresholdModel(center, epsilon), DEFAULT_GOAL_THRESHOLD);
    double totalSum = 0;
    for (CounterfactualEntity entity : result.getEntities()) {
        totalSum += entity.asFeature().getValue().asNumber();
        logger.debug("Entity: {}", entity);
    }
    logger.debug("Outputs: {}", result.getOutput().get(0).getOutputs());
    assertTrue(totalSum <= center + epsilon);
    assertTrue(totalSum >= center - epsilon);
    assertTrue(result.isValid());
}
Also used : 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) Feature(org.kie.kogito.explainability.model.Feature) LinkedList(java.util.LinkedList) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 22 with Feature

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

the class CounterfactualExplainerTest method testCounterfactualCategoricalNotStrict.

/**
 * Search for a counterfactual using categorical features with the Symbolic arithmetic model.
 * The outcome match is not strict (goal threshold of 0.01).
 * The CF should be valid with this number of iterations.
 *
 * @param seed
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws TimeoutException
 */
@ParameterizedTest
@ValueSource(ints = { 0, 1, 2 })
void testCounterfactualCategoricalNotStrict(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.01);
    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.5;
    assertTrue(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)

Example 23 with Feature

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

the class CounterfactualExplainerTest method testSparsity.

/**
 * The test rationale is to find the solution to (f-num1 + f-num2 = 10), for f-num1 with an initial
 * value of 0 and f-num2 with an initial value of 5 and both varying in [0, 10].
 * All the possible solutions will have the same distance, but the sparsity
 * criteria will select the ones which leave one of the inputs (either f-num1 or f-num2) unchanged.
 *
 * @param seed
 * @throws ExecutionException
 * @throws InterruptedException
 * @throws TimeoutException
 */
@ParameterizedTest
@ValueSource(ints = { 0, 1, 2, 3, 4 })
void testSparsity(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 ArrayList<>();
    features.add(FeatureFactory.newNumericalFeature("f-num1", 0, NumericalFeatureDomain.create(0, 10)));
    features.add(FeatureFactory.newNumericalFeature("f-num2", 5, NumericalFeatureDomain.create(0, 10)));
    final double center = 10.0;
    final double epsilon = 0.1;
    final CounterfactualResult result = runCounterfactualSearch((long) seed, goal, features, TestUtils.getSumThresholdModel(center, epsilon), DEFAULT_GOAL_THRESHOLD);
    assertTrue(!result.getEntities().get(0).isChanged() || !result.getEntities().get(1).isChanged());
    assertTrue(result.isValid());
}
Also used : 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) ArrayList(java.util.ArrayList) Feature(org.kie.kogito.explainability.model.Feature) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 24 with Feature

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

the class CounterfactualScoreCalculatorTest method IntegerDistanceSameValueZero.

@ParameterizedTest
@ValueSource(ints = { 0, 1, 2, 3, 4 })
void IntegerDistanceSameValueZero(int seed) {
    final Random random = new Random(seed);
    final int value = 0;
    Feature x = FeatureFactory.newNumericalFeature("x", value);
    Feature y = FeatureFactory.newNumericalFeature("y", value);
    Output ox = outputFromFeature(x);
    Output oy = outputFromFeature(y);
    // Use a random threshold, mustn't make a difference
    final double distance = CounterFactualScoreCalculator.outputDistance(ox, oy, random.nextDouble());
    assertEquals(Type.NUMBER, ox.getType());
    assertEquals(0.0, Math.abs(distance));
}
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)

Example 25 with Feature

use of org.kie.kogito.explainability.model.Feature 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)

Aggregations

Feature (org.kie.kogito.explainability.model.Feature)233 PredictionOutput (org.kie.kogito.explainability.model.PredictionOutput)118 Test (org.junit.jupiter.api.Test)107 PredictionInput (org.kie.kogito.explainability.model.PredictionInput)107 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)104 Output (org.kie.kogito.explainability.model.Output)102 ArrayList (java.util.ArrayList)97 Random (java.util.Random)92 PredictionProvider (org.kie.kogito.explainability.model.PredictionProvider)78 Value (org.kie.kogito.explainability.model.Value)74 LinkedList (java.util.LinkedList)72 ValueSource (org.junit.jupiter.params.provider.ValueSource)71 Prediction (org.kie.kogito.explainability.model.Prediction)67 List (java.util.List)51 CounterfactualEntity (org.kie.kogito.explainability.local.counterfactual.entities.CounterfactualEntity)46 PerturbationContext (org.kie.kogito.explainability.model.PerturbationContext)42 Type (org.kie.kogito.explainability.model.Type)39 NumericalFeatureDomain (org.kie.kogito.explainability.model.domain.NumericalFeatureDomain)37 SimplePrediction (org.kie.kogito.explainability.model.SimplePrediction)35 FeatureDomain (org.kie.kogito.explainability.model.domain.FeatureDomain)33