---
title: "Explainable machine learning multi-label classification of Spanish"
description: "This study tests how a random forest assigns multiple legal labels to Spanish court judgments and explains its choices with words and…"
canonical: "https://research.elamur.ai/free/en/papers/arriba-2024-perez-explainable-machine-learning-multi-label/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/arriba-2024-perez-explainable-machine-learning-multi-label/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2024](https://md.research.elamur.ai/free/en/papers/2024/) / Explainable machine learning multi-label classification of Spanish legal judgements

# Explainable machine learning multi-label classification of Spanish legal judgements

Paper · 2024 · Francisco de Arriba-Perez, Silvia Garcia-Mendez, Francisco J. Gonzalez-Castano et al.

**Authors:** Francisco de Arriba-Perez, [Silvia Garcia-Mendez](https://md.research.elamur.ai/free/en/authors/silvia-garcia-mendez/), Francisco J. Gonzalez-Castano and Jaime Gonzalez-Gonzalez · **Year:** 2024 · **Venue:** arXiv:2405.17610 · **Licence:** [CC BY-NC-ND 4.0 (arXiv)](http://creativecommons.org/licenses/by-nc-nd/4.0/)

[**16** citations OpenAlex, 2026-10-14](https://openalex.org/works?filter=cites:W4307723144) · [arXiv:2405.17610](https://openalex.org/S2764955546) · [licence](http://creativecommons.org/licenses/by-nc-nd/4.0/)

- [PDF](https://arxiv.org/pdf/2405.17610)
- [DOI 10.1016/j.jksuci.2022.10.015](https://doi.org/10.1016/j.jksuci.2022.10.015)
- [arXiv 2405.17610](https://arxiv.org/abs/2405.17610)
- [OpenAlex](https://openalex.org/W4307723144)

Citations: OpenAlex, 2026-10-14.

## Summary

A court judgment can be relevant to several areas of law at once. A dispute over a mortgage, for instance, can raise a question about rights attached to property and another about the obligations of a bank. A search tool that files the judgment under just one subject may make it harder to find from the other. The authors study how to assign several legal labels to a Spanish judgment and give the reader an account of how the software arrived at them. This is a problem in [legal AI](https://md.research.elamur.ai/free/en/topics/legal-ai/) whose immediate purpose is to help practitioners find and review decisions that may be relevant to their cases.

The system combines [text classification](https://md.research.elamur.ai/free/en/concepts/text-classification/) with information extracted from recognizable parts of a judgment. It counts words and short phrases, identifies details such as the court and jurisdiction, and replaces names with role tags where it detects them. The authors then compare two ways of learning from lawyers’ annotations. One trains a separate classifier for each legal label. The other treats every observed set of labels as a single choice during training and turns that choice back into a set when a judgment is classified.

The experiments use 106,806 judgments annotated by lawyers at E4Legal Analytics. Each judgment has up to three labels, and each label combines a broad legal order with three categories of law. In 10-fold cross-validation, a random forest trained to choose among complete label sets performed best overall. The abstract reports micro precision above 85, and the results section puts the average overlap between assigned and annotated sets, reported as accuracy, at around 74. The random forest that considered each label separately achieved higher recall, so it recovered more of the annotations under the reported recall measure.

The authors also address [interpretability](https://md.research.elamur.ai/free/en/topics/interpretability/) by showing which word counts a tree tested, which path it followed and what label set appeared at the end. The system draws on these paths and on estimates of feature relevance to produce templated explanations, alongside details extracted from the judgment. These explanations describe why the software categorized a document as it did. Whether that account helps a lawyer find relevant cases, detect a mistaken label or decide when to trust a suggestion remains a separate question from how well the labels match the annotations.

## Deep dive: Explainable machine learning multi-label classification of Spanish legal judgements

This study tests how a random forest assigns multiple legal labels to Spanish court judgments and explains its choices with words and decision paths. · about 33 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### Why a judgment can belong in several places

Legal practitioners consult earlier judgments to understand the context of a case they are working on. A database organized by jurisdiction provides one way into that material. Inside a jurisdiction, however, a practitioner may be looking for a particular point of law that arises across several kinds of dispute. The authors describe a further complication in the judgments themselves. Writing styles differ, and formal organization varies enough to make it difficult to identify comparable decisions consistently. Human reviewers may also weigh the same details differently. The paper presents automatic categorization as a way to assist with this search and reduce the amount of repetitive filing work.

A keyword provides a direct way to look for a term, but its presence and the legal relevance of the document are separate matters. The authors describe keyword-based retrieval as susceptible to returning too much or too little. A judgment can mention a legal topic as background without turning on it. Conversely, judgments with a similar legal issue can describe it in different terms. A category assigned to the document gives a reader another way to reach it. The value of that route depends on the quality of the annotation scheme and on how consistently a classifier can reproduce it across judgments.

The mortgage example in the paper shows why the unit being assigned matters. The legal annotation associates one part of the judgment with property rights, security rights and mortgage law under a civil/mercantile order. Another part concerns contractual obligations, financial markets and banking law under a mercantile order. Someone researching mortgage rights and someone researching how a bank must recalculate payments could both have reason to read the same decision. The annotation records both views of the judgment, with each view carried by a complete label. The classifier is trained to produce those document-level labels. The passages illustrating them help a reader understand why the labels can coexist.

The authors distinguish this from a yes-or-no classification and from a task that picks one class from a list. A binary classifier might decide whether a particular category applies. A single-choice classifier might select one subject from several alternatives. In the paper’s task, a judgment has a set of labels, each of which can take a value from the legal classification scheme. The distinction matters at evaluation time. A system that retrieves one appropriate label and omits another has accomplished something that a wholly incorrect answer has missed, even though neither answer reproduces the full annotation.

#### How earlier studies approached the assignment

The paper groups previous [machine learning](https://md.research.elamur.ai/free/en/concepts/machine-learning/) methods into transformation and adaptation approaches. Transformation changes the shape of the task so that existing classifiers can handle it. A separate yes-or-no question for every category is one example. Treating a recurring set of categories as a single class is another. Adaptation changes the learning algorithm so that it can work directly with multiple labels. The paper discusses adaptations to nearest-neighbor classification and ranking methods, as well as neural approaches whose output layer can assign several labels to the same input.

An independent binary classifier can learn from every judgment that carries its label, including judgments whose other labels differ. The cost is that adding possible labels adds classifiers, each with its own training and prediction work. Independence also means that a positive decision for one label is made without consulting the other binary decisions. The literature reviewed in the paper explores ways to account for relationships between labels. Ranking methods can consider pairs of relevant and irrelevant labels. A classifier chain can pass an earlier prediction to a later classifier. The authors describe the more elaborate dependency approaches as more computationally demanding.

Learning whole combinations offers a different way to use co-occurrence. A repeatedly observed bundle can become a class in its own right. This gives the classifier a way to learn that the labels belong together in some judgments. It also means that a bundle must have enough examples to be recognized as a class, even if the individual labels are well represented elsewhere. The authors note that legal categories are frequently imbalanced. Frequent categories and combinations bring more training evidence, while a small class can be difficult to distinguish when it shares vocabulary with larger ones.

The related work also establishes why task details matter when comparing legal classifiers. The paper describes single-label studies on U.S. judgments, including one in which a random forest using features based on domain concepts outperformed the deep learning alternatives tested there. It discusses a court-judgment classifier by Csányi and colleagues that used a separate binary transformation with over a hundred classifiers. It also describes Song and colleagues’ work on posture50k, which used domain-specific pretraining and attention to the labels for an extreme multi-label task. The authors discuss classification of legislation separately because the documents and the methodologies used for them differ from those for court decisions.

#### What an explanation is meant to explain

In the authors’ account, users of a legal information system have reason to want more than a label. A lawyer reviewing a suggested category may want to see which words or extracted details contributed to it. That information can make a surprising assignment easier to examine. The paper grounds this objective in earlier work on explainable artificial intelligence, which distinguishes questions about whether an account is understandable, whether it gives the reader useful information and whether it reveals how the system behaves. These questions apply to different parts of the system, from the classifier’s decision rules to the wording of the explanation. [Explainable Artificial Intelligence (XAI)](https://md.research.elamur.ai/free/en/papers/arrieta-2019-explainable-artificial-intelligence-xai-concepts/)

The authors identify related legal studies that explain human annotations or inspect attention weights. They frame their own contribution around producing an automatic classification and accompanying it with a visual and verbal account at the feature level. That requirement informs the choice of classifier. A tree exposes the tests on a route to its prediction, and a template can describe those tests using the names of the features. The explanation concerns the software’s handling of a judgment that already exists. The object being explained is the assignment of subject labels to that document, rather than the judicial reasoning through which the court decided the case.

### The method, step by step

#### From a written judgment to a set of labels

The input is the text of a Spanish judgment. The desired output is a set whose members describe the areas of law under which that judgment has been classified. Each label starts with a substantive order, a broad division such as penal, social or tributary law, and includes three law categories associated with that order. The other orders named in the paper are civil, administrative, civil/mercantile and mercantile. The entire combination constitutes one label. A judgment can have up to three such combinations, which makes the annotated target a set of structured labels.

There are two kinds of evidence on the input side. The text supplies repeated words and phrases that may help distinguish legal subjects. The document also has sections and identifiers from which details such as court and jurisdiction can be extracted. The authors turn both kinds of evidence into features, the input variables on which the classifier makes decisions. They reduce the vocabulary before training, compare different ways of encoding the lawyers’ annotations and then translate the predictions back into the legal categories a reader recognizes.

From a Spanish judgment to labels and explanations The steps in order.

#### Prepare the text and read its legal structure

The cleaning stage removes layout and formatting material such as page breaks, tabs, URLs, punctuation and redundant spaces. The authors also remove stop words, which in this pipeline are words that the stop-word list treats as unlikely to help distinguish documents. The next operations are [tokenization](https://md.research.elamur.ai/free/en/concepts/tokenization/), which divides the text into word units, and [lemmatization](https://md.research.elamur.ai/free/en/concepts/lemmatization/), which reduces inflected forms to their base forms. By grouping forms of a word under a shared representation, the pipeline can count them as evidence for the same feature. The implementation uses the Spanish `es_core_news_md` component of spaCy for lemmatization and NLTK for stop-word detection.

The authors use the organization of Spanish legal documents to guide [information extraction](https://md.research.elamur.ai/free/en/concepts/information-extraction/). A typical judgment begins with a heading that identifies the legal resolution and the parties. The statement of facts describes the dispute and its procedural history. The legal grounds relate the facts to applicable law and prior decisions. A decision section records the court’s disposition. The extraction rules can therefore look for particular details in the places where those details are expected. Searching the disposition for a decision term, for instance, gives the term a more specific function than counting its occurrences throughout the judgment.

The case-type detector combines an official vocabulary, official abbreviations and pattern matching. When the search produces several matches, it keeps the first. The court detector likewise applies a regular expression, a rule for matching textual patterns, with a vocabulary derived from the Spanish court administration’s public access point. Both operations turn text into a categorical value. For the classifier, a detected court or case type is a distinct input from a phrase that happens to include some of the same words.

To identify the decision, the system checks terms extracted from the decision section against a legal vocabulary. A single recognized term can supply the decision value, and several recognized terms lead the system to record a multiple decision. Decision type is a separate item. The authors treat the decision in a judgment as substantive and the decisions in orders and decrees as procedural. Resolution type identifies the kind of legal document and is sought near the end of the heading, immediately before the facts. These distinctions allow the architecture to retain details about what kind of document it is reading and what action the court took.

Instance type is inferred from terms in the recognized case type. The paper maps `recurso` to its first-instance category, terms such as `apelación` and `suplicación` to its second, and `casación` and `unificación` to its third. Cases outside these rules enter the system’s higher-instance category. For jurisdiction, the authors describe several sources in decreasing order of effectiveness in their experience. The preferred source is the judicial division listed with the court information. Another source is the General Identification Number, where digit 8 encodes jurisdiction. The case-type vocabulary gives a further route to an answer. The resulting jurisdiction value is a feature used in prediction. The substantive order is part of what the classifier is asked to predict.

#### Replace names while preserving roles

The anonymization module looks for personal titles, less explicit references to people and legal forms used in company names. The surrounding names can then be replaced with tags such as `@Judge`, `@Corporate` and `@Person`. The system checks names near the tags against data from Spain’s national statistics institute. It also uses an index supplied by E4Legal Analytics through Solr to check identified people and companies and to correct role assignments. The generic `@Person` tag is excluded from that index-based check.

Different references to a name can appear in slightly different forms. The authors use Jaro distance, a string comparison measure, through the Python library jellyfish to find similar occurrences and bring them together. Replacing a judge’s name with a role marker preserves information that the person is a judge while removing the name from the representation where the procedure detects it. The authors undertake this step both because the judgments contain sensitive information and because they want the classifier’s textual features to rely less on personal identity.

#### Turn words and extracted details into features

A textual feature is a count for a word or a sequence of adjacent words. The technical term [n-gram](https://md.research.elamur.ai/free/en/concepts/n-gram/) refers to such a sequence, with its length given by *n*. The final representation includes single words and adjacent word pairs. A pair can carry information that is dispersed across its component words. The paper’s tree illustration, for example, uses the count for `seguridad social`, Spanish for social security. The representation records it as a phrase in its own right.

The authors use CountVectorizer to build the count representation and GridSearchCV to search alternative vocabulary settings. The chosen upper document-frequency limit is 0.5 and the lower limit is 0.01. These settings concern the share of documents containing a term. The vectorizer excludes terms occurring in a share strictly above the upper limit or strictly below the lower one. The selected n-gram range is (1,2), admitting words and pairs of neighboring words. The tested alternatives included different frequency cutoffs and ranges extending to longer word sequences. The authors reserve a subset for this search, with the stated purpose of reducing bias in later classification.

The legal features come from the extraction rules. They record values such as the case type and court, alongside the vocabulary counts. The authors examine how the categorical features relate to the target using Spearman’s rank correlation. This measure asks whether higher positions in one ranking tend to correspond to higher or lower positions in another. It can capture a consistently increasing or decreasing relationship whose rate of change varies. In describing the analysis, the paper refers to a 10-step discretized scale for the ranks.

```
rₛ = cov(R(X), R(Y)) / (σR(X) · σR(Y))
```

Here `rₛ` is the Spearman coefficient. `X` and `Y` are the variables being compared, and `R(X)` and `R(Y)` are the corresponding rank variables. `cov` is the covariance of the ranks. `σR(X)` and `σR(Y)` denote their respective standard deviations, and the dot multiplies those standard deviations in the denominator. The coefficient ranges from -1 to +1. The extremes describe perfectly decreasing and increasing relationships in the ranks.

The architecture allows features to be screened using a configurable correlation threshold and also considers importance estimates obtained in training. For the latter, the experiment uses scikit-learn’s SelectFromModel with a random forest of 20 estimators. SelectFromModel is a feature selector that uses importance weights produced by a fitted classifier. In this step an estimator is an individual tree in the forest. The final input set reported comprises 1928 of the 9581 distinct word and word-pair features considered, along with the court, decision, jurisdiction, and types of case, instance and resolution. Decision type belongs to the extraction and explanation descriptions and is absent from the reported list of retained classifier inputs.

#### Learn separate label decisions or whole sets

The first training strategy, which the authors call binary transformation, gives every possible legal label its own column. The rows are judgments. A cell records whether the annotators supplied that label for that judgment. The label in a column is a complete combination of substantive order and law categories. The scheme therefore trains a binary classifier on the presence of the mortgage-related label in the example and another on the presence of the banking-related label. Both can be positive for the same judgment.

```
βᵢⱼ = 1 if λⱼ ∈ Lᵢ, and 0 if λⱼ ∉ Lᵢ
```

`βᵢⱼ` is the training entry in row `i` and column `j`. `i` indexes a judgment, `j` indexes a class and `λⱼ` is the complete legal label associated with that column. `Lᵢ` is the set of labels annotated for judgment `i`. The symbol `∈` means that the class belongs to the set, and `∉` means that it is absent. The value `1` records a positive training example for the column and `0` records a negative example.

The distinct labels observed across the training judgments define the columns. At prediction time, each column’s classifier gives its own decision. Reading the positive entries back into their legal meanings produces the predicted set. This lets the classifier for a given label draw on cases where that label appears alone and on cases where it co-occurs with various other labels. Since each decision is made separately, the construction also permits a set of labels to be assembled even when that precise combination was absent during training.

The second strategy, multi-class transformation, gives a code to each distinct complete label set. The authors can order the component labels alphabetically because their labels are strings. This converts different orderings of the same set to the same code. The order sorted into the code serves only to identify the set. The underlying legal annotation gives no priority to a label merely because it comes first alphabetically. In the mortgage example, the conjunction of the civil/mercantile and mercantile labels is one training class. Each of those labels by itself would correspond to a different class if observed as a complete annotation.

```
αᵢ = j if fᵣ(Lᵢ) = L′ⱼ, with αᵢ ∈ [1,p]
```

`αᵢ` is the integer class code assigned to judgment `i`. `Lᵢ` is that judgment’s annotated label set, and `fᵣ` is the function that puts its labels into the canonical order. `L′ⱼ` is the distinct ordered combination identified by code `j`. The equality inside the condition means that the reordered annotation matches that combination. `p` is the number of combinations available as classes, and `[1,p]` gives the inclusive range of the codes.

After training, the classifier picks a combination code and the system looks up its constituent labels. A prediction can therefore contain multiple labels even though the classifier chose a single class internally. This transformation can learn a recurrent joint assignment directly. Its possible outputs are bounded by the combinations available to the classifier. The difference between the strategies concerns the unit that can be learned and returned, even though both ultimately produce sets evaluated against the same kind of annotation.

The authors test tree-based classifiers with both transformations. A decision tree passes a judgment through a series of tests on its features. A split might send judgments with a word-pair count above a threshold down one branch and other judgments down the other branch. The final node, called a leaf, supplies a prediction. In a random forest, many trees contribute predictions. The architecture also tests an individual Extra Tree and an ensemble of Extra Trees. For the authors, trees serve practical purposes at training and explanation time. The same feature tests that generate a prediction are available to inspect once the tree has made it.

#### Explain an assignment at the level of its inputs

The explanation procedure follows the path a judgment takes in each tree. It collects the word features used in those paths and orders them by how often they occur. A phrase used in a split helps route the document whether the phrase is abundant, scarce or absent. Frequency in the collection of paths concerns how often the feature is tested. Frequency inside the document is the value a particular split tests. Distinguishing these two senses of frequency helps make sense of why the software might mention a phrase that occurs rarely in the judgment.

The authors also use Local Interpretable Model-Agnostic Explanations, abbreviated LIME. This method changes inputs around the judgment being explained and observes the effect on the classifier’s response. It then uses feature selection to describe which inputs matter in that local neighborhood. The paper combines those results with its frequency-ordered collection of path features and keeps the first seven entries described in that procedure. The tree paths supply the actual tests that the judgment encountered. LIME supplies estimates of local relevance, derived by asking how predictions respond to changes in inputs. [Explaining the Predictions of Any Classifier](https://md.research.elamur.ai/free/en/papers/ribeiro-2016-why-should-i-trust-explaining/)

A tree visualization can present the splits and their outcomes, and a language template can put the same kind of evidence into sentences. The explanation is enriched with the available case details, including court, decision, decision type, instance, jurisdiction and resolution type. The paper describes the forest’s final decision through the agreement of its trees. For the confidence values displayed in templates, it uses `predict_proba`, which averages the individual trees’ predicted class probabilities. The probabilities are thus based on the fitted forest and refer to its choices among classes.

#### Score complete and partial agreement

The paper’s measures distinguish full agreement from partial agreement. Each judgment has an annotated set and a predicted set. An exact match requires these sets to contain precisely the same labels. The exact match ratio averages that outcome over test judgments.

```
Exact match ratio = (1/n) Σᵢ₌₁ⁿ I(Lᵢ = Zᵢ)
```

`n` is the number of test judgments, and the sum `Σᵢ₌₁ⁿ` runs over their indices `i`. `Lᵢ` is the annotated set and `Zᵢ` the predicted set for that judgment. The equality inside `I` compares the complete sets. `I` is an indicator, returning `1` when the condition holds and `0` otherwise. The factor `1/n` converts the sum into an average.

The authors’ example-based accuracy uses the overlap of the two sets. A missed annotation and an extra prediction each increase the collection of labels against which the overlap is judged. This gives credit for recovering part of the annotation while also taking unsupported assignments into account.

```
Accuracy = (1/n) Σᵢ₌₁ⁿ |Lᵢ ∩ Zᵢ| / |Lᵢ ∪ Zᵢ|
```

`n` is the number of test judgments and `Σᵢ₌₁ⁿ` sums over the judgments indexed by `i`. `Lᵢ` is the annotated set, and `Zᵢ` is the predicted set. The intersection `∩` contains labels in both sets, and the union `∪` contains every label in either set. Vertical bars count the labels in the collection they enclose. The fraction inside the sum is the overlap score for the judgment, and `1/n` averages those scores.

Precision and recall distinguish extra assignments from missed annotations. The paper’s prose reverses their denominators in the evaluation section. The displayed equations define precision using the predicted set and recall using the annotated set. Those are the definitions used here to explain the measures.

```
Precision = (1/n) Σᵢ₌₁ⁿ |Lᵢ ∩ Zᵢ| / |Zᵢ|
```

Here `n` is the number of test judgments, and `Σᵢ₌₁ⁿ` sums over judgments `i`. `Lᵢ` and `Zᵢ` are the annotated and predicted label sets, respectively. Their intersection `Lᵢ ∩ Zᵢ` contains the correct predictions. The vertical bars count elements, so `|Zᵢ|` is the number of predicted labels. The formula scores the share of the prediction supported by the annotation and then averages over judgments with the stated factor `1/n`.

```
Recall = (1/n) Σᵢ₌₁ⁿ |Lᵢ ∩ Zᵢ| / |Lᵢ|
```

`n` again denotes the number of test judgments, and `Σᵢ₌₁ⁿ` sums over their indices `i`. `Lᵢ` is the annotated set, and `Zᵢ` is the predicted set. The intersection `∩` selects labels shared by the sets. Vertical bars count labels, with `|Lᵢ|` giving the number of annotated labels. This time the ratio scores the share of the annotation recovered. The factor `1/n` averages the per-judgment ratios.

Hamming loss considers each possible label for each judgment. It counts a mistake when the label is predicted and absent from the annotation, or when it belongs to the annotation and is omitted from the prediction. Correct absences remain part of the number of opportunities for error, so the result must be understood in relation to the size of the class vocabulary.

```
Hamming loss = (1/(|C| · n)) Σᵢ₌₁ⁿ Σλ∈C [I(λ ∈ Zᵢ ∧ λ ∉ Lᵢ) + I(λ ∉ Zᵢ ∧ λ ∈ Lᵢ)]
```

`C` is the set of possible labels, `|C|` counts those labels, and `n` is the number of test judgments. The dot multiplies those counts. The outer sum runs over judgments `i`; the inner sum runs over labels `λ` in `C`. `Zᵢ` is the predicted set and `Lᵢ` the annotated set. `∈` and `∉` mean membership and absence, respectively, and `∧` requires both conditions to hold. `I` returns `1` for a true condition and `0` otherwise. The plus sign adds the indicators for a spurious label and a missed label. The denominator expresses the count as a share of all judgment-label decisions, so smaller values indicate fewer errors.

The paper also reports precision, recall and F-measure using micro and macro averaging. F-measure summarizes precision and recall together. Micro averaging pools label decisions before calculating the measure, giving frequent classes more influence through their larger number of cases. Macro averaging first computes the measure for each class and then gives the classes equal weight in the average. Example-based averaging gives each judgment the same weight. These choices answer different questions about the same predictions. Macro averages are especially informative when a pooled score could be dominated by commonly assigned labels.

### Experiments and results

#### The judgments and the comparison

Lawyers at E4Legal Analytics annotated the experimental collection of 106,806 judgments. The paper reports up to three labels per document and an average label cardinality of 1.39. Cardinality here is the number of legal labels assigned to a document. The average expresses how often multiple assignments enter the task, without specifying which labels occur together. After multi-class transformation there are 47 distinct classes. Those classes count complete sets of labels. A label that occurs alone in some judgments and with a companion in others can contribute to several transformed classes.

The anonymization pass gives a separate view of the collection. The authors report detecting sensitive data in all 106,806 documents. The module replaced 188,710 occurrences attributed to lawyers, 128,260 attributed to solicitors and 266,839 attributed to judges, along with 22,365 occurrences of names of people involved in the cases. These are counts of replacements or occurrences in the text. The same person can appear repeatedly within or across documents. The counts indicate the scale of the operation and are distinct from an evaluation against independently annotated personal information.

The internal comparison puts a Decision Tree, an individual Extra Tree, an Extra Trees ensemble and a Random Forest under each target transformation. These are the experimental baselines for one another. Comparing the same classifier family across the two transformations helps isolate a practical difference between the encodings, while comparing tree families within a transformation shows what happens when the learner changes and the form of the target stays fixed. The authors selected these families based on performance in related work and on the prospect of extracting explanations from their decisions.

GridSearchCV was used to tune the settings. The search considered class weighting, depth, the number of training examples needed to split a node, the minimum number at a leaf and the criterion for judging the quality of a split. The single-tree searches also considered how a split was selected. For ensembles, the candidate numbers of trees were 50,100,200. These are candidate settings for the classification ensembles. The 20 estimators used during feature selection belong to a separate random forest. The authors searched for settings independently for the binary and whole-set strategies.

The reported evaluation used 10-fold cross-validation for each classifier and transformation pairing. Cross-validation rotates which partition supplies the test judgments and fits the classifier on the remaining partitions. The ratings therefore concern predictions made on test folds of the same experimental collection. The authors also describe tuning the feature representation and the classifier settings on subsets of the data to reduce bias. The comparisons in the paper summarize the results across the cross-validation procedure.

#### The best assignment strategy depends on the measure

The random forest with multi-class transformation was the best overall configuration in the authors’ assessment. Its example-based accuracy was around 74, meaning that the score for each test judgment was based on the intersection of annotated and predicted labels compared with their union. The precision headline in the abstract is above 85 on the micro average. The conclusion gives 85 for micro precision. These are the paper’s own levels of precision in describing the results. Micro precision reflects support for pooled label assignments across the test judgments. Exact match concerns how frequently the complete predicted set agrees with the complete annotation.

The random forest using binary transformation had higher recall. Since the binary classifiers face each label separately, they can recover an annotated label even when the other labels with which it appears form an unusual combination. That is one possible interpretation of the recall result. The paper gives the observed metric ordering without an error breakdown that would establish the prevalence of that particular behavior. A classifier that selects the whole set may benefit from expecting some labels to occur together, and may lose an opportunity to recover an individual label when choosing between similar bundles. The recall comparison gives a reason to keep those possibilities in view when reading the overall ranking.

In comparisons on a percentage scale, the authors report that multi-class transformation raises exact match and precision by up to 10 points. The two measures capture different changes. Precision improves when a greater share of predictions belongs to the reference annotations. Exact match improves when enough additions and omissions are resolved for a document’s sets to agree completely. The paper also notes that some binary classifiers seemed to have difficulty separating classes sharing n-gram values. This is a plausible explanation for part of the pattern. The observed result is the relative performance of the tested configurations on the annotated collection.

Training cost favored the whole-set approach in the authors’ account. The paper attributes the cost of binary transformation to the number of independently trained classifiers. It gives exact training times for the binary Random Forest and Extra Trees ensemble. The comparison below shows those timings within a shared transformation. The shorter time belongs to the Extra Trees ensemble. The overall quality ranking uses the classification metrics and favors the whole-set Random Forest.

Binary-transformation training time on the Spanish judgment collection The Extra Trees ensemble trained faster than the Random Forest under binary transformation.

**The numbers**

| System or setting | training time in seconds |
| --- | --- |
| Random Forest, binary transformation | 1911.29 |
| Extra Trees ensemble, binary transformation (this paper) | 1546.67 |

#### What readers can see in the explanation examples

The paper illustrates a partial tree from the random forest with branches that test phrases such as `actividad laboral` for work activity, `seguridad social` for social security, and `económico administrativo` for an economic-administrative matter. On one route in the example, the work-activity feature is below 0.5, and the social-security and economic-administrative features exceed 0.5. The example assigns a tributary label involving financial and tax law, tax law and corporate law. The same route also produces a mercantile label involving contractual obligations, contract law and consumer law.

A different illustrated route checks for work activity and for `art CP`, an abbreviation associated with a penal code article. The respective counts exceed 0.5 and 1.0. The assignment shown falls under the penal order and addresses tort law, road traffic law and crimes against collective security. The examples show how a path through feature tests can be connected to the legal categories at the leaf. In a forest, the illustrated tree supplies part of the evidence for the ensemble’s decision. The authors use a partial tree so the reader can see what this contribution looks like.

The thresholds were learned during training. They remain fixed when a fitted tree is used to explain an individual test judgment, though a later split in the same tree can test a different feature or use a different threshold. The explanation’s scope is consequently concrete. A reader can look at an input feature, see how its value sent the judgment down a branch and follow the displayed path to its outcome. The templated account can add contextual information from the document and a confidence value from the forest.

#### How the authors situate the scores

The external comparisons use figures reported by earlier papers. Qiu and colleagues obtained macro precision of 98.07, macro recall of 99.61 and macro F-measure of 98.84 with a convolutional approach on a collection of 143 legal documents. The authors draw attention to both the size of that collection and the reported training time of roughly 3 hours. The macro scores represent averages over classes, and the current paper’s headline precision is a micro average on a different collection. Each set of figures describes the corresponding study’s own task.

The paper reports that Csányi and colleagues’ binary-transformation system reached 31 on exact match, 57 on accuracy and 80 on F-measure. These figures give context for the Spanish system’s results because the earlier study also allowed multiple assignments for a judgment. Differences in the labels, documents and implementation limit the comparisons that follow from the numbers. The paper uses the work to situate its system among existing judgment classifiers. The internal cross-validation comparison is the one that keeps the Spanish annotation task fixed.

Song and colleagues reported 87.80 micro precision and 80.30 for both micro recall and micro F-measure, as relayed by the authors. The macro figures reported for that work were 31.40 for precision, 28.70 for recall and 28.40 for F-measure. Training took approximately 3 hours according to the comparison. The difference between the micro and macro figures illustrates how aggregate performance and equal-weight class performance can look quite different on an imbalanced task. The authors characterize their own approach as competitive while drawing attention to an output the external comparisons did not target, an automatic natural language and visual account of the assignment.

### What the ablations show

#### The comparison that changes the prediction target

The paper reports no component-removal ablation. Its analyses instead compare target transformations and tree learners, search feature settings, inspect feature associations and illustrate the explanation procedure. Those activities support different conclusions. A comparison of classifiers can rank the implementations trained for this collection. A feature analysis can indicate which inputs are associated with the annotation. A picture of a tree can demonstrate what information the system can expose for one decision. The strength of the evidence depends on the question being asked.

The closest comparison to a controlled test holds the classifier family and the judgment collection fixed while changing the transformation. The whole-set Random Forest gave the strongest overall results, while its binary counterpart gave better recall and took more time to train. The former learns recurring combinations and only has to choose among known combinations when predicting. The latter learns each component label from all available positive examples for that label and pays the computational cost of fitting separate classifiers. The results show how those designs performed as complete alternatives. Because each was tuned independently, the comparison reflects the joint effect of the encoding and the settings chosen for it.

The label vocabulary helps explain why the contrast could matter beyond runtime. Consider two judgments that share the mortgage label. If one carries the banking label and the other carries a different companion label, the binary mortgage classifier can learn from both as positives. The whole-set classifier sees two different targets. Conversely, when the mortgage and banking labels regularly go together, the whole-set classifier can learn the combination directly. The reported performance establishes that whole-set learning worked well on this collection. The examples of how evidence is shared or separated are consequences of the design and help explain why the outcome could differ on a collection with a different mix of label combinations.

#### What feature selection establishes

The document-frequency search and n-gram search establish which vocabulary configuration the tuning procedure selected for the experiment. In the reported configuration, the text features covered words and word pairs, subject to lower and upper document-frequency cutoffs. The fitted selector then retained a subset of those features and a set of categorical variables. This establishes the representation presented to the final classifiers. The effects of moving to longer sequences, removing the legal features altogether or using the full initial vocabulary on the final cross-validation scores remain unmeasured in the reported comparison.

The Spearman analysis provides a different kind of evidence. It shows that some of the categorical features have an association with the target rankings used in the analysis. This supports the authors’ decision to explore extracted details as predictors. Associations can overlap, however. Court and jurisdiction may each carry information about the legal setting of a case, and the words in the judgment may express some of that same information. Determining how much predictive value each feature adds would require a comparison in which the remaining inputs and evaluation procedure are held fixed while that feature is varied.

#### What the explanation example establishes

The partial tree demonstrates that a reader can trace a particular output to explicit tests on the document’s features. It also shows how thresholds can yield different outcomes when the same feature is used differently along different paths. The language templates convert that kind of material into a verbal description and can supplement it with extracted case details. These are demonstrations of what the system can present. The examples give a way to inspect an assignment at the level of the fitted classifier.

The paper combines path tracing, LIME and context from legal extraction in the same explanation procedure. No controlled comparison measures their contributions to a reader’s understanding. A path can explain which tests determined the route within a particular tree. LIME can identify inputs to which the prediction is locally sensitive. A court or resolution type can help a reader place the case, including when that detail was supplied as context. Their roles are visible in the method, while the combined effect on the reader remains outside the experimental measures. The classification scores evaluate the labels. The example explanations illustrate the kind of account attached to them.

### Limitations

#### Limits and next steps identified by the authors

The authors describe this study as an initial investigation centered on Spanish judgments. They propose extending the label space to represent the full Spanish legal system through extreme multi-label learning, an approach aimed at settings with a very large number of available labels. They also plan to study dependencies among the law categories more directly. Multi-class transformation captures observed co-occurrence by assigning a common code to a complete set. Studying dependencies would ask which relationships among individual legal labels can be learned and used across different groups of judgments.

The paper also proposes exploring [transformers and attention](https://md.research.elamur.ai/free/en/concepts/transformer/) for the specialized language of the task. The reported results are evidence for the tested tree-based system with its engineered inputs. The proposed direction leaves open the empirical question of whether a different representation of Spanish legal language improves assignment and how the resulting explanations would compare. The authors’ present argument for tree classifiers rests partly on being able to follow the feature tests that produce a prediction at a reasonable cost.

The authors recognize important constraints in the external comparisons. The Qiu study used a much smaller collection. Other studies used different learning methods and training procedures. Some dealt with a single-label task or legislative documents and were excluded from the direct discussion of comparable judgment tasks. The authors also point out that the judgment classifiers they compare against did not have to supply their kind of explanation. The resulting comparisons show where the reported scores sit among studies with related aims. They give limited grounds for ranking the systems across a common task or attributing timing differences to the algorithms alone.

#### Limits that follow from the experimental setup

The test folds came from the collection annotated by lawyers at one organization. This supports an estimate of how well the procedure reproduces those annotations within that collection. Performance across independently annotated judgments, unfamiliar document conventions or a future period remains open. The paper also gives no measure of how often annotators disagreed with each other. As a consequence, the scores alone cannot show how much of the remaining discrepancy comes from difficult prediction cases and how much reflects cases where legal readers might reasonably choose different labels.

The document conventions are especially important for the legal extraction steps. The procedure expects to find certain information in headings, decision sections and identifiers, and it backs those expectations with particular vocabularies. The paper gives a specific account of how the extractor reads Spanish judgments but does not report precision and recall for each extracted field against a separate set of human annotations. The reported association between a feature and the target tests a different issue. It can show that the extracted value is related to the classification while leaving its reliability as a description of individual documents uncertain.

The scope of the two target transformations also differs under changes to the legal taxonomy. In multi-class transformation, a label set must have a code that the classifier can predict. An unfamiliar combination of familiar labels therefore poses a structural difficulty. The binary transformation permits such a combination, but each new legal label requires training evidence and its own classifier. The results show a favorable balance for whole-set prediction on the observed collection. They leave open where that balance would shift as the number of combinations, the representation of rare categories or the volume of available annotated data changes.

The paper reports subset-based tuning to reduce bias, but gives limited detail on how the tuning subsets and feature-selection fits relate to every test fold. A reader consequently cannot reconstruct whether every learned preprocessing decision was refitted with complete separation from the data evaluated in each fold. The reported comparison still provides a common experimental setting for the classifiers. The detail matters when interpreting the cross-validation scores as an estimate of the performance a new collection would see under the full training procedure.

Micro precision is useful for gauging the share of correctly assigned labels in the pooled predictions. Under class imbalance it leaves considerable room for variation in how well the system handles infrequent categories. A high pooled score may be driven by labels with many instances, while macro averaging makes the performance of each class count equally. Neither average reveals which legal distinctions account for the errors. For a practitioner interested in a rare subject, the practical question concerns retrieval of judgments bearing that particular label. The aggregate scores provide only indirect evidence on that question.

#### Limits of the privacy and explanation claims

The conclusions describe anonymization as assuring confidentiality and avoiding bias. The experimental evidence records detected sensitive material and the replacements made by the rules. It gives no independently measured rate of missed identifiers, and it gives no comparison of whether group-related differences in assignment decline after replacement. Remaining text and extracted features may still carry information related to identity or institutional setting. The reported operation establishes that names are actively removed where detected. Privacy protection and changes in [bias, fairness and safety](https://md.research.elamur.ai/free/en/topics/bias-fairness-safety/) require evidence that addresses those outcomes directly.

The explanation examples likewise establish a more specific result than end-user effectiveness. They show that the system can generate paths, feature-level information and verbal descriptions from a fitted classifier. The paper offers no study of whether practitioners using those descriptions find useful judgments faster, detect more errors or adjust their trust appropriately. An explanation can faithfully identify a feature test even when the corresponding assignment is legally unhelpful. The distinction matters because the classifier was trained to reproduce annotations from text patterns and extracted details. The court reached its decision using legal considerations that the classifier was never asked to reconstruct.

The confidence scores have a similarly defined scope. The paper obtains them by averaging tree-level predicted probabilities. This gives the forest’s assessment of its alternatives. The evaluation does not show whether judgments receiving a given confidence level are correct with a matching observed frequency. Classification accuracy, reader comprehension and probability calibration are distinct outcomes. The paper supplies classification results and examples of explanations. How those elements interact when a lawyer acts on the output remains open.

### What came after

#### Labeling the roles of passages

MARRO, published in 2025, cites the study and addresses rhetorical role labeling in legal documents using multi-headed attention. At the level of the stated tasks, there is a shift in what the label describes. The Spanish judgment classifier assigns areas of law to a whole judgment. Rhetorical role labeling concerns the function of portions of a legal document in the organization of its argument or account. The connection is visible in the Spanish system’s use of document structure. It already treats a decision section as a particular place to look for the court’s disposition. MARRO makes rhetorical organization the subject of the labeling task itself. The citation establishes a connection between the studies. It leaves open whether MARRO adopted any of the Spanish classifier’s extraction rules, legal taxonomy or explanation procedure. [MARRO](https://md.research.elamur.ai/free/en/papers/bambroo-2025-marro-multi-headed-attention-rhetorical/)

#### Verifying steps in judgment reasoning

LegalReasoner, also published in 2025, cites the study and addresses legal judgment reasoning through stepwise verification and correction. The two works direct inspection at different outputs. In the Spanish classification study, a decision path exposes the feature tests that routed a completed judgment to a proposed set of labels. In LegalReasoner, the stated focus is checking and correcting steps in legal judgment reasoning. A tree branch in the earlier system explains a decision about categorization, whereas a reasoning step in the later task forms part of the material being checked. The citation gives grounds to discuss their shared interest in making intermediate decisions open to inspection. It gives no evidence that LegalReasoner reused the Spanish judgment collection or evaluated its verification procedure with the earlier paper’s classification measures. [LegalReasoner](https://md.research.elamur.ai/free/en/papers/shi-2025-legalreasoner-step-wised-verification-correction/)

## Cite

Cite as Francisco de Arriba-Perez, Silvia Garcia-Mendez, Francisco J. Gonzalez-Castano and Jaime Gonzalez-Gonzalez. 2024. Explainable machine learning multi-label classification of Spanish legal judgements. arXiv:2405.17610.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.1016/j.jksuci.2022.10.015](https://doi.org/10.1016/j.jksuci.2022.10.015) · [arXiv 2405.17610](https://arxiv.org/abs/2405.17610)

```bibtex
@misc{arribaperez2024explainable,
  title = {{Explainable machine learning multi-label classification of Spanish legal judgements}},
  author = {Francisco {de Arriba-Perez}, Silvia Garcia-Mendez, Francisco J. Gonzalez-Castano and Jaime Gonzalez-Gonzalez},
  year = {2024},
  doi = {10.1016/j.jksuci.2022.10.015},
  eprint = {2405.17610},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.1016/j.jksuci.2022.10.015}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
