Search in sources :

Example 11 with PredictionProvider

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

the class ShapKernelExplainer method explain.

/**
 * Compute the shap values for a specific prediction
 *
 * @param prediction: The ShapPrediction to be explained.
 * @param model: The PredictionProvider we are explaining.
 *
 * @return the shap values for this prediction, of shape [n_model_outputs x n_features]
 */
private CompletableFuture<ShapResults> explain(Prediction prediction, PredictionProvider model) {
    ShapDataCarrier sdc = this.initialize(model);
    sdc.setSamplesAdded(new ArrayList<>());
    PredictionInput pi = prediction.getInput();
    PredictionOutput po = prediction.getOutput();
    if (pi.getFeatures().size() != sdc.getCols()) {
        throw new IllegalArgumentException(String.format("Prediction input feature count (%d) does not match background data feature count (%d)", pi.getFeatures().size(), sdc.getCols()));
    }
    int cols = sdc.getCols();
    CompletableFuture<RealMatrix> output = sdc.getOutputSize().thenApply(os -> {
        if (po.getOutputs().size() != os) {
            throw new IllegalArgumentException(String.format("Prediction output size (%d) does not match background data output size (%d)", po.getOutputs().size(), os));
        }
        return MatrixUtils.createRealMatrix(new double[os][cols]);
    });
    RealVector poVector = MatrixUtilsExtensions.vectorFromPredictionOutput(po);
    // first find varying features
    this.setVaryingFeatureGroups(pi, sdc);
    // if no features vary, then the features do not effect output, and all shap values are zero.
    if (sdc.getNumVarying() == 0) {
        return output.thenApply(o -> saliencyFromMatrix(o, pi, po)).thenCombine(sdc.getFnull(), ShapResults::new);
    } else if (sdc.getNumVarying() == 1) // if 1 feature varies, this feature has all the effect
    {
        CompletableFuture<RealVector> diff = sdc.getLinkNull().thenApply(poVector::subtract);
        return output.thenCompose(o -> diff.thenCombine(sdc.getOutputSize(), (df, os) -> {
            RealMatrix out = MatrixUtils.createRealMatrix(new double[os][cols]);
            for (int i = 0; i < os; i++) {
                out.setEntry(i, sdc.getVaryingFeatureGroups(0), df.getEntry(i));
            }
            return saliencyFromMatrix(out, pi, po);
        })).thenCombine(sdc.getFnull(), ShapResults::new);
    } else // if more than 1 feature varies, we need to perform WLR
    {
        // establish sizes of feature permutations (called subsets)
        ShapStatistics shapStats = this.computeSubsetStatistics(sdc);
        // weight each subset by number of features
        this.initializeWeights(shapStats, sdc);
        // add all fully enumerated subsets
        this.addCompleteSubsets(shapStats, pi, sdc);
        // renormalize weights after full subsets have been added
        this.renormalizeWeights(shapStats);
        // sample non-fully enumerated subsets
        this.addNonCompleteSubsets(shapStats, pi, sdc);
        // run the synthetic data generated through the model
        CompletableFuture<RealMatrix> expectations = this.runSyntheticData(sdc);
        // run the wlr model over the synthetic data results
        return output.thenCompose(o -> this.solveSystem(expectations, poVector, sdc).thenApply(wo -> saliencyFromMatrix(wo[0], wo[1], pi, po))).thenCombine(sdc.getFnull(), ShapResults::new);
    }
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) LarsPath(org.kie.kogito.explainability.utils.LarsPath) Prediction(org.kie.kogito.explainability.model.Prediction) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) RealVector(org.apache.commons.math3.linear.RealVector) WeightedLinearRegression(org.kie.kogito.explainability.utils.WeightedLinearRegression) Saliency(org.kie.kogito.explainability.model.Saliency) ArrayList(java.util.ArrayList) MathArithmeticException(org.apache.commons.math3.exception.MathArithmeticException) MatrixUtils(org.apache.commons.math3.linear.MatrixUtils) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) LassoLarsIC(org.kie.kogito.explainability.utils.LassoLarsIC) CombinatoricsUtils(org.apache.commons.math3.util.CombinatoricsUtils) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) LocalExplainer(org.kie.kogito.explainability.local.LocalExplainer) AnyMatrix(org.apache.commons.math3.linear.AnyMatrix) WeightedLinearRegressionResults(org.kie.kogito.explainability.utils.WeightedLinearRegressionResults) FeatureImportance(org.kie.kogito.explainability.model.FeatureImportance) Collectors(java.util.stream.Collectors) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Consumer(java.util.function.Consumer) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) List(java.util.List) MatrixUtilsExtensions(org.kie.kogito.explainability.utils.MatrixUtilsExtensions) RandomChoice(org.kie.kogito.explainability.utils.RandomChoice) RealMatrix(org.apache.commons.math3.linear.RealMatrix) Collections(java.util.Collections) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) CompletableFuture(java.util.concurrent.CompletableFuture) RealMatrix(org.apache.commons.math3.linear.RealMatrix) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) RealVector(org.apache.commons.math3.linear.RealVector)

Example 12 with PredictionProvider

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

the class HighScoreNumericFeatureZonesProvider method getHighScoreFeatureZones.

/**
 * Get a map of feature-name -> high score feature zones. Predictions in data distribution are sorted by (descending)
 * score, then the (aggregated) mean score is calculated and all the data points that are associated with a prediction
 * having a score between the mean and the maximum are selected (feature-wise), with an associated tolerance
 * (the stdDev of the high score feature points).
 *
 * @param dataDistribution a data distribution
 * @param predictionProvider the model used to score the inputs
 * @param features the list of features to associate high score points with
 * @param maxNoOfSamples max no. of inputs used for discovering high score zones
 * @return a map feature name -> high score numeric feature zones
 */
public static Map<String, HighScoreNumericFeatureZones> getHighScoreFeatureZones(DataDistribution dataDistribution, PredictionProvider predictionProvider, List<Feature> features, int maxNoOfSamples) {
    Map<String, HighScoreNumericFeatureZones> numericFeatureZonesMap = new HashMap<>();
    List<Prediction> scoreSortedPredictions = new ArrayList<>();
    try {
        scoreSortedPredictions.addAll(DataUtils.getScoreSortedPredictions(predictionProvider, new PredictionInputsDataDistribution(dataDistribution.sample(maxNoOfSamples))));
    } catch (ExecutionException e) {
        LOGGER.error("Could not sort predictions by score {}", e.getMessage());
    } catch (InterruptedException e) {
        LOGGER.error("Interrupted while waiting for sorting predictions by score {}", e.getMessage());
        Thread.currentThread().interrupt();
    } catch (TimeoutException e) {
        LOGGER.error("Timed out while waiting for sorting predictions by score", e);
    }
    if (!scoreSortedPredictions.isEmpty()) {
        // calculate min, max and mean scores
        double max = scoreSortedPredictions.get(0).getOutput().getOutputs().stream().mapToDouble(Output::getScore).sum();
        double min = scoreSortedPredictions.get(scoreSortedPredictions.size() - 1).getOutput().getOutputs().stream().mapToDouble(Output::getScore).sum();
        if (max != min) {
            double threshold = scoreSortedPredictions.stream().map(p -> p.getOutput().getOutputs().stream().mapToDouble(Output::getScore).sum()).mapToDouble(d -> d).average().orElse((max + min) / 2);
            // filter out predictions whose score is in [min, threshold]
            scoreSortedPredictions = scoreSortedPredictions.stream().filter(p -> p.getOutput().getOutputs().stream().mapToDouble(Output::getScore).sum() > threshold).collect(Collectors.toList());
            for (int j = 0; j < features.size(); j++) {
                Feature feature = features.get(j);
                if (Type.NUMBER.equals(feature.getType())) {
                    int finalJ = j;
                    // get feature values associated with high score inputs
                    List<Double> topValues = scoreSortedPredictions.stream().map(prediction -> prediction.getInput().getFeatures().get(finalJ).getValue().asNumber()).distinct().collect(Collectors.toList());
                    // get high score points and tolerance
                    double[] highScoreFeaturePoints = topValues.stream().flatMapToDouble(DoubleStream::of).toArray();
                    double center = DataUtils.getMean(highScoreFeaturePoints);
                    double tolerance = DataUtils.getStdDev(highScoreFeaturePoints, center) / 2;
                    HighScoreNumericFeatureZones highScoreNumericFeatureZones = new HighScoreNumericFeatureZones(highScoreFeaturePoints, tolerance);
                    numericFeatureZonesMap.put(feature.getName(), highScoreNumericFeatureZones);
                }
            }
        }
    }
    return numericFeatureZonesMap;
}
Also used : DataUtils(org.kie.kogito.explainability.utils.DataUtils) Logger(org.slf4j.Logger) PredictionInputsDataDistribution(org.kie.kogito.explainability.model.PredictionInputsDataDistribution) PerturbationContext(org.kie.kogito.explainability.model.PerturbationContext) Feature(org.kie.kogito.explainability.model.Feature) Prediction(org.kie.kogito.explainability.model.Prediction) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) DataDistribution(org.kie.kogito.explainability.model.DataDistribution) Type(org.kie.kogito.explainability.model.Type) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) ArrayList(java.util.ArrayList) DoubleStream(java.util.stream.DoubleStream) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) Map(java.util.Map) Output(org.kie.kogito.explainability.model.Output) HashMap(java.util.HashMap) Prediction(org.kie.kogito.explainability.model.Prediction) ArrayList(java.util.ArrayList) Feature(org.kie.kogito.explainability.model.Feature) ExecutionException(java.util.concurrent.ExecutionException) PredictionInputsDataDistribution(org.kie.kogito.explainability.model.PredictionInputsDataDistribution) TimeoutException(java.util.concurrent.TimeoutException)

Example 13 with PredictionProvider

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

the class PredictionProviderFactoryImplTest method createPredictionProvider.

@Test
void createPredictionProvider() {
    PredictionProviderFactoryImpl factory = new PredictionProviderFactoryImpl(Vertx.vertx(), ThreadContext.builder().build(), ManagedExecutor.builder().build());
    PredictionProvider predictionProvider = factory.createPredictionProvider(LIME_REQUEST.getServiceUrl(), LIME_REQUEST.getModelIdentifier(), LIME_REQUEST.getOutputs());
    Assertions.assertNotNull(predictionProvider);
    Assertions.assertTrue(predictionProvider instanceof RemotePredictionProvider);
}
Also used : PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) Test(org.junit.jupiter.api.Test)

Example 14 with PredictionProvider

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

the class DummyDmnModelsLimeExplainerTest method testAllTypesDMNExplanation.

@Test
void testAllTypesDMNExplanation() throws ExecutionException, InterruptedException, TimeoutException {
    DMNRuntime dmnRuntime = DMNKogito.createGenericDMNRuntime(new InputStreamReader(getClass().getResourceAsStream("/dmn/allTypes.dmn")));
    assertThat(dmnRuntime.getModels().size()).isEqualTo(1);
    final String namespace = "https://kiegroup.org/dmn/_24B9EC8C-2F02-40EB-B6BB-E8CDE82FBF08";
    final String name = "new-file";
    DecisionModel decisionModel = new DmnDecisionModel(dmnRuntime, namespace, name);
    PredictionProvider model = new DecisionModelWrapper(decisionModel);
    Map<String, Object> context = new HashMap<>();
    context.put("stringInput", "test");
    context.put("listOfStringInput", Collections.singletonList("test"));
    context.put("numberInput", 1);
    context.put("listOfNumbersInput", Collections.singletonList(1));
    context.put("booleanInput", true);
    context.put("listOfBooleansInput", Collections.singletonList(true));
    context.put("timeInput", "h09:00");
    context.put("dateInput", "2020-04-02");
    context.put("dateAndTimeInput", "2020-04-02T09:00:00");
    context.put("daysAndTimeDurationInput", "P1DT1H");
    context.put("yearsAndMonthDurationInput", "P1Y1M");
    Map<String, Object> complexInput = new HashMap<>();
    complexInput.put("aNestedListOfNumbers", Collections.singletonList(1));
    complexInput.put("aNestedString", "test");
    complexInput.put("aNestedComplexInput", Collections.singletonMap("doubleNestedNumber", 1));
    context.put("complexInput", complexInput);
    context.put("listOfComplexInput", Collections.singletonList(complexInput));
    List<Feature> features = new ArrayList<>();
    features.add(FeatureFactory.newCompositeFeature("context", context));
    PredictionInput predictionInput = new PredictionInput(features);
    List<PredictionOutput> predictionOutputs = model.predictAsync(List.of(predictionInput)).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
    Prediction prediction = new SimplePrediction(predictionInput, predictionOutputs.get(0));
    Random random = new Random();
    PerturbationContext perturbationContext = new PerturbationContext(0L, random, 3);
    LimeConfig limeConfig = new LimeConfig().withSamples(10).withPerturbationContext(perturbationContext);
    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()) {
        assertThat(saliency).isNotNull();
    }
    assertThatCode(() -> ValidationUtils.validateLocalSaliencyStability(model, prediction, limeExplainer, 1, 0.5, 0.2)).doesNotThrowAnyException();
    String decision = "myDecision";
    List<PredictionInput> inputs = new ArrayList<>();
    for (int n = 0; n < 10; n++) {
        inputs.add(new PredictionInput(DataUtils.perturbFeatures(features, perturbationContext)));
    }
    DataDistribution distribution = new PredictionInputsDataDistribution(inputs);
    int k = 2;
    int chunkSize = 5;
    double precision = ExplainabilityMetrics.getLocalSaliencyPrecision(decision, model, limeExplainer, distribution, k, chunkSize);
    assertThat(precision).isBetween(0d, 1d);
    double recall = ExplainabilityMetrics.getLocalSaliencyRecall(decision, model, limeExplainer, distribution, k, chunkSize);
    assertThat(recall).isBetween(0d, 1d);
    double f1 = ExplainabilityMetrics.getLocalSaliencyF1(decision, model, limeExplainer, distribution, k, chunkSize);
    assertThat(f1).isBetween(0d, 1d);
}
Also used : SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) PerturbationContext(org.kie.kogito.explainability.model.PerturbationContext) HashMap(java.util.HashMap) LimeExplainer(org.kie.kogito.explainability.local.lime.LimeExplainer) ArrayList(java.util.ArrayList) DecisionModel(org.kie.kogito.decision.DecisionModel) DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) Saliency(org.kie.kogito.explainability.model.Saliency) Feature(org.kie.kogito.explainability.model.Feature) Random(java.util.Random) PredictionInputsDataDistribution(org.kie.kogito.explainability.model.PredictionInputsDataDistribution) InputStreamReader(java.io.InputStreamReader) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) Prediction(org.kie.kogito.explainability.model.Prediction) SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) DMNRuntime(org.kie.dmn.api.core.DMNRuntime) LimeConfig(org.kie.kogito.explainability.local.lime.LimeConfig) PredictionInputsDataDistribution(org.kie.kogito.explainability.model.PredictionInputsDataDistribution) DataDistribution(org.kie.kogito.explainability.model.DataDistribution) PredictionOutput(org.kie.kogito.explainability.model.PredictionOutput) DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) Test(org.junit.jupiter.api.Test)

Example 15 with PredictionProvider

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

the class DummyDmnModelsLimeExplainerTest method testFunctional1DMNExplanation.

@Test
void testFunctional1DMNExplanation() throws ExecutionException, InterruptedException, TimeoutException {
    DMNRuntime dmnRuntime = DMNKogito.createGenericDMNRuntime(new InputStreamReader(getClass().getResourceAsStream("/dmn/functionalTest1.dmn")));
    assertThat(dmnRuntime.getModels().size()).isEqualTo(1);
    final String namespace = "https://kiegroup.org/dmn/_049CD980-1310-4B02-9E90-EFC57059F44A";
    final String name = "functionalTest1";
    DecisionModel decisionModel = new DmnDecisionModel(dmnRuntime, namespace, name);
    PredictionProvider model = new DecisionModelWrapper(decisionModel);
    Map<String, Object> context = new HashMap<>();
    context.put("booleanInput", true);
    context.put("notUsedInput", 1);
    List<Feature> features = new ArrayList<>();
    features.add(FeatureFactory.newCompositeFeature("context", context));
    PredictionInput predictionInput = new PredictionInput(features);
    List<PredictionOutput> predictionOutputs = model.predictAsync(List.of(predictionInput)).get(Config.INSTANCE.getAsyncTimeout(), Config.INSTANCE.getAsyncTimeUnit());
    Prediction prediction = new SimplePrediction(predictionInput, predictionOutputs.get(0));
    Random random = new Random();
    PerturbationContext perturbationContext = new PerturbationContext(0L, random, 1);
    LimeConfig limeConfig = new LimeConfig().withSamples(10).withPerturbationContext(perturbationContext);
    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()) {
        assertThat(saliency).isNotNull();
        List<FeatureImportance> topFeatures = saliency.getPositiveFeatures(2);
        assertThat(topFeatures.isEmpty()).isFalse();
        assertThat(topFeatures.get(0).getFeature().getName()).isEqualTo("booleanInput");
    }
    assertThatCode(() -> ValidationUtils.validateLocalSaliencyStability(model, prediction, limeExplainer, 1, 0.5, 0.5)).doesNotThrowAnyException();
    String decision = "decision";
    List<PredictionInput> inputs = new ArrayList<>();
    for (int n = 0; n < 10; n++) {
        inputs.add(new PredictionInput(DataUtils.perturbFeatures(features, perturbationContext)));
    }
    DataDistribution distribution = new PredictionInputsDataDistribution(inputs);
    int k = 2;
    int chunkSize = 5;
    double precision = ExplainabilityMetrics.getLocalSaliencyPrecision(decision, model, limeExplainer, distribution, k, chunkSize);
    assertThat(precision).isBetween(0d, 1d);
    double recall = ExplainabilityMetrics.getLocalSaliencyRecall(decision, model, limeExplainer, distribution, k, chunkSize);
    assertThat(recall).isBetween(0d, 1d);
    double f1 = ExplainabilityMetrics.getLocalSaliencyF1(decision, model, limeExplainer, distribution, k, chunkSize);
    assertThat(f1).isBetween(0d, 1d);
}
Also used : SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) PerturbationContext(org.kie.kogito.explainability.model.PerturbationContext) HashMap(java.util.HashMap) LimeExplainer(org.kie.kogito.explainability.local.lime.LimeExplainer) ArrayList(java.util.ArrayList) DecisionModel(org.kie.kogito.decision.DecisionModel) DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) Saliency(org.kie.kogito.explainability.model.Saliency) Feature(org.kie.kogito.explainability.model.Feature) Random(java.util.Random) PredictionInputsDataDistribution(org.kie.kogito.explainability.model.PredictionInputsDataDistribution) InputStreamReader(java.io.InputStreamReader) PredictionInput(org.kie.kogito.explainability.model.PredictionInput) Prediction(org.kie.kogito.explainability.model.Prediction) SimplePrediction(org.kie.kogito.explainability.model.SimplePrediction) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) DMNRuntime(org.kie.dmn.api.core.DMNRuntime) LimeConfig(org.kie.kogito.explainability.local.lime.LimeConfig) 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) DmnDecisionModel(org.kie.kogito.dmn.DmnDecisionModel) Test(org.junit.jupiter.api.Test)

Aggregations

PredictionProvider (org.kie.kogito.explainability.model.PredictionProvider)158 Prediction (org.kie.kogito.explainability.model.Prediction)134 PredictionInput (org.kie.kogito.explainability.model.PredictionInput)134 PredictionOutput (org.kie.kogito.explainability.model.PredictionOutput)126 Test (org.junit.jupiter.api.Test)109 SimplePrediction (org.kie.kogito.explainability.model.SimplePrediction)99 Random (java.util.Random)91 Feature (org.kie.kogito.explainability.model.Feature)76 ArrayList (java.util.ArrayList)73 PerturbationContext (org.kie.kogito.explainability.model.PerturbationContext)69 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)64 LimeConfig (org.kie.kogito.explainability.local.lime.LimeConfig)59 LimeExplainer (org.kie.kogito.explainability.local.lime.LimeExplainer)54 Output (org.kie.kogito.explainability.model.Output)45 Saliency (org.kie.kogito.explainability.model.Saliency)45 LinkedList (java.util.LinkedList)41 Value (org.kie.kogito.explainability.model.Value)41 List (java.util.List)37 LimeConfigOptimizer (org.kie.kogito.explainability.local.lime.optim.LimeConfigOptimizer)33 ValueSource (org.junit.jupiter.params.provider.ValueSource)32