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);
}
}
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;
}
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);
}
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);
}
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);
}
Aggregations