Search in sources :

Example 36 with Saliency

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

the class DummyModelsLimeExplainerTest method testMapOneFeatureToOutputRegression.

@ParameterizedTest
@ValueSource(longs = { 0 })
void testMapOneFeatureToOutputRegression(long seed) throws Exception {
    Random random = new Random();
    int idx = 1;
    List<Feature> features = new LinkedList<>();
    features.add(TestUtils.getMockedNumericFeature(100));
    features.add(TestUtils.getMockedNumericFeature(20));
    features.add(TestUtils.getMockedNumericFeature(0.1));
    PredictionInput input = new PredictionInput(features);
    PredictionProvider model = TestUtils.getFeaturePassModel(idx);
    List<PredictionOutput> outputs = model.predictAsync(List.of(input)).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
    Prediction prediction = new SimplePrediction(input, outputs.get(0));
    LimeConfig limeConfig = new LimeConfig().withSamples(100).withPerturbationContext(new PerturbationContext(seed, random, 1));
    LimeExplainer limeExplainer = new LimeExplainer(limeConfig);
    Map<String, Saliency> saliencyMap = limeExplainer.explainAsync(prediction, model).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
    for (Saliency saliency : saliencyMap.values()) {
        assertNotNull(saliency);
        List<FeatureImportance> topFeatures = saliency.getTopFeatures(3);
        assertEquals(3, topFeatures.size());
        assertEquals(1d, ExplainabilityMetrics.impactScore(model, prediction, topFeatures));
    }
    int topK = 1;
    double minimumPositiveStabilityRate = 0.5;
    double minimumNegativeStabilityRate = 0.5;
    TestUtils.assertLimeStability(model, prediction, limeExplainer, topK, minimumPositiveStabilityRate, minimumNegativeStabilityRate);
    List<PredictionInput> inputs = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        List<Feature> fs = new LinkedList<>();
        fs.add(TestUtils.getMockedNumericFeature());
        fs.add(TestUtils.getMockedNumericFeature());
        fs.add(TestUtils.getMockedNumericFeature());
        inputs.add(new PredictionInput(fs));
    }
    DataDistribution distribution = new PredictionInputsDataDistribution(inputs);
    int k = 2;
    int chunkSize = 10;
    String decision = "feature-" + idx;
    double precision = ExplainabilityMetrics.getLocalSaliencyPrecision(decision, model, limeExplainer, distribution, k, chunkSize);
    assertThat(precision).isZero();
    double recall = ExplainabilityMetrics.getLocalSaliencyRecall(decision, model, limeExplainer, distribution, k, chunkSize);
    assertThat(recall).isEqualTo(1);
    double f1 = ExplainabilityMetrics.getLocalSaliencyF1(decision, model, limeExplainer, distribution, k, chunkSize);
    assertThat(f1).isZero();
}
Also used : SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) PerturbationContext(org.kie.kogito.explainability.model.PerturbationContext) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) Prediction(org.kie.kogito.explainability.model.Prediction) SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) ArrayList(java.util.ArrayList) Saliency(org.kie.kogito.explainability.model.Saliency) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Feature(org.kie.kogito.explainability.model.Feature) LinkedList(java.util.LinkedList) Random(java.util.Random) FeatureImportance(org.kie.kogito.explainability.model.FeatureImportance) PredictionInputsDataDistribution(org.kie.kogito.explainability.model.PredictionInputsDataDistribution) DataDistribution(org.kie.kogito.explainability.model.DataDistribution) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) PredictionInputsDataDistribution(org.kie.kogito.explainability.model.PredictionInputsDataDistribution) ValueSource(org.junit.jupiter.params.provider.ValueSource) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 37 with Saliency

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

the class ExplainabilityMetricsTest method testFidelityWithEvenSumModel.

@Test
void testFidelityWithEvenSumModel() throws ExecutionException, InterruptedException, TimeoutException {
    List<Pair<Saliency, Prediction>> pairs = new LinkedList<>();
    LimeConfig limeConfig = new LimeConfig().withSamples(10);
    LimeExplainer limeExplainer = new LimeExplainer(limeConfig);
    PredictionProvider model = TestUtils.getEvenSumModel(1);
    List<Feature> features = new LinkedList<>();
    features.add(FeatureFactory.newNumericalFeature("f-1", 1));
    features.add(FeatureFactory.newNumericalFeature("f-2", 2));
    features.add(FeatureFactory.newNumericalFeature("f-3", 3));
    PredictionInput input = new PredictionInput(features);
    Prediction prediction = new SimplePrediction(input, model.predictAsync(List.of(input)).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit()).get(0));
    Map<String, Saliency> saliencyMap = limeExplainer.explainAsync(prediction, model).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
    for (Saliency saliency : saliencyMap.values()) {
        pairs.add(Pair.of(saliency, prediction));
    }
    Assertions.assertDoesNotThrow(() -> {
        ExplainabilityMetrics.classificationFidelity(pairs);
    });
}
Also used : SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) LimeExplainer(org.kie.kogito.explainability.local.lime.LimeExplainer) Prediction(org.kie.kogito.explainability.model.Prediction) SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) Saliency(org.kie.kogito.explainability.model.Saliency) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Feature(org.kie.kogito.explainability.model.Feature) LinkedList(java.util.LinkedList) LimeConfig(org.kie.kogito.explainability.local.lime.LimeConfig) Pair(org.apache.commons.lang3.tuple.Pair) Test(org.junit.jupiter.api.Test)

Example 38 with Saliency

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

the class ShapKernelExplainerTest method shapTestCase.

/*
     * given a specific model, config, background, explanations, and expected shap values,
     * test that the computed shape values match expected shap values
     */
private void shapTestCase(PredictionProvider model, ShapConfig skConfig, double[][] toExplainRaw, double[][][] expected) throws InterruptedException, TimeoutException, ExecutionException {
    // establish background data and desired data to explain
    List<PredictionInput> toExplain = createPIFromMatrix(toExplainRaw);
    // initialize explainer
    List<PredictionOutput> predictionOutputs = model.predictAsync(toExplain).get(5, TimeUnit.SECONDS);
    List<Prediction> predictions = new ArrayList<>();
    for (int i = 0; i < predictionOutputs.size(); i++) {
        predictions.add(new SimplePrediction(toExplain.get(i), predictionOutputs.get(i)));
    }
    // evaluate if the explanations match the expected value
    ShapKernelExplainer ske = new ShapKernelExplainer(skConfig);
    for (int i = 0; i < toExplain.size(); i++) {
        // explanations shape: outputSize x nfeatures
        Saliency[] explanationSaliencies = ske.explainAsync(predictions.get(i), model).get(5, TimeUnit.SECONDS).getSaliencies();
        RealMatrix explanations = saliencyToMatrix(explanationSaliencies)[0];
        for (int j = 0; j < explanations.getRowDimension(); j++) {
            assertArrayEquals(expected[i][j], explanations.getRow(j), 1e-6);
        }
    }
}
Also used : SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) Prediction(org.kie.kogito.explainability.model.Prediction) SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) ArrayList(java.util.ArrayList) Saliency(org.kie.kogito.explainability.model.Saliency) RealMatrix(org.apache.commons.math3.linear.RealMatrix) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput)

Example 39 with Saliency

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

the class ShapKernelExplainerTest method testManyFeatureRegularization.

@Test
void testManyFeatureRegularization() throws ExecutionException, InterruptedException {
    RealVector modelWeights = MatrixUtils.createRealMatrix(generateN(1, 25, "5021")).getRowVector(0);
    PredictionProvider model = TestUtils.getLinearModel(modelWeights.toArray());
    RealMatrix data = MatrixUtils.createRealMatrix(generateN(101, 25, "8629"));
    List<PredictionInput> toExplain = createPIFromMatrix(data.getRowMatrix(100).getData());
    List<PredictionOutput> predictionOutputs = model.predictAsync(toExplain).get();
    RealVector predictionOutputVector = MatrixUtilsExtensions.vectorFromPredictionOutput(predictionOutputs.get(0));
    Prediction p = new SimplePrediction(toExplain.get(0), predictionOutputs.get(0));
    List<PredictionInput> bg = createPIFromMatrix(data.getSubMatrix(0, 99, 0, 24).getData());
    List<ShapConfig.Builder> testConfigs = List.of(testConfig.copy().withBackground(bg).withRegularizer(ShapConfig.RegularizerType.AIC), testConfig.copy().withBackground(bg).withRegularizer(ShapConfig.RegularizerType.BIC), testConfig.copy().withBackground(bg).withRegularizer(10), testConfig.copy().withBackground(bg).withRegularizer(ShapConfig.RegularizerType.NONE));
    List<Integer> nsamples = List.of(1000, 2000, 5000);
    for (Integer nsamp : nsamples) {
        for (ShapConfig.Builder sk : testConfigs) {
            ShapKernelExplainer ske = new ShapKernelExplainer(sk.withNSamples(nsamp).build());
            ShapResults shapResults = ske.explainAsync(p, model).get();
            Saliency[] saliencies = shapResults.getSaliencies();
            RealMatrix[] explanationsAndConfs = saliencyToMatrix(saliencies);
            RealMatrix explanations = explanationsAndConfs[0];
            double actualOut = predictionOutputVector.getEntry(0);
            double predOut = MatrixUtilsExtensions.sum(explanations.getRowVector(0)) + shapResults.getFnull().getEntry(0);
            assertTrue(Math.abs(predOut - actualOut) < 1e-6);
            double coefMSE = (data.getRowVector(100).ebeMultiply(modelWeights)).getDistance(explanations.getRowVector(0));
            assertTrue(coefMSE < 10);
        }
    }
}
Also used : SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) Prediction(org.kie.kogito.explainability.model.Prediction) SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) Saliency(org.kie.kogito.explainability.model.Saliency) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) BigInteger(java.math.BigInteger) RealMatrix(org.apache.commons.math3.linear.RealMatrix) RealVector(org.apache.commons.math3.linear.RealVector) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 40 with Saliency

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

the class ShapKernelExplainerTest method testLargeBackground.

// Test cases where search space cannot be fully enumerated ========================================================
@Test
void testLargeBackground() throws InterruptedException, TimeoutException, ExecutionException {
    // establish background data and desired data to explain
    double[][] largeBackground = new double[100][10];
    for (int i = 0; i < 100; i++) {
        for (int j = 0; j < 10; j++) {
            largeBackground[i][j] = i / 100. + j;
        }
    }
    double[][] toExplainLargeBackground = { { 0, 1., -2., 3.5, -4.1, 5.5, -12., .8, .11, 15. } };
    double[][][] expected = { { { -0.495, 0., -4.495, 0.005, -8.595, 0.005, -18.495, -6.695, -8.385, 5.505 } } };
    List<PredictionInput> background = createPIFromMatrix(largeBackground);
    List<PredictionInput> toExplain = createPIFromMatrix(toExplainLargeBackground);
    PredictionProvider model = TestUtils.getSumSkipModel(1);
    ShapConfig skConfig = testConfig.withBackground(background).build();
    // initialize explainer
    List<PredictionOutput> predictionOutputs = model.predictAsync(toExplain).get();
    List<Prediction> predictions = new ArrayList<>();
    for (int i = 0; i < predictionOutputs.size(); i++) {
        predictions.add(new SimplePrediction(toExplain.get(i), predictionOutputs.get(i)));
    }
    // evaluate if the explanations match the expected value
    ShapKernelExplainer ske = new ShapKernelExplainer(skConfig);
    for (int i = 0; i < toExplain.size(); i++) {
        Saliency[] explanationSaliencies = ske.explainAsync(predictions.get(i), model).get(5, TimeUnit.SECONDS).getSaliencies();
        RealMatrix[] explanationsAndConfs = saliencyToMatrix(explanationSaliencies);
        RealMatrix explanations = explanationsAndConfs[0];
        for (int j = 0; j < explanations.getRowDimension(); j++) {
            assertArrayEquals(expected[i][j], explanations.getRow(j), 1e-2);
        }
    }
}
Also used : SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) Prediction(org.kie.kogito.explainability.model.Prediction) SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) ArrayList(java.util.ArrayList) Saliency(org.kie.kogito.explainability.model.Saliency) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) RealMatrix(org.apache.commons.math3.linear.RealMatrix) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

Saliency (org.kie.kogito.explainability.model.Saliency)51 Prediction (org.kie.kogito.explainability.model.Prediction)44 PredictionInput (org.kie.kogito.explainability.model.PredictionInput)43 PredictionOutput (org.kie.kogito.explainability.model.PredictionOutput)43 PredictionProvider (org.kie.kogito.explainability.model.PredictionProvider)39 SimplePrediction (org.kie.kogito.explainability.model.SimplePrediction)39 ArrayList (java.util.ArrayList)34 Random (java.util.Random)28 Feature (org.kie.kogito.explainability.model.Feature)26 PerturbationContext (org.kie.kogito.explainability.model.PerturbationContext)26 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)25 Test (org.junit.jupiter.api.Test)23 FeatureImportance (org.kie.kogito.explainability.model.FeatureImportance)23 DataDistribution (org.kie.kogito.explainability.model.DataDistribution)21 PredictionInputsDataDistribution (org.kie.kogito.explainability.model.PredictionInputsDataDistribution)18 ValueSource (org.junit.jupiter.params.provider.ValueSource)16 LimeConfig (org.kie.kogito.explainability.local.lime.LimeConfig)16 LimeExplainer (org.kie.kogito.explainability.local.lime.LimeExplainer)16 LinkedList (java.util.LinkedList)13 RealMatrix (org.apache.commons.math3.linear.RealMatrix)9