{'fraction_non_alphanumeric': 0.030279083309071246, 'fraction_numerical': 0.007944100153890946, 'mean_word_length': 4.771483437349976, 'pattern_counts': {'":': 2, '<': 0, '<?xml version=': 0, '>': 2, '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}}
Optimality-based Analysis of XCSF Compaction in Discrete Reinforcement Learning

Learning classifier systems (LCSs) are population-based predictive systems that were originally envisioned as agents to act in reinforcement learning (RL) environments. These systems can suffer from population bloat and so are amenable to compaction techniques that try to strike a balance between population size and performance. A well-studied LCS architecture is XCSF, which in the RL setting acts as a Q-function approximator. We apply XCSF to a deterministic and stochastic variant of the FrozenLake8x8 environment from OpenAI Gym, with its performance compared in terms of function approximation error and policy accuracy to the optimal Q-functions and policies produced by solving the environments via dynamic programming. We then introduce a novel compaction algorithm (Greedy Niche Mass Compaction - GNMC) and study its operation on XCSF's trained populations. Results show that given a suitable parametrisation, GNMC preserves or even slightly improves function approximation error while yielding a significant reduction in population size. Reasonable preservation of policy accuracy also occurs, and we link this metric to the commonly used steps-to-goal metric in maze-like environments, illustrating how the metrics are complementary rather than competitive.


Introduction
Reinforcement learning (RL) is characterised by an agent learning a behavioural policy in an environment by means of maximising a reward signal. Learning Classifier Systems (LCSs) are a paradigm of cognitive systems that originated via representing agents in this framework, although due to flexibility in implementation have also been widely adapted to other kinds of machine learning (ML) tasks such as classification and clustering [16]. The most widely-studied LCS architecture to date, Wilson's XCS [18], is at its heart a reinforcement learner. More recently, an extension of XCS to allow for function approximation, dubbed XCSF [19], has been successfully used in the RL setting for value function approximation [12,13].
LCSs utilise a combination of evolutionary computation and ML techniques to create population-based solutions to prediction problems. The most common style of LCSs are Michigan-style LCSs, where each individual (classifier) in the population represents a partial solution, and classifiers co-operate in a potentially overlapping piecewise ensemble to define an overall solution [16]. A general issue with Michigan-style LCSs is that of population bloat and/or redundancy. Since these systems learn in an online fashion and regularly refine their population via a genetic algorithm (GA), after learning is complete there are often members of the population that have not had time to properly adapt to the environment and form accurate predictions.
A common way to deal with this issue is to perform a post-processing compaction procedure after the system is trained in order to remove low-quality classifiers from the population [16]. Compaction seeks to shrink the population size as much as possible while simultaneously minimising degradation of predictive performance. This is often done as part of an analysis pipeline where the system is being used to "mine" knowledge from the problem via interpretation of the compacted population [17]. Wilson originally described a compaction algorithm for a variant of XCS trained on a classification problem in [20], and other algorithms such as those detailed in [8,7,15] extended this line of work. These algorithms all incorporate some kind of greedy heuristic to preferentially retain some classifiers over others, and mainly use metrics related to classification performance. Since compaction is related to knowledge discovery, other works have focused more on this latter task [4,9,17]. What all these works have in common is that they study compaction in the context of supervised learning.
In this work we apply XCSF to discrete maze-like RL environments and perform compaction on the trained populations. We are interested in measuring the performance of XCSF with respect to the optimal solutions to the environments, and investigating how performance is impacted when performing compaction. As part of our analysis we introduce a novel compaction algorithm called Greedy Niche Mass Compaction (GNMC) as a generalisation of previous work. We also attempt to connect our optimality metrics to the steps-to-goal metric used by other work applying LCSs to maze-like environments.

Reinforcement Learning
RL environments can be modelled as a Markov Decision Process (MDP), defined by components (S, A, T, R, γ) where S is the state space, A is the action space, T is the transition function, R is the reward function and γ ∈ [0, 1] is the reward discount factor [14]. We consider the case where the agent interacting with the environment seeks to learn a deterministic behavioural policy π : S → A. From the agent's perspective, T and R are unknown and so learning becomes an act of balancing exploration with exploitation to sample from T and R in order to construct π. If the full definition of the MDP is known, dynamic programming methods such as value iteration can be used to exhaustively obtain an optimal solution to the problem.
Value iteration yields an optimal Q-function Q * : S × A → R, which maps each state-action pair (s, a) ∈ S × A to a real number representing the utility of the pair: the expected amount of cumulative discounted reward that can be obtained from performing action a in state s, and acting optimally thereafter. An optimal policy π * can then be constructed by acting greedily with respect to Q * . One of the main approaches to RL is to have the agent build an approximationQ to Q * from its environmental experience using e.g. temporal difference learning techniques such as Q-learning [14]. The agent's approximationπ to π * can then be constructed by acting greedily with respect toQ.

XCSF
XCSF is an LCS architecture designed to perform function approximation. It differs from XCS in that classifiers compute their predictions as a function of their inputs, instead of predicting a scalar value. The system operates by adaptively partitioning the input space into subspaces with classifiers (evolutionary component), in tandem with forming approximations to the target function in the subspaces (ML component) [3].
Classifiers take the form of IF condition T HEN action rules. Partitioning is accomplished by specifying the rule representation to be used by conditions. Common choices include hyperrectangles [19,12] and hyperellipsoids [5]. In the simplest case, linear functions can be used as a prediction scheme but extensions to the non-linear case have been investigated [11]. Additionally, classifiers have a number of parameters, denoted as cl.param, that store or calculate information related to them; the following parameters being important in this work: fitness -the predictive accuracy of a classifier relative to other classifiers in the action set(s) (defined below) that it participates in, numerosity -the number of copies of a classifier present in the population (necessary because the GA may produce classifiers with duplicate rules), generality -a quantity in the range (0, 1] representing the fraction of the input space covered by the classifier's condition. Numerosity yields the concept of macroclassifiers and microclassifiers, defined as the classifiers in the population with unique rule structures (possibly having numerosity > 1) and individual copies of these unique classifiers, respectively.
Applied as a RL method, XCSF uses a Q-learning style reinforcement component to form classifier predictions. The overall system outputQ is computed for each (s, a) ∈ S × A according to: [A] is termed an action set and contains classifiers in the population whose conditions match s and who advocate action a, i.e. XCSF's current knowledge about a particular niche of the environment.

Environments
We consider two variations of the FrozenLake environment with grid size 8 (FrozenLake8x8) from OpenAI Gym 1 . FrozenLake is an episodic, fully observable grid navigation environment. In this environment, the agent must navigate across frozen cells to reach a goal, without falling into any holes. If the agent falls into a hole the episode terminates. The state representation used is an (x, y) co-ordinate representing the location of the agent in the grid, as shown in Fig A parameter p slip controls the level of stochasticity in the environmental transition dynamics. Figure 1b gives examples of transition dynamics with p slip = 0.1. Transition stochasticity is global over all s ∈ S. By default p slip = 2 3 , which is quite high. For our variants, we consider the cases where p slip = 0 and p slip = 0.1, the latter because we wish to preserve the spirit of the default case while making the problem substantially easier through lowering the amount of noise incurred in transitions and therefore the reward signal. The reward function operates as follows: +1 if the agent transitions into G, 0 otherwise. We set γ = 0.95 to ensure that there is time pressure to reach the goal. Note that a time step is counted even if the agent does not move to a new state after performing an action (as occurs with 90% probability in the leftmost example of Figure 1b). Figure 2 shows the optimal policies for our two variants. In the deterministic case reaching the goal is a shortest path problem, hence in some states there are multiple optimal actions. In the stochastic case the optimal policy is more strict as there is only a single optimal action in every state. (b) Transition dynamics with p slip = 0.1. With probability 0.1 the agent slips to one of the directions perpendicular to its intended direction (mass shared equally across both possible slip directions). As illustrated by the leftmost example, the agent is unable to maneuver off the grid.

XCSF Configuration
We use our own implementation of XCSF written in Python 2 , faithful to the base description of XCS given in [2]. We use the same linear prediction scheme as in [19], where each classifier has an associated weight vector and its prediction is computed as a dot product between its weight vector and the input vector, and classifier weight vectors are updated via a normalised least mean squares procedure with the prediction target calculated via the system's reinforcement component. Also incorporated is the extension to XCS from [10], termed XCSµ, which is used to estimate uncertainty introduced by stochasticity in the environment. This involves adding a parameter µ to each classifier which tracks minimum prediction error in the action sets the classifier participates in, adjusted by a separate learning rate β .
The rule representation used is an interval-based representation, specifically an integer-valued variant of min-percentage representation [6]. Interval minimum alleles are retained but percentage-to-maximum alleles are replaced by "spanto-maximum" alleles; interval maximums calculated as: max = min + span. The covering and mutation operators from [6] are adopted and modified to work with integer values, resembling those in [21]. Subsumption and calculation of condition generality are the same as in [21]. GA selection is done via tournament selection and uniform crossover is applied on allele sequences.
The chosen rule representation and prediction scheme yield a system that learns linear predictions of value over rectangular regions of the input space. This is suitable for both FrozenLake8x8 environments because it exploits the fact that Q-values decay smoothly (due to discounting) when moving away from the goal. In areas of the state space where there are no holes, accurate generalisation over large areas is possible (refer to e.g. top two rows in Figure 1a) so only a few classifiers are required to cover such an area. The opposite is true for areas near holes. Compared to other Q-function approximators used in RL (e.g. neural networks), XCSF has the advantage of presenting its knowledge in a piecewise, easily interpretable format that can reduced to a compact set of classifiers (as is the theme of this work).
By default, the agent starts each episode in state (0, 0), which puts a heavy emphasis on exploration to reach the goal, making learning relatively difficult. To make learning easier, we allow the agent to start a training episode in any s ∈ S, selected uniformly at random. We can therefore safely adopt the alternating explore-exploit action selection strategy used elsewhere in the literature, i.e.greedy with a fixed value of = 0.5.

Metrics
Before training, we use value iteration to compute Q * and consequently π * for each environment. XCSF'sQ mean absolute error (MAE) can then be calculated as: 1 |S||A| s∈S a∈A MAE is used because we wish to directly compare with 0 . To allow for comparison between π * andπ, policies are encoded as a series of binary action advocacy vectors, one for each s ∈ S, whereby if policy π advocates action a i in state s, bit i of π(s) is set to 1, 0 otherwise. For example, following Figure 2a the optimal actions in state (0, 0) are {Down, Right}. Assuming the ordering of actions is {Lef t, Down, Right, U p}, then the encoding π * (0, 0) = [0, 1, 1, 0]. XCSF'ŝ π accuracy can then be calculated as: where C is a Boolean function that accepts two binary action advocacy vectors, a * andâ, and determines if at least one of the actions advocated in a * is also advocated inâ , i.e. determines ifâ is "correct": C a * ,â = 1 count ones a * ANDâ > 0 0 otherwise Reusing the previous example, if s = (0, 0), π * (s) = [0, 1, 1, 0] and alsoπ(s) = [0, 0, 1, 0] then C returns 1 becauseπ advocates one of the optimal actions, Right.  Figure 3 shows XCSF training performance curves for both environments, measured over time areQ MAE andπ accuracy. In the deterministic case, XCSF converges to a small MAE that is slightly larger than the target error threshold 0 , withπ accuracy very close to the maximum value of 1. In the stochastic case, MAE is still quite small but noticeably larger than in the deterministic case, also with larger variance.π accuracy is significantly lower and with much larger variance. We now investigate this reduction ofπ accuracy in the stochastic case in more detail. Figure 4 shows the frequency of optimal action predictions for each s ∈ S over the 30 trained instances. From this we can see that XCSF is quite often predicting the optimal action in a majority of states. However, there are a few states that are degrading policy accuracy more than others. Table 1 shows the distributions of actions predicted in the four states with lowest optimal action prediction frequencies, and indicates that for these states if the predicted action is not optimal (U p or Down) it is at least sensible (Right). Thus the situation is not as poor as it first seems.

Compaction
We now turn to the main consideration of this work: compaction of trained XCSF populations. Algorithm 1 presents Greedy Niche Mass Compaction (GNMC), a novel compaction algorithm designed for use on LCS populations applied to RL environments with discrete state-action spaces. GNMC considers all environmental action sets (niches) and greedily keeps some number of the best quality classifiers in each. The notion of "best quality" is defined by the parameter λ, which is a function that assigns each classifier a mass (quality weighting) in the action set. ρ acts as a compression factor and controls the number of classifiers kept in each action set; higher values result in more classifiers being discarded. GNMC exhibits a number of desirable properties: 1. The exact number of classifiers discarded in each action set is dependent on the distribution of classifier mass; ρ is sensitive to this distribution. 2. ρ can be adjusted in a smooth manner without needing prior information about the size of action sets. 3. It is guaranteed that no "gaps" in the predictive mapping are introduced, due to all action sets being considered and at least a single classifier being kept in each action set (because ρ cannot equal 1). 4. Any classifiers that only match a state s ∈ S T (and so have zero experience and do not contribute to overall predictions) are implicitly removed from the population because they are never added into the toKeep set; the for loop on line 2 operates only over S. This occurs even when ρ = 0. Notably, simple compaction strategies such as removing all classifiers with experience less than some threshold do not uphold point 3 listed above. This property is crucial for function approximation in RL where a complete mapping of the state-action space is necessary.
GNMC can be viewed as a generalisation of previous work in the literature. In particular, we consider the work of Tan et al. in [15], where the authors define  [1]) variant where accuracy is equivalent to fitness. GNMC is therefore equivalent to PDRC when the mass function λ(cl) = cl.f itness × cl.numerosity × cl.generality and the mass removal factor ρ is sufficiently high so as to keep only a single classifier from each action set.
We apply GNMC to our trained XCSF populations, considering three different mass functions, named with subscripts. The first is λ f it = cl.f itness, motivated by the manner in which XCSF calculates its overall predictions: see Eqn. 1. Classifiers with higher fitness have more weight in the overall prediction, so using fitness as a mass function makes sense. The second mass function is λ tan = cl.f itness × cl.numerosity × cl.generality. The final mass function is an antagonistic variant of the first mass function that is designed to see what happens when GNMC is operating with "bad information": λ inv f it = 1 cl.f itness . Figure 5 shows results of applying GNMC with these three mass functions to the XCSF instances trained on both environments, measured are the effect on performance (Q MAE andπ accuracy) and population size (number of macro and microclassifiers).
In the deterministic case, GNMC retains performance when either λ f it or λ tan is used, for any value of ρ.Q MAE improves very slightly as ρ increases, andπ accuracy is unchanged. Using λ inv f it gives smooth degradation in both metrics. Looking at the population sizes, both λ f it and λ tan exhibit a moderate reduction in the number of microclassifiers and a significant reduction in the number of macroclassifiers as ρ increases. However λ inv f it is different, yielding similar number of macroclassifiers in the extreme, but drastically smaller number of microclassifiers. This conforms to our expectations of its operation; classifiers that are kept by λ inv f it have low fitness values, and since low fitness classifiers tend to have low numerosity, the ratio of microclassifiers to macroclassifiers is low. For λ f it and λ tan the ratio is much higher. In the stochastic case, the situation is similar overall with a slight difference when considering the effect on performance: namely thatπ accuracy for both λ f it and λ tan is degraded slightly instead of remaining constant as ρ increases.

Rollout Analysis
We now investigate the relationship between policy accuracy and the commonly used black-box performance metric, steps-to-goal (STG), from other works applying LCSs to maze-like RL environments, e.g. [10,12]. Note that in such envi- Table 2: Results of STG testing procedure on FrozenLake8x8 p slip = 0.1 for three different groups of XCSF instances. Asterisks for mean and max STG indicate incomplete data. Set in bold are the "worst" values for each column (π acc. minimum, others maximum). ronments, minimising STG is equivalent to maximising cumulative discounted reward. For our analysis we consider only the stochastic variant of FrozenLake8x8, as it showed the most interesting variations inπ accuracy when GNMC was applied to it in Section 6.
A testing procedure to measure STG is devised as follows: allow each XCSF instance a budget of 150 rollouts (episodes) and in these 150 rollouts, attempt to record STG (successfully reach the goal) 100 times. If 100 successes are not achieved, STG data is incomplete. In each rollout, the agent's initial state is (0, 0) and the random seed of the environment is set to a unique number. Note this is different from training where the agent's initial state was any s ∈ S, selected uniformly at random. This testing procedure is applied to all 30 trained XCSF instances in three groups, representing different levels of GNMC compaction: no compaction, compaction with λ f it ρ = 0.99, and compaction with λ inv f it ρ = 0.99. Table 2 shows the collected results: included are mean and max STG, number of rollouts performed, andπ accuracy (for reference). Note that minimum STG in the environment is 14.
Group A in general achieves admirable mean STG; only 5 out of 30 instances could be considered as outliers. Number of rollouts for all instances is generally not much higher than 110. This indicates that in most instances XCSF is quickly navigating towards the goal, with a low failure rate due to environmental stochasticity. Comparing Group B to Group A, there are two instances in Group B that have failed to collect complete STG data, also having the two lowest policy accuracies. In general, all four measures degrade only slightly between the two groups, which indicates that the compaction applied to Group B is not having a detrimental effect on performance. Transitioning from Group A to Group C however produces noticeable performance loss. 11 out of 30 instances fail to record complete STG data, and generally those that do show degradation in all four measures.
It is difficult to determine the exact relationship between STG and policy accuracy. Some instances (e.g. instance 1) exhibit minimal degradation in both measures between groups, but some exhibit larger degradation (e.g. instance 22). In cases where degradation in policy accuracy is small but degradation in STG is large, the cause is often a minority of states along the edge of the grid that are advocating actions where the only possible way to advance further towards the goal is to slip, e.g. advocating Right in any of the states in the rightmost column (where x = 7). It is therefore clear that the two metrics are complementary rather than competitive. Policy accuracy is measured globally and is always defined, and STG is measured on a specific task (starting state), possibly being undefined/incomplete. The starting state is an arbitrary choice and if altered results in differing STG but unchanged policy accuracy.

Conclusion
We trained XCSF on a deterministic and stochastic variant of FrozenLake8x8, measuring its performance with respect to the optimal solutions produced via dynamic programming. Results show that in both cases XCSF achieved low Qfunction approximation error, and in the deterministic case XCSF converged to maximum policy accuracy. In the stochastic case policy accuracy was noticeably degraded both because of increased problem difficulty and increased strictness of the optimal policy. Next we introduced Greedy Niche Mass Compaction (GNMC), a compaction algorithm designed for LCSs applied to discrete RL environments. We showed GNMC is a generalisation of previous work and applied it to our trained XCSF instances. Given a suitable mass function, GNMC can yield a significant reduction in population size without increasing function approximation error and only slightly decreasing policy accuracy. Finally we linked our policy accuracy metric to the steps-to-goal metric used in previous work across multiple groups of compacted XCSF instances. This highlighted how the two metrics are complementary rather than competitive. Suggested future work includes applying GNMC to environments where populations are larger/more complex and the mass removal factor has more impact on performance. GNMC's concept could also be extended to continuous state and/or action spaces.