{'fraction_non_alphanumeric': 0.0346380097932893, 'fraction_numerical': 0.008807387689375267, 'mean_word_length': 4.622690317812269, 'pattern_counts': {'":': 0, '<': 0, '<?xml version=': 0, '>': 1, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
Synthesizing explainable counterfactual policies for algorithmic recourse with program synthesis

Being able to provide counterfactual interventions - sequences of actions we would have had to take for a desirable outcome to happen - is essential to explain how to change an unfavourable decision by a black-box machine learning model (e.g., being denied a loan request). Existing solutions have mainly focused on generating feasible interventions without providing explanations on their rationale. Moreover, they need to solve a separate optimization problem for each user. In this paper, we take a different approach and learn a program that outputs a sequence of explainable counterfactual actions given a user description and a causal graph. We leverage program synthesis techniques, reinforcement learning coupled with Monte Carlo Tree Search for efficient exploration, and rule learning to extract explanations for each recommended action. An experimental evaluation on synthetic and real-world datasets shows how our approach generates effective interventions by making orders of magnitude fewer queries to the black-box classifier with respect to existing solutions, with the additional benefit of complementing them with interpretable explanations.


Introduction
Counterfactual explanations are very powerful tools to explain the decision process of machine learning models [1,2]. They give us the intuition of what could have happened if the state of the world was different (e.g., if you had taken the umbrella, you would not have gotten soaked). Researchers have developed many methods that can generate counterfactual explanations given a trained model [1,[3][4][5][6][7]. However, these methods do not provide any actionable information about which steps are required to obtain the given counterfactual. Thus, most of these methods do not enable algorithmic recourse. Algorithmic recourse describes the ability to provide "explanations and recommendations to individuals who are unfavourably treated by automated decision-making systems" [8]. For instance, algorithmic recourse can answer questions such as: what actions does a user have to perform to be granted a loan? Recently, providing feasible algorithmic recourse has also become a legal necessity [9]. Some research works address this problem by developing ways to generate counterfactual interventions [8], i.e., sequences of actions that, if followed, can overturn a decision made by a machine learning model, thus guaranteeing recourse. While being quite successful, these methods have several limitations. First, they are purely optimization methods that must be rerun from scratch for each new user. As a consequence, this requirement prevents their use for real-time interventions' generation. Second, they are expensive in terms of queries to the black-box classifier and computing time. Last but not least, they fail to explain their recommendations (e.g., why does the model suggest getting a better degree rather than changing job?). On the contrary, explainability has been pointed out as a major requirement for methods generating counterfactual interventions [10].
In this paper, we cast the problem of providing explainable counterfactual interventions as a program synthesis task [11][12][13][14]: we want to generate a "program" that provides all the steps needed to overturn a bad decision made by a machine learning model. We propose a novel reinforcement learning (RL) method coupled with a discrete search procedure, Monte Carlo Tree Search [15], to generate counterfactual interventions in an efficient data-driven manner. As done by [16], we assume a causal model encoding relationships between user features and consequences of potential interventions. We also provide a solution to distil an explainable deterministic program from the learned policy in the form of an automaton. Fig. 1 provides an overview of the architecture and the learning strategy, and an example of an explainable intervention generated by the extracted automaton. Our approach addresses the three main limitations that characterize existing solutions: • It learns a general policy that can be used to generate interventions for multiple users, rather than running separate user-specific optimizations. • By coupling reinforcement learning with Monte Carlo Tree Search, it can efficiently explore the search space, requiring massively fewer queries to the black-box classifier than the best evolutionary algorithm (EA) model Given the state s t representing the features of the user, the agent generates candidate intervention policies π f and πx for functions and arguments, respectively (an action is a function-argument pair). MCTS uses these policies as a prior, and it extracts the best next action (f, x) * t+1 . Once found, the reward received upon making the action is used to improve the MCTS estimates, and correct traces (i.e., those leading to the desired outcome change) are saved in a replay buffer. 2. Training step. The buffer is used to sample a subset of correct traces to be used to train the RL agent to mimic the behaviour of MCTS. 3. Explainable intervention. Example of an explainable intervention generated by the automaton extracted from the learned agent. Actions are in black, while explanations for each action are in red.
available, especially in settings with many features and (relatively) long interventions.
• By extracting a program from the learned policy, it can complement the intervention with explanations motivating each action from contextual information. Furthermore, the program can be executed in real-time without accessing the black-box classifier.
Our experimental results on synthetic and real-world datasets confirm the advantages of the proposed solution over existing alternatives in terms of generality, scalability and interpretability.

Related Work
Counterfactual explanations are versatile techniques to provide post-hoc interpretability of black-box machine learning models [1,[3][4][5][6][7]. They are modelagnostic, which means that they can be applied to trained models without performance loss. Compared to other global methods [17,18], they provide instead local explanations. Namely, they underline only the relevant factors impacting a decision for a given initial target instance. They are also humanfriendly and present many characteristics of what it is considered to be a good explanation [19]. Therefore, they are suitable candidates to provide explanations to end-users since they are both highly-informative and localized. Recent research has shown how to generate counterfactual interventions for algorithmic recourse via various techniques [2], such as probabilistic models [20], integer programming [21], reinforcement learning [22], program synthesis [23] and genetic algorithms [16]. Methods with (approximated) convergence guarantees on the optimal counterfactual policies have also been proposed [24]. However, most of these methods ignore the causal relationships between user features [21][22][23][24]. Without assuming an underlying causal graph, the proposed interventions become permutation invariant. For example, given an intervention consisting of three actions [A, B, C], any intervention that is a permutation of the actions will have the same total cost. More importantly, it has been recently shown that optimal algorithmic recourse is impossible to achieve without a causal model of the interactions between the features [20]. The work by Karimi et al. [20] does provide algorithmic recourse following a causal model but optimizes for interventions that can operate on multiple user's attributes simultaneously, which is unrealistic. CSCF [16] is the only model-agnostic method capable of producing consequence-aware sequential interventions by exploiting causal relationships between features represented by a causal graph. However, CSCF is still purely an (evolutionary-based) optimization method, so it has to be run from scratch for each new user. Furthermore, the approach is opaque with respect to the reasons behind a suggested intervention. In this work, we show how our approach improves over CSCF in terms of generality, efficiency and interpretability.

Problem setting
The state of a user is represented as a vector of attributes s ∈ S (e.g., age, sex, monthly income, job). A black-box classifier h : S → {T rue, F alse} predicts an outcome given a user state, with T rue being favourable to the user and F alse being unfavourable. The setting can be easily extended to multiclass classification by either grouping outcomes in favourable and unfavourable ones or learning separate programs converting from one class to the other. A counterfactual intervention I is a sequence of actions. Each action is represented as a tuple, (f, x) ∈ A, composed by a function, f , and its argument, x ∈ X f (e.g., (change income, 500)). When an action is performed for a certain user, it modifies their state by altering one of their attributes according to its argument. A library F contains all the possible functions which can be called. This library and the corresponding DSL (Domain Specific Language) are typically defined as a-priori by experts to prevent changes to protected attributes (e.g., age, sex, etc.). Examples of such DSLs can be found in the Appendix B. Moreover, each function possesses pre-conditions in the form of Boolean predicates over its arguments which describe the conditions that a user state must meet in order for a function to be called. The end of an intervention I is always specified by the STOP action. We also define a cost function, C : A × S → R which mimics the effort made by a given user to perform an action given the current state. The cost is computed by looking at a causal graph G, where the nodes of the graph are the user's features. This assumption encodes the concept of consequences and it ensures a notion of order for the intervention's  actions. For example, it might be easier to get first a degree and then a better salary, rather than doing the opposite. Fig. 2 shows an example of a causal graph G and of the corresponding costs. Our goal is to train an agent that, given a user with an unfavourable outcome, generates counterfactual interventions that overturn it. Given a black-box classifier h, a user s 0 for whom the prediction by h is unfavourable (i.e., h(s 0 ) = F alse), a causal graph G and a set of possible actions A (implicitly represented by the functions in F and their arguments in X ), we want to generate a sequence I * , that, if applied to s 0 , produces a new state, s * = I(s 0 ), such that h(s * ) = T rue. This sequence must be actionable, which means that the user has to be able to perform those actions, and minimize the user's cost. More formally:

Model Architecture
Overall structure. Fig. 1 shows the complete model architecture. It is composed of a binary encoder and an RL agent coupled with the Monte Carlo Tree Search procedure. The binary encoder converts the user's features into a binary representation. The conversion is done by one-hot-encoding the categorical features and discretizing the numerical features into ranges. In the following sections, we will use s t to directly indicate the user's state binary version. Given a state s t , the RL agent generates candidate policies, π f and π x , for the function and argument generation respectively. MCTS uses these policies as priors for its exploration of the action space and extracts the best next action (f, x) * t+1 . The action is then applied to the environment. The procedure ends when the STOP action is chosen (i.e., the intervention was successful) or when the maximum intervention length is reached, in which case the result is marked as a failure. During training, the reward is used to improve the MCTS estimates of the policies. Moreover, correct traces (i.e., traces of interventions leading to the desired outcome change) are stored in a replay buffer, and a sample of traces from the buffer is used to refine the RL agent.

RL agent structure.
The agent structure is inspired by previous program synthesis works [11,12]. It is composed by 5 components: a state encoder, g enc , an LSTM controller, g lstm , a function network g f , an argument network g x and a value network g V . We use simple feedforward networks to implement g f , g x and g V .
g enc encodes the user's state in a latent representation which is fed to the controller, g lstm . The controller, g lstm learns an implicit representation of the program to generate the interventions. The function and argument networks are then used to extract the corresponding policies, π f and π x , by taking as input the hidden state h t from g lstm . g V represents the value function V and it outputs the expected reward from the state s t . Here, we omit the state s t when defining the policies and the value function output, since s t is already embedded into the h t representation. In our settings, we try to learn a single program, which we call INTERVENE.

Policy.
A policy is a distribution over the available actions (i.e., functions and their arguments) such that N i=0 π(i) = 1. Our agent produces two policies: π f on the function space, and π x on the argument space. The next action, (f, x) t+1 , is chosen by taking the argmax over the policies: Each program starts by calling the program INTERVENE, and it ends when the action STOP is called.

Reward.
Once we have applied the intervention I, given the black-box classifier h, the reward, r, is computed as: where λ is a regularization coefficient and T is the length of the intervention. The λ T penalizes longer interventions in favour of shorter ones.

Monte Carlo Tree Search
Monte Carlo Tree Search (MCTS) is a discrete heuristic search procedure that can successfully solve combinatorial optimization problems with large action spaces [25,26]. MCTS explores the most promising nodes by expanding the search space based on a random sampling of the possible actions. In our setting, each tree node represents the user's state at a time t, and each arc represents a possible action determining a transition to a new state. MCTS searches for the correct sequence of interventions that minimize the user effort and changes the prediction of the black-box model. We use the agent policies, π f and π x , as a prior to explore the program space. Then, the newly found sequence of interventions is used to train the RL agent. To select the next node, we maximize the UCT criterion [27]: Here Q(s, (f, x)) returns the expected reward by taking action (f, x).
U (s, (f, x)) is a term which trades-off exploration and exploitation, and it is based on how many times we visited node s in the tree. L(s, (f, x)) is a scoring term which is defined as follows: where l cost = C(a, s) ∈ R represents the effort needed to perform the a = (f, x) ∈ A action, and l count ∈ R penalizes interventions that call multiple times the same function f . MCTS uses the simulation results to return an improved version of the agent policies π mcts f and π mcts x . From the found intervention, we build an intervention trace, which is a sequence of tuples that stores, for each time step t: the input state, the output state, the reward, the hidden state of the controller and the improved policies. The traces are stored in the replay buffer, to be used to train the RL agent.

Training the agent
The agent has to learn to replicate the interventions provided by MCTS at each step t. Given the replay buffer, we sample a batch of intervention traces and we minimize the cross-entropy L between the MCTS policies and the agent policies for each time step t: where θ represents the agent's parameters and V is the value function evaluation computed by the agent.

Generate Interventions through RL
When training the agent, we learn a general policy that can be used to provide interventions for many different users. The inference procedure is similar to the one used for training. Given an initial state s, MCTS explores the tree search space using as "prior" the learnt policies π x and π f coming from the agent. The policies π x and π f give MCTS a hint of which node to select at each step. Once MCTS finds the minimal cost trace that achieves recourse, we return it to the user. In principle, we can also use only π x and π f to obtain a viable intervention (e.g., by deterministically taking the action with highest probability each time). However, keeping the search component (MCTS) with a small exploration budget outperforms the RL agent alone. See Table 2 in Section 4 for the comparison between the agent-only model and the agent augmented with MCTS. Learning a general policy to provide interventions is a powerful feature. However, the policy is encoded in the latent states of the agent, thus making it impossible for us to understand it. We want to be able to extract from the trained model an explainable version of this policy, which can then be used to explain why the model suggested a given intervention. Namely, besides providing to the users a sequence of actions, we want to show also the reason behind each suggested action. The intuition to achieve this is the following: given a set of successful interventions generated by the agent, we can distill a synthetic automaton, or program, which condense the policy in a graph-like structure which we can traverse. 1. For all f ∈ F, we add a new node. 2. Given the samples traces, we add the transitions, and we store (s i , (f i , x i )) in each node. 3. We train a decision tree for each node to predict the next action (consistently with the sampled traces). 4. We execute the program on the new instance at prediction time, using the decision trees to decide the next action at each node. We extract a Boolean rule explaining it from the corresponding decision tree for each action. On the right, an example of generated intervention. The actions (f, x) are black, while the explanations are red.

Explainable Intervention Program
We now show how we can build a deterministic program given the agent. Fig. 4 shows the complete procedure and an example of the produced trace. First, we sample M intervention traces from the trained agent and extract a sequence of {(s i , (f, x) i )} T i=0 for each trace. Then, we construct an automaton graph, P, in the following way: 1. Given the function library F, we create a node for each function f available.
We also add a starting node called INTERVENE and a "sink" node called STOP; 2. We connect each node by unrolling the sampled traces. Starting from INTERVENE, we treat each action (f, x) t as a transition. We label the transition with (f, x) and we connect the current node to the one representing the function f ; 3. Lastly, for each node f , we store a collection of outgoing state-action pairs (s i , (f, x) i ). Namely, we store all the states s and the corresponding outward transitions which were decided by the model while at the node f ; 4. For each node, f ∈ P, we train a decision tree on the tuples (s i , (f, x) i ) stored in the node to predict the transition (f, x) i given a user's state s i .
The decision trees are trained only once by using the collection of traces sampled from the trained agent. The agent is frozen at this step, and it is not trained further. At this point, we perform Step 1 to 3 of Fig. 4. The pseudocode of the entire procedure is available in the Appendix A.

Generate Explainable Interventions
The intervention generation is done by traversing the graph P, starting from the node INTERVENE, until we reach the STOP node or we reach the maximum intervention length. In the last case, the program is marked as a failure. Given the node f ∈ P and given the state s t , we use the decision tree of that node to predict the next transition (f , x ). Moreover, we can extract from the decision tree interpretable rules which tell us why the next action was chosen. A rule is a boolean proposition on the user's features such as (income > 5000 ∧ education = bachelor). Then, we follow (f , x ), which is an arc going from f to the next node f , and we apply the action to s t to get s t+1 . Again, the program is "fixed" at inference time, and it is not trained further. See Step 4 of Fig. 4 for an example of the inference procedure and of the produced explainable trace.

Experiments
Our experimental evaluation aims at answering the following research questions: (1) Does our method provide better performances than the competitors in terms of the accuracy of the algorithmic recourse? (2) Does our approach allow us to complement interventions with action-by-action explanations in most cases? (3) Does our method minimize the interaction with the black-box classifier to provide interventions?
The code and the dataset of the experiments are available on Github to ensure reproducibility 1 . The software exploit parallelization through mpi4python [28] to improve inference and training time. We compared the performance of our algorithm with CSCF [16], to the best of our knowledge the only existing model-agnostic approach that can generate consequence-aware interventions following a causal graph. However, note that earlier solutions still perform user-specific optimization, so that our results in terms of generality, interpretability and cost (number of queries to the black-box classifier and computational cost) carry over to these alternatives. For the sake of a fair comparison, we built our own parallelized version of the CSCF model based on the original code. We developed the project to make it easily extendable and reusable by the research community. The experiments were performed using a Linux distribution on an Intel(R) Xeon(R) CPU E5-2660 2.20GHz with 8 cores and 100 GB of RAM (only 4 cores were used). Table 1 shows a brief description of the datasets. They all represent binary (favourable/unfavourable) classification problems. The two real world datasets, German Credit (german) and Adult Score (adult) [29], are taken from the relevant literature. Given that in these datasets a couple of actions is usually german  1002  301  701  10  44  7  adult  48845  11691  37154  15  125  6  syn  10004  5002  5002  10  40  6  syn long  10004  5002  5002  14  64  10   Table 1: Description of the datasets. |D| is the size of the dataset. |s| the number of features for an instance. |B(s)| shows how many binary features the agent sees after the conversion with the binary converter. |F| is the size of the agent program library. h(s) indicates the number of favourable (1) and unfavourable (0) samples. sufficient to overturn the outcome of the black-box classifier, we also developed two synthetic datasets, syn and syn long, where longer interventions are required, so as to evaluate the models in more challenging scenarios. The datasets are made by both categorical and numerical features (e.g., monthly income, job type, etc.). Each dataset was randomly split into 80% train and 20% test. For each dataset, we manually define a causal graph, G, by looking at the features available. For the synthetic datasets, we sampled instances directly from the causal graph. The black-box classifier for german and adult was obtained by training a 5-layers MLP with ReLu activations. The trained classifiers are reasonably accurate (∼ 0.9 test-set accuracy for german, ∼ 0.8 for adult). The synthetic datasets (syn and syn long) do not require any training since we directly use our manually defined decision function.

Models
We evaluate four different models: the agent coupled with MCTS (M mcts ), the explainable deterministic program distilled from the agent (M prog ), and two versions of CSCF, one (M cscf ) with a large budget of generation, n, and population size, p, (n = 50, p = 200) and one (M small cscf ) with a smaller budget (n = 25, p = 100).  Table 2: Ablation study. In order to evaluate the contribution of MCTS in finding successful interventions, we also developed an additional model which only uses the RL agent, M agent . The agent just predicts the next action using its own policy without leveraging MCTS to refine the choice. Results indicate that RL alone is incapable of finding successful interventions.

Evaluation
The left plot in Fig. 5 shows the average accuracy of the different models, namely the fraction of instances for which a model manages to generate a successful intervention. We can see how M mcts outperforms or is on-par with the M cscf and M small cscf models on both the real-word and synthetic datasets. The performance difference is more evident in the synthetic datasets, because the evolutionary algorithm struggles in generating interventions that require more than a couple of actions. The accuracy loss incurred in distilling M mcts into a program (M prog ) is rather limited. This implies that we are able to provide interventions with explanations for 94% (german), 66% (adult), 99% (syn) and 87% (syn long) of the test users 2 . Moreover, M prog generates similar interventions to M mcts . The sequence similarity between their respective interventions for the same user are 0.89 (german), 0.72 (adult), 0.80 (syn) and 0.71 (syn long), where 1.0 indicates identical interventions.
The main reason for the accuracy gains of our model is the ability to generate long interventions, something evolutionary-based algorithms struggle with. This effect can be clearly seen from the middle plot of Fig. 5. Both M cscf and M small cscf rarely generate interventions with more than two actions, while our approach can easily generate interventions with up to five actions. A drawback of this ability is that intervention costs are, on average, higher (right plot of Fig. 5). On the one hand, this is due to the fact that our model is capable of finding interventions for more complex instances, while M cscf and M small cscf fail. Indeed, if we compute lengths and costs on the subset of instances for which all models find a successful intervention, the difference between the approaches is less pronounced. See Fig. 6 for the evaluation. On the other hand, there is a clear trade-off between solving a new optimization problem from scratch for each new user, and learning a general model that, once trained, can generate interventions for new users in real-time and without accessing the black-box classifier.   Our approach requires far fewer queries than M cscf (note that the plot is in logscale), and even substantially less than M small cscf (that is anyhow not competitive in terms of accuracy). Furthermore, most queries are made for training the agent (M mcts (train)), which is only done once for all users. Once the model is trained, generating interventions for a single user requires around two orders of magnitude fewer queries than the competitors. Note that MCTS is crucial to allow the RL agent to learn a successful policy with a low budget of queries. Indeed, training an RL agent without the support of MCTS fails to converge in the given budget, leading to a completely useless policy. By efficiently searching the space of interventions, MCTS manages to quickly correct inaccurate initial policies, allowing the agent to learn high quality policies with a limited query budget. See Table 2 for the evaluation.
When turning to the program, building the automaton (M prog (train)) requires a negligible number of queries to extract the intervention traces used as supervision.
Using the automaton to generate interventions does not require to query the black-box classifier. This characteristic can substantially increase the usability of the system, as M prog can be employed directly by the user even if they have no access to the classifier. Computationally speaking, the advantage of a twostep phase is also quite dramatic. M cscf takes an average of ∼ 693s for each user to provide a solution (the same order of magnitude of training a model for all users with M mcts ), while M mcts inference time is under 1s, allowing real-time interaction with the user.
Additionally, Fig. 8 shows how it is possible to improve the performances of M prog by just sampling more traces from the trained agent (M mcts ). We can see how the accuracy increases in the adult, syn and syn long datasets. We also notice that using a larger budget to train M prog produces longer explainable rules by keeping the length and cost of the generated interventions almost constant. The total number of queries to the black-box classifier will also slightly increase.
Overall, our experimental evaluation allows us to affirmatively answer the research questions stated above.

Conclusion
This work improves the state-of-the-art on algorithmic recourse by providing a method that can generate effective and interpretable counterfactual interventions in real-time. Our experimental evaluation confirms the advantages of our solution with respect to alternative consequence-aware approaches in terms of accuracy, interpretability and number of queries to the black-box classifier. Our work unlocks many new research directions, which could be explored to solve some of its limitations. First, following previous work on causal-aware intervention generation, we use manually-crafted causal graphs and action costs. Learning them from the available data directly, minimizing the human intervention, would allow applying the approach in settings where this information is not available or unreliable. Second, we showed how our method learns a general program by optimizing over multiple users. It would be interesting to investigate additional RL methods to optimize the interventions globally and locally to provide more personalized sequences to the users. Such methods could be coupled with interactive approaches eliciting preferences and constraints directly from the user, thus maximizing the chance to generate the most appropriate intervention for a given user.

Ethical Impact
The research field of algorithmic recourse aims at improving fairness, by providing unfairly treated users with tools to overturn unfavourable outcomes. By providing real-time, explainable interventions, our work makes a step further in making these tools widely accessible. As for other approaches providing counterfactual interventions, our model could in principle be adapted by malicious users to "hack" a fair system. Research on adversarial training can help in mitigating this risk.