"markdown":"\n\n# `ConformalGenerator`\n\nIn this section, we will look at a simple example involving synthetic data, a black-box model and a generic Conformal Counterfactual Generator.\n\n## Black-box Model\n\nWe consider a simple binary classification problem. Let $(X_i, Y_i), \\ i=1,...,n$ denote our feature-label pairs and let $\\mu: \\mathcal{X} \\mapsto \\mathcal{Y}$ denote the mapping from features to labels. For illustration purposes, we will use linearly separable data. \n\n\n\nWhile we could use a linear classifier in this case, let's pretend we need a black-box model for this task and rely on a small Multi-Layer Perceptron (MLP):\n\n\n\nWe can fit this model to data to produce plug-in predictions. \n\n## Conformal Prediction\n\nHere we will instead use a specific case of CP called *split conformal prediction* which can then be summarized as follows:^[In other places split conformal prediction is sometimes referred to as *inductive* conformal prediction.]\n\n1. Partition the training into a proper training set and a separate calibration set: $\\mathcal{D}_n=\\mathcal{D}^{\\text{train}} \\cup \\mathcal{D}^{\\text{cali}}$.\n2. Train the machine learning model on the proper training set: $\\hat\\mu_{i \\in \\mathcal{D}^{\\text{train}}}(X_i,Y_i)$.\n\nThe model $\\hat\\mu_{i \\in \\mathcal{D}^{\\text{train}}}$ can now produce plug-in predictions. \n\n::: callout-note\n\n## Starting Point\n\nNote that this represents the starting point in applications of Algorithmic Recourse: we have some pre-trained classifier $M$ for which we would like to generate plausible Counterfactual Explanations. Next, we turn to the calibration step. \n:::\n\n3. Compute nonconformity scores, $\\mathcal{S}$, using the calibration data $\\mathcal{D}^{\\text{cali}}$ and the fitted model $\\hat\\mu_{i \\in \\mathcal{D}^{\\text{train}}}$. \n4. For a user-specified desired coverage ratio $(1-\\alpha)$ compute the corresponding quantile, $\\hat{q}$, of the empirical distribution of nonconformity scores, $\\mathcal{S}$.\n5. For the given quantile and test sample $X_{\\text{test}}$, form the corresponding conformal prediction set: \n\n$$\nC(X_{\\text{test}})=\\{y:s(X_{\\text{test}},y) \\le \\hat{q}\\}\n$$ {#eq-set}\n\nThis is the default procedure used for classification and regression in [`ConformalPrediction.jl`](https://github.com/pat-alt/ConformalPrediction.jl). \n\nUsing the package, we can apply Split Conformal Prediction as follows:\n\n\n\nTo be clear, all of the calibration steps (3 to 5) are post hoc, and yet none of them involved any changes to the model parameters. These are two important characteristics of Split Conformal Prediction (SCP) that make it particularly useful in the context of Algorithmic Recourse. Firstly, the fact that SCP involves posthoc calibration steps that happen after training, ensures that we need not place any restrictions on the black-box model itself. This stands in contrast to the approach proposed by @schut2021generating in which they essentially restrict the class of models to Bayesian models. Secondly, the fact that the model itself is kept entirely intact ensures that the generated counterfactuals maintain fidelity to the model. Finally, note that we also have not resorted to a surrogate model to learn more about $X \\sim \\mathcal{X}$. Instead, we have used the fitted model itself and a calibration data set to learn about the model's predictive uncertainty. \n\n## Differentiable CP\n\nIn order to use CP in the context of gradient-based counterfactual search, we need it to be differentiable. @stutz2022learning introduce a framework for training differentiable conformal predictors. They introduce a configurable loss function as well as smooth set size penalty.\n\n### Smooth Set Size Penalty\n\nStarting with the former, @stutz2022learning propose the following:\n\n$$\n\\Omega(C_{\\theta}(x;\\tau)) = = \\max (0, \\sum_k C_{\\theta,k}(x;\\tau) - \\kappa)\n$$ {#eq-size-loss}\n\nHere, $C_{\\theta,k}(x;\\tau)$ is loosely defined as the probability that class $k$ is assigned to the conformal prediction set $C$. In the context of Conformal Training, this penalty reduces the **inefficiency** of the conformal predictor. \n\nIn our context, we are not interested in improving the model itself, but rather in producing **plausible** counterfactuals. Provided that our counterfactual $x^\\prime$ is already inside the target domain ($\\mathbb{I}_{y^\\prime = t}=1$), penalizing $\\Omega(C_{\\theta}(x;\\tau))$ corresponds to guiding counterfactuals into regions of the target domain that are characterized by low ambiguity: for $\\kappa=1$ the conformal prediction set includes only the target label $t$ as $\\Omega(C_{\\theta}(x;\\tau))$. Arguably, less ambiguous counterfactuals are more **plausible**. Since the search is guided purely by properties of the model itself and (exchangeable) calibration data, counterfactuals also maintain **high fidelity**.\n\nThe left panel of @fig-losses shows the smooth size penalty in the two-dimensional feature space of our synthetic data.\n\n### Configurable Classification Loss\n\nThe right panel of @fig-losses shows the configurable classification loss in the two-dimensional feature space of our synthetic data.\n\n\n\n## Fidelity and Plausibility\n\nThe main evaluation criteria we are interested in are *fidelity* and *plausibility*. Interestingly, we could also consider using these measures as penalties in the counterfactual search.\n\n### Fidelity\n\nWe propose to define fidelity as follows:\n\n::: {#def-fidelity}\n\n## High-Fidelity Counterfactuals\n\nLet $\\mathcal{X}_{\\theta}|y = p_{\\theta}(X|y)$ denote the class-conditional distribution of $X$ defined by $\\theta$. Then for $x^{\\prime}$ to be considered a high-fidelity counterfactual, we need: $\\mathcal{X}_{\\theta}|t \\approxeq \\mathcal{X}^{\\prime}$ where $t$ denotes the target outcome.\n\n:::\n\nWe can generate samples from $p_{\\theta}(X|y)$ following @grathwohl2020your. In @fig-energy, I have applied the methodology to our synthetic data.\n\n\n\nAs an evaluation metric and penalty, we could use the average distance of the counterfactual $x^{\\prime}$ from these generated samples, for example.\n\n### Plausibility\n\nWe propose to define plausibility as follows:\n\n::: {#def-plausible}\n\n## Plausible Counterfactuals\n\nFormally, let $\\mathcal{X}|t$ denote the conditional distribution of samples in the target class. As before, we have $x^{\\prime}\\sim\\mathcal{X}^{\\prime}$, then for $x^{\\prime}$ to be considered a plausible counterfactual, we need: $\\mathcal{X}|t \\approxeq \\mathcal{X}^{\\prime}$.\n\n:::\n\nAs an evaluation metric and penalty, we could use the average distance of the counterfactual $x^{\\prime}$ from (potentially bootstrapped) training samples in the target class, for example.\n\n## Counterfactual Explanations\n\nNext, let's generate counterfactual explanations for our synthetic data. We first wrap our model in a container that makes it compatible with `CounterfactualExplanations.jl`. Then we draw a random sample, determine its predicted label $\\hat{y}$ and choose the opposite label as our target. \n\n\n\nThe generic Conformal Counterfactual Generator penalises the only the set size only:\n\n$$\nx^\\prime = \\arg \\min_{x^\\prime} \\ell(M(x^\\prime),t) + \\lambda \\mathbb{I}_{y^\\prime = t} \\Omega(C_{\\theta}(x;\\tau)) \n$$ {#eq-solution}\n\n\n\n## Multi-Class\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Benchmark\n\n",