Abstract
Artificial intelligence (AI) is transforming numerous sectors, and its integration into the legal domain holds significant potential for automating labor-intensive tasks, enhancing judicial decision-making, and improving overall system efficiency. This study introduces an AI-powered model, named the Legal Judgment Prediction Ensemble (LJPE), which is designed to predict legal case outcomes by leveraging historical judicial data. By using natural language processing (NLP) techniques, feature engineering, and a complex two-level stacking ensemble, the LJPE model has better predictive accuracy at 94.68% compared to modern legal language and conventional machine learning models. Moreover, the findings underline the predictive strength of textual features obtained from case facts, vote margins, and legal-specific features. This study offers a solid technical solution for predicting legal judgments for the responsible use of the model, helping to create a more efficient, transparent, and fair legal system.
Keywords:
artificial intelligence; legal; prediction; machine learning; natural language processing; feature engineering MSC:
68T01; 68T50; 68T05; 68U15; 68U35
1. Introduction
The rapid advancement of technology has stimulated a significant transformation across society, with AI emerging as one of the most crucial technologies of our era. Its adoption in various fields, from complex industrial activities to daily operations, has presented novel efficiencies and capabilities, but it has also given rise to significant legal and ethical challenges [1,2]. The role that AI plays in the legal field is a unique blend of opportunity and risk. AI models take over the routine aspects of law by going through large sets of case reports to identify trends and through their ability to present data-driven inputs that in turn help in law-related decisions [3,4]. This increases efficiency, allows for better-quality decision-making, and reduces costs for clients. Moreover, this technique is put forth as a means to support legal authorities and human rights to timely and fair justice.
The potential benefits of AI in law are manifold and can be categorized as follows [5,6]:
- Increased Efficiency: AI systems conduct processes that were previously in the domain of legal professionals, like document review, research in case law, and analysis of contracts, but much more efficiently, which in turn allows lawyers to strategically put their skills to use, including counseling clients and presenting arguments in court.
- Enhanced Decision-Making: By using large sets of data from past cases, AI can present trends, past decisions, and relationships between variables, which may not be apparent to the human eye, to judges and lawyers. This in turn provides very consistent, fair, and data-driven decisions that can improve their practices.
- Cost Savings and Accessibility: The automation of law processes will considerably decrease the time and resources required, which in turn reduces legal fees for clients and possibly increases access to justice for underserved populations.
However, since law is a very sensitive and high-stakes field, AI cooperation is not without risk [7,8,9]. The use of AI systems raises several critical issues that must be addressed proactively, particularly for those that are based on machine learning.
- Bias and Transparency: AI models are trained on past data. If that data includes existing societal biases, such as those related to race, gender, or religion, the model in question may end up promoting and even increasing these biases, thus leading to discriminatory results. Additionally, many modern AI models function as black boxes, offering predictions without clear, understandable explanations, which is a big issue in legal situations that require the reason behind a given decision to be made clear.
- Privacy and Security: In many legal cases, there are issues related to dealing with very sensitive and private information. Enabling AI that processes and stores this information will raise critical issues of client privacy and security, which requires strong cyber security measures to be put in place, and data protection policies must be strictly followed.
- Accountability and Liability: A complex issue arises when determining the liability resulting from an AI model making an error leading to a negative outcome or causing harm. Legal and ethical debates discuss the implementation of clear frameworks for the accountability of AI decision systems.
- Resistance to Change: The legal field has long consisted of a very conservative and tradition-based community, which has been slow to adapt to changes. The introduction of disruptive technologies like AI models, which are very different from what was used before, is met with doubt and fear of large-scale impacts, thus leading to resistance from practitioners.
Previous research has highlighted the paradigm shift in the field of legal artificial intelligence from symbolic, rule-based schemes to data-driven machine learning methods [4]. Whereas studies have shown that AI can sometimes surpass human capability in specific predictive functions [10], an important challenge remains: the law itself has slowed down to adapt to the fast pace of AI development.
The main issue that this study considers is the balance between the requirement for a very accurate prediction tool that can automatically analyze past legal cases and a robust framework that will govern this usage. Manually reviewing past cases to develop a strategy is a time-intensive and often unproductive task. By using AI and NLP, we can put this automation into practice, thus helping us to bring out key themes in legal texts and predict results with high accuracy, which in turn gives legal professionals data-based insights.
The main contributions of this study can be summarized as follows:
- We develop, implement, and assess the LJPE, which is a novel two-level stacking ensemble model. The proposed LJPE combines various machine learning methods to obtain superior accuracy in predicting case outcomes.
- We present a comprehensive feature engineering approach mainly for the legal domain. This involves the extraction of features based on legal vocabulary, constitutional amendments, procedural functions, and a sentiment analysis of case facts, which are demonstrated to be significantly predictive of case results.
- We introduce a new, three-tier stacking strategy (Level 0 Base, Level 1 Meta, Level 2 Weighted) that specifically targets prediction instability. By empirically weighting the classifiers, rather than using a simple average, we demonstrate that our ensemble significantly reduces the high variance typically seen in single-model legal predictors.
- We introduce a solid data pre-processing pipeline, consisting of the handling of missing values and data type conversion, and apply advanced text cleaning methods including lemmatization and stopword removal for law texts.
The rest of this paper is constructed as follows: Section 2 analyzes literature reviews in the domains of AI and law. Section 3 provides a comprehensive description of the research methodology, including the dataset, data pre-processing, extensive feature engineering, and the structure of the proposed LJPE model. Section 4 presents and discusses the experimental results, including comparative performance analysis, feature importance, and a discussion of the findings. Finally, Section 5 concludes this paper, summarizing contributions and suggesting directions for future research.
2. Literature Review
AI and law have undergone extensive evolution over the past few decades. Early research was mainly conducted on symbolic AI, which helped develop expert systems and knowledge-based models for legal reasoning. As reported in [4,11], recently, we have seen a large shift toward machine learning and data-driven approaches, which has been brought about by the use of large digital collections of legal documents and by improved computational power.
2.1. Automatic Prediction of Court Decisions
The automatic prediction of legal decisions has become an important field of research in AI and law. This task typically entails training a machine learning model on the dataset for previous cases to predict the results of a new, unseen case. In [12], an important review of this domain is provided, and the results distinguish between outcome identification, outcome-based judgment classification, and true outcome prediction. This study emphasizes the need for careful evaluation to avoid challenges in function and prediction.
NLP has played an important role in this domain, as unstructured text is prevalent in most legal contexts. Many studies have shown the effects of NLP methods [13,14]. For example, the authors of [15] used machine learning and NLP to predict the decisions of the European Court of Human Rights (ECHR), and they obtained remarkably accurate results by analyzing the text content of cases. Similarly, ref. [16] employed NLP to predict the results in Turkish high courts, reported strong performance, and highlighted the ability of these techniques in different legal fields. As a specific application, Law-U, in [17], is an AI manual chatbot that provides legal guidance to victims of sexual violence by matching user input in relevant Supreme Court cases with high accuracy. These studies together confirm the opportunity to use NLP to extract future signals from legal texts.
The author of [18] investigates the obstacles in legal judgment prediction (LJP), including topology dependencies across sub-datasets of legal decisions and the lack of prior knowledge in sentence prediction based on the case description only. This research proposes a sequential PS-LJP model that integrates process supervision to ensure accuracy in processing sequential dependencies. The model uses convolutional neural networks to extract relevant textual features in the case description and applies Principal Component Analysis (PCA) to reduce dimensions. In addition, a genetic algorithm is also used to optimize the values of the model’s parameters and enhance the potential prediction performance.
The authors of [19] present a machine learning model called Legal Acumen, which employs a Support Vector Machine for the prediction of judicial decisions and K-Means Clustering for determining the punishments for criminal law, thus enabling the automatic regulation of court decisions, with particular reference to the Supreme Court of India.
In [20], automatically predicting court decisions involves algorithms assessing legally relevant factors, the metadata of the case, and textual descriptions to predict the outcomes of cases. However, this study concludes that predictors are only useful if their predictions are capable of being justified in a legally meaningful manner. Algorithms that learn from legally insignificant characteristics or derive systematic statistical correlations that are legally irrelevant may provide no meaningful value to judges and may lead to potentially consequential misleading conclusions or possibly undermine the reasoning and overall rationale of the judicial decision-making process.
The authors of [21] analyze a predictive model for the automated prediction of court rulings using a cascade classifier that integrates textual features from original documents in the first stage with metadata in the second stage. The goal of the predictive model is to enhance performance by improving consistency, out-of-sample applicability, generality, and explainability. The authors obtain good results using their model, and the results are better than those obtained using both a text-only and metadata-only baseline, which advances the argument that the integration of both data types is useful in automated predictions of administrative court rulings.
The authors of [22] present a full-process intelligent trial system (FITS) that incorporates a judgment predictor that uses a claim-aware representation of facts to yield the probability of support for a judgment. This is accomplished with a fully connected layer and sigmoid operation, allowing the model to predict judgments based on legal knowledge extracted from facts, formalized in first-order logic. The goal of the system is to help judges make better decisions by automating the prediction of court decisions during trials.
The author of [23] primarily tackles the problem of automatically predicting court outcomes through the analysis of decisions released in French from the European Court of Human Rights (ECtHR). Predicting the potential infringement of convention articles—by using extracted facts—presents a challenge. This study establishes different classification tasks for predicting court outcomes, comparing simple linear models with an attention-based neural network. Additionally, modifications to a partial least squares algorithm are made to accommodate the handling of sparse inputs sourced from natural language into the analyses, thus increasing the prediction accuracy of legal outcomes.
The authors of [24] propose a mathematical model of the law search process that is concerned with citation prediction in legal documents and the search results produced by individual users. They apply several adaptive algorithms to the U.S. Supreme Court’s opinions, thus revealing that the algorithms can improve upon a null model, specifically, for a learning-based algorithm. They identify a possibility that machine law search can operate at the level of human or near-human performance when predicting court decisions. Their findings suggest that textual similarity and citation networks are contributing factors in the law search process.
The authors of [25] discuss legal decision prediction, which aims to automatically predict judgment outcomes, including applicable law articles, charges, and penalty terms, according to the fact description of law cases. The authors highlight the associated challenges, such as indistinguishable fact descriptions and misleading articles of law, and propose a reinforcement learning-based framework called the Criminal Element Extraction Network (CEEN), which extracts discriminative criminal elements. Overall, this strategy enhances LJP accuracy by developing extractive, distinctive representatives corresponding to criminal elements, which improves the outcomes of LJP.
2.2. Baseline Models for Comparison
For a strict evaluation of the performance of the proposed model, this study compares it with several well-established machine learning algorithms that are commonly used as basic classification functions and some state-of-the-art legal language models. These models represent different approaches to classification and provide a solid goal for assessing the contributions from the more complex proposed ensemble technique.
The authors of [26] investigate the process of pre-training language models (LegalBERT and CaseLawBERT) on Indian legal data and apply them to legal NLP tasks, thus improving performance on both Indian and non-Indian datasets. In [27], Lawformer is a pre-trained language model that effectively understands long Chinese legal documents, improving various LegalAI tasks like judgment prediction, similar case retrieval, reading comprehension, and question answering.
- Logistic Regression: Logistic regression models are linear models used regularly for binary classification problems because they are very simple, interpretable, and computationally efficient. Logistic regression models a binary outcome with probabilities using a logistic function. This could be useful when predicting legal outcomes given that the model will find linear relationships between features (case facts, legal terms, etc.) and the final decisions [28].
- Support Vector Machines (SVMs): SVMs are powerful classification tools that define the optimal hyperplane that splits data points of different classes in a high-dimensional space. SVMs are effective in complex, non-linear spaces and have been used to rigorously define the classification of texts in many legal prediction tasks [19].
- K-Nearest Neighbors (KNN): KNN is a nonparametric, instance-based learning algorithm that classifies new samples based on the majority class decision of the nearest “k” neighbors in the feature space. KNN is a very easy algorithm to implement, but it is costly in terms of computational time, and it can also be very sensitive to the value of “k” and the distance metric. In the field of law, KNN could be utilized to classify the outcomes of cases based on previous legal decisions that had similar fact and context patterns [29].
Despite the advancements highlighted in Table 1, a critical gap remains in the current literature. Most existing solutions fall into two extremes: they either rely on simple machine learning models that miss textual nuance, or they utilize complex transformers that process text but ignore the structural logic of the law. Specifically, there is a lack of frameworks that combine deep semantic representations by using embeddings like standard NLP; explicit domain logic with engineered features like vote margins, legal term density, and constitutional amendment interactions; and ensemble stability with a hierarchical voting mechanism to reduce the variance found in single-model predictions.
Table 1.
A summary of the key literature and existing limitations.
The abovementioned gap is filled by this proposed LJPE framework, which not only considers the content in the text but also includes specific legal definitions and historical voting patterns, thus allowing for a far superior solution than that obtained when simply relying on raw text classification.
3. Methodology
The methodology employed in this study includes data collection and pre-processing, developing advanced feature engineering, and designing a new ensemble prediction model. The process is structured to promote technical robustness and predictive power for responsible AI use. The intended methodology workflow is illustrated in Figure 1. In addition, Figure 2 shows the main components of the proposed LJPE model for the law case prediction system.
Figure 1.
General methodology for law case prediction system.
Figure 2.
The main components of the proposed LJPE methodology.
3.1. Dataset Description
This study uses the “Prediction of Supreme Court Judgments” dataset, which can be accessed freely on Kaggle. This dataset has information on thousands of cases from the U.S. Supreme Court. The initial dataset contains 3303 records of cases, and each case consists of an individual event with 16 distinct features. The key features included in the dataset are as follows:
- Facts: A textual briefing of the facts of the case. This is what was utilized to create the proposed NLP feature extraction process.
- First party winner (class 1): The Boolean target variable (True/False) represents whether the first party won or lost the case.
- Issue area: The legal area the case falls into.
- Majority vote/minority vote: The number of justices that voted for the majority and minority opinions, respectively.
- Decision type/disposition: Categorical features that denote what type of opinion the court issued and the procedural disposition (e.g., majority opinion, reversed/remanded).
- Term: The court year for the case.
After the initial cleaning and dealing with missing values, we had a useable working dataset of 3288 complete cases.
3.2. Data Pre-Processing and Cleaning
A robust pre-processing pipeline was employed in the proposed implementation to set up the dataset for machine learning. This included multiple important steps:
- Dealing With Missing Values: Missing values were treated carefully. The issue area column has missing values that were filled in with “Unknown” to denote a separate category. For numerical columns such as term, facts, majority vote, and minority vote, missing values were filled in using the median of the relevant column to mitigate the effect of outliers and maintain the distribution.
- Data Type Conversion: The target variable first party winner originally contained True, False, and NaN values. This was then carefully converted into a binary integer (1 for True, 0 for False). Rows with inconvertible or missing target values were removed to improve the accuracy of the training dataset. Other columns like term were checked for and cleaned of year ranges (for instance, 1981–1982 was extracted to the year 1981) before being converted to a numeric type.
- Advanced Text Pre-processing: The facts column contained case summaries and was processed through an extensive NLP pre-processing pipeline via the NLTK approach. The proposed advanced pre-process text function wrapped the above pipeline and performed the following operations in turn on each case summary:HTML Tag Removal: This removed any remaining HTML tags from the text.Lowercasing: This converted all text to lowercase so that the words were consistent.Punctuation Removal: This stripped the casing of any punctuation marks so we could focus on the text.Tokenization: This broke the text down into chunks (for our purposes, words) (tokens).Stopword Removal: This removed common English stopwords (e.g., “the”, “a”, “is”) that do not contribute much semantically for prediction.Lemmatization: This applied the WordNet lemmatizer to reduce a word to its base or dictionary form (e.g., “arguing” to “argue”). This is useful for combining a word into one single feature, regardless of various forms (e.g., to make sure “argue”, “arguing”, and “argued” are all lumped together).
The output from this step was a cleaned text string (cleaned facts) for each case, which was ready to be used for feature extraction.
3.3. Feature Engineering
Feature engineering plays a significant role in this study, as it converts raw data to an extensive set of features that reflect the detailed aspects of law cases. We engineered a wide array of features, combining basic numerical calculations, NLP-driven metrics, and domain-specific legal indicators. The subsections below explain the feature engineering process we developed for this study.
3.3.1. Fundamental Vote-Based Features
- Vote Margin (): This denotes the difference between majority () and minority ( votes, which is computed as follows:
A wider margin often suggests a more definitive ruling.
- Vote Ratio (): This reflects the percentage of majority votes, as shown below:
This helps normalize the influence of each vote.
- Vote Unanimity (): This is a binary feature representing whether the decision was unanimous:
3.3.2. NLP and Sentiment Features
Using the pre-processed text and NLTK, sentiment analysis was conducted using VADER (Valence Aware Dictionary and sEntiment Reasoner) and Sentiment Intensity Analyzer (sid), and we were able to extract the following:
- Text Statistics: These consist of the sentence count, word count, and average sentence length. These can be substitutes for case complexity.
- Sentiment Score (): This is a single compound sentiment score ranging from −1 (most negative) to +1 (most positive) for the case facts. This attribute allows us to test the hypothesis that the tone of the case summary may correlate with outcomes. It is computed as follows:
- Sentiment Polarity (): This is a categorical feature derived from the sentiment score (1 for positive, −1 for negative, 0 for neutral) that is calculated as follows:
3.3.3. Domain-Specific Legal Features
This is the most significant phase we designed in the proposed methodology. We constructed features by looking at how many times different terms appeared in the case facts based on our pre-defined lists of legal terms:
- Legal Term Count (): Count of legal terms (e.g., “constitution”, “statute”, “precedent”, “plaintiff”), counted using a pre-defined lexicon of legal terms.
- Amendment Count (): Count of mentions of major U.S. constitutional amendments (e.g., “first”, “fourth”, “fourteenth”).
- Entity Count (): Count of legal entities (e.g., “supreme court”, “congress”, “department”).
- Action Count (): Count of verbs of legal action (e.g., “appealed”, “ruled”, “convicted”).
- Procedure Count (): Count of procedures (e.g., “motion”, “brief”, “discovery”).
- Rights Count (): Count of rights (e.g., “freedom”, “privacy”, “liberty”).
Subsequently, we derived density, complexity, and interaction features from the counts to capture more sophisticated relationships as follows:
- Density Features
Legal Term Density (): The percentage obtained from the legal term count () and the filtered word count ().
- Complexity Features
Average Sentence Length (): The average number of words per sentence.
where is word count, and is sentence count.
Case Complexity (): A composite metric of text length and the number of legal terms.
Legal Diversity (): The count of the total number of different legal concept categories.
Text Complexity (): A composite measure of the document structure.
- Interaction Features
Legal–Vote Interaction (): The interaction between legal terms and margin votes.
Amendment–Vote Interaction (): The interaction between amendment references and margin votes.
Complexity–Vote Interaction (): The interaction between case complexity and vote ratio.
3.3.4. Encoding Categorical Features
Categorical features like decision type, disposition, and issue area were converted into numerical features using one-hot encoding. For every category, one-hot encoding creates a new binary column to avoid any ordinal assumptions of the model.
3.4. Feature Selection and Extraction
We developed a feature selection and extraction process because it is critical to keep only the most informative features to maximize the performance of the model and limit overfitting when there are many engineered features.
- Feature Selection: We used mutual information to select the best features by using the following formula.
- 2.
- Text Feature Extraction: For our “cleaned facts” text, we used Term Frequency–Inverse Document Frequency (TF-IDF). TF-IDF transforms text into a matrix of numerical features, in which each feature corresponds to a word or n-gram, and the value indicates the significance of the feature within a specific document, compared to the entire corpus. We configured it to create the top 3000 features using n-grams of 1, 2, and 3 words. Term Frequency (TF): The frequency that a term appears in a document. Inverse Document Frequency (IDF): The rarity of a term across all documents.
- 3.
- Dimensionality Reduction: The final 3000-dimensional TF-IDF matrix was considered to be sparse and high-dimensional. To reduce complexity while capturing the most important latent semantic structures, we applied Singular Value Decomposition (SVD) to the document representations, building our own dimension in the text feature space to 50 components. The final feature vector for each case contained the 50 selected engineered features and the 50 SVD components from the text, which resulted in 100-dimensional inputs for our models.
3.5. Model Architecture: The Proposed LJPE Model
At the center of our proposed predictive methodology is the LJPE model. This model has been conceptualized as a complex, two-level ensemble model that uses the combined strengths of several heterogeneous machine learning algorithms to achieve the highest possible prediction accuracy. Ensembling serves to reduce variance, mitigate bias, and achieve more robust predictions.
3.5.1. Level 1: Stacking Classifier
The first level of the LJPE is a stacking ensemble. Stacking consists of training multiple base models and thereafter training a meta-model to create the final predictive model based on the outputs of the base models. The meta-model will learn how to optimally combine the outputs of the different algorithms in the ensemble. Our stacking classifier (Level 1) is made up of the following:
- (A)
- Base Estimators:
- (1)
- Logistic Regression: This estimates the probability of the target class from a logistic/sigmoid function.Equation (15) is used to estimate the probability that the output y = 1, given input features X (the probability of class 1):
- (2)
- Support Vector Classifier (SVC): This is a non-linear classifier with powerful performance in high-dimensional spaces. The SVC determines the optimal hyperplane that maximizes the margin between the classes. The SVC also uses a decision function for class prediction:whereXi: Training data points (support vectors are the only ones where αi > 0).yi ∈ {−1, +1}: Class labels for the training data.αi: The learned coefficient in the SVC.sign(⋅): The function that returns the class label: +1 if the inside part is positive and −1 if the inside part is negative.K(Xi,X): The kernel function (Radial Basis Function RBF) that is used to gauge the similarity or closeness between test point X and training point Xi, which is defined as follows:where γ > 0 is the kernel parameter that controls how wide or flexible the decision boundary is.
- (3)
- Extra Trees Classifier: This consists of the ensemble learning of decision trees and creates extra randomness in both the selection of features and splitting points to minimize variance. It first measures the Gini index, which indicates the overall impurity of nodes.
- (4)
- MLP Classifier: This is a perceptron with multiple layered inputs, and as a feedforward neural network, it is able to learn complicated non-linear relationships. It uses forward propagation, which runs the prediction through the layers (hidden and output) of the network as follows:
Finally, the classifier used Binary Cross-Entropy Loss to measure prediction error:
- (B)
- Final Estimator (Meta-Learner): The proposed method uses a logistic regression model as the meta-learner, which takes the prediction probabilities from the four base models as input and learns the optimal weights to combine them for the final prediction. Meta-model prediction merges base predictions as follows:
3.5.2. Level 2: Voting Classifier
The second level of the LJPE integrates the whole stacking classifier from Level 1 together with three other robust, independently tuned models and uses soft voting to make the final prediction. The final Voting Classifier consists of the following:
- (1)
- The Level 1 Stacked Classifier.
- (2)
- A second independently tuned Extra Trees Classifier configured differently for relevant predictors.
- (3)
- A second independently tuned MLP classifier configured differently for relevant predictors.
- (4)
- A fine-tuned SVC model.
With soft voting, the final prediction is the average among the predicted probabilities of each constituent model scaled by the weights assigned to each constituent model. We assigned weights of [4, 2, 2, 1]; therefore, the Level 1 stacking classifier was consistently the most robust predictor, so we assigned it a dominant weight of 4 to serve as the anchor for the final decision. The extra trees and MLP models were given a moderate influence of 2 to capture non-linear nuances that the stack might miss, while the SVC served a minor corrective role with a weight of 1. The hierarchical and weighted ensemble structure was purposely designed to result in a high degree of predictive accuracy while being robust against the inability of any single model to make the best use of the data. The weighted average was calculated as follows:
where W = ∑ is a normalization term used so that the weights can be summed correctly, and represents the weights for each model.
3.6. Evaluation Metrics
To analyze our models, we provided a defining set of classification metrics from the confusion matrix (True Positives (TPs), True Negatives (TNs), False Positives (FPs), False Negatives (FNs)). The data was split into an 80% training set and 20% testing set. These metrics were computed as follows:
- Accuracy: The proportion of correctly classified instances calculated.
- Precision: The proportion of positive predictions that were correctly calculated.
- Recall (Sensitivity): The proportion of actual positives that were correctly classified. This is reflected as follows:
- F1-Score: The harmonic mean of precision and recall, which produces a single score that balances both properties and is calculated as follows:
- AUC (Area Under the ROC Curve): The area under the Receiver Operating Characteristic curve, which plots the True Positive Rate against the False Positive Rate at multiple threshold settings. The AUC measures the model’s ability to separate classes, with 1.0 denoting a perfect classifier.
4. Results and Discussion
In this section, we provide the empirical results obtained from the experiments we performed. We assess the performance of our proposed LJPE model against the baseline models: LegalBERT, CaseLawBERT, Lawformer, logistic regression, Support Vector Machine (SVM), and K-Nearest Neighbors (KNN). Once the data was loaded, the dataset had 3303 entries and 16 columns. The first party winner column, which represents the target variable, originally had 2140 True values, 1148 False values, and 15 NaN values. Following the pre-processing steps explained in the methodology, the first party winner was converted into a binary integer (1 for winning, 0 for losing), and for the handling of missing values, the extracted, cleaned dataset for modeling had 3288 entries. The final target variable distribution consisted of 2140 instances for class 1 (first party winner) and 1148 instances for class 0 (first party loser), which indicates some class imbalance, as is commonly seen in real-world datasets. The analysis below utilizes the evaluation metrics defined in the Methodology Section and was performed on the 20% hold-out test set.
4.1. Experimental Setup
To ensure the full reproducibility of our results, in Table 2, we provide the hyperparameter settings used for all models in this study.
Table 2.
Configuration of hyperparameters.
4.2. Comparative Model Performance
The main goal of this study was to determine whether our proposed LJPE model would outperform standard machine learning methods. The overall accuracy and AUC performance are both summarized in Table 3 and depicted in Figure 3.
Table 3.
Summary of comparison of performance of all models on test set.
Figure 3.
Comparison of model performance based on accuracy (top) and AUC (bottom).
The results illustrate that the LJPE model clearly dominates both the more advanced, domain-specific language models and other traditional baseline systems. The LJPE model achieved an accuracy of 94.68% and an AUC of 96.49%, thus outperforming all the other models. The LJPE had very reliable and balanced performance, and consequently, it was the most optimal model because it produced strong discrimination between classes while also maintaining robustness against both False Positives and False Negatives, which is crucial in legal prediction, in which the cost of error can be high.
The performance of the three specialized pre-trained models (Legal BERT, Case Law BERT, and Lawformer) was notable in terms of how much better they were compared to the more traditional machine learning models. LegalBERT was the closest competitor to our proposed method, reaching an accuracy of 89.08% and an AUC of 89.64%. CaseLawBERT and Lawformer followed closely behind, with accuracies of 86.88% and 85.73%, respectively.
Although these models were specifically trained on legal data, they still did not perform as well as the LJPE model, falling short by 5% to 9%. This indicates that while raw linguistic understanding is powerful, it is not enough on its own. The superior performance of the LJPE demonstrates that our method used hierarchical ensemble architecture, in combination with specific feature engineering and a stacking technique, and captured distinctions in the case data that pure text embeddings might miss.
On the contrary, traditional baseline models struggled to keep up. Logistic regression was the only such model that had reasonable performance with an accuracy of 78.72% and AUC of 83.67%. On the other hand, the SVM model had poor performance with an accuracy of 61.70%. It achieved a perfect recall rate for class 1 but had 0 recall for the negative class (as seen in the confusion matrix below), which means that the model predicted every case as a win for the first party and failed to actually learn a meaningful separation between the classes. The KNN model had the same poor performance and had the lowest accuracy and AUC scores.
The success of the LJPE model can be attributed to its two-level stacking architecture. By leveraging the strengths of multiple base classifiers and refining them through a meta-learner, the model can correct the biases of individual algorithms. Furthermore, the inclusion of legal domain-specific features and interaction terms likely gave the model the context it needed to outperform the “black box” approach of the deep learning models. In short, while models like LegalBERT are powerful, the focused, structured approach of the LJPE proved to be the most effective strategy for the dataset specified in this study. The results from classification also demonstrate the strong performance of the proposed LJPE model, which had high precision, recall, and F1-scores for both classes, thus indicating that the model can correctly classify both winning and losing outcomes for the first party.
4.3. Analysis of ROC and Precision–Recall Curves
The ROC and precision–recall curves give a nuanced perspective on model performance across differing classification thresholds.
The ROC curves depicted in Figure 4 reveal that the LJPE model—shown in a red line—is located closest to the top-left corner of the graph. This is the ideal behavior for a classifier; it indicates that the model sustains a high True Positive Rate (TPR) while keeping the False Positive Rate (FPR) almost negligible. With an AUC of 0.965, the LJPE framework clearly distinguishes itself as the most capable system for discriminating between winning and losing case outcomes. CaseLawBERT, LegalBERT, and Lawformer cluster together, with AUC scores ranging from roughly 0.887 to 0.903. While these models are significantly more effective than the traditional logistic regression baseline (AUC = 0.837), they still lack the sharpness of the proposed ensemble method, showing a more gradual curve that implies a higher rate of false alarms to achieve the same sensitivity. On the contrary, the curves for the SVM and KNN remain dangerously close to the diagonal dashed line. Their low AUC scores (0.564 and 0.550, respectively) confirm that these algorithms failed to learn a meaningful separation boundary in this high-dimensional feature space.
Figure 4.
ROC curves for all models, showing the trade-off between the TPR and FPR.
The precision–recall curve in Figure 5 highlights the trade-offs involved in prediction confidence. In legal judgment prediction, in which the cost of a wrong prediction can be high, high precision is ideal even at high recall levels. The LJPE model dominates this space, maintaining a near flat trajectory across the top of the graph. This stability implies that the model can identify most winning cases (high recall) without being forced to make a lot of incorrect guesses (high precision). In contrast, the other models show a much greater drop-off. As we push models like LegalBERT or logistic regression to find more positive cases, their precision begins to waver significantly. The SVM and KNN models, once again, show immediate degradation, thus confirming their inability to handle the nuances of the dataset.
Figure 5.
Precision–recall curves for all models, showing the trade-off between precision and recall.
4.4. Confusion Matrix Analysis
Figure 6 includes confusion matrices with further details regarding the predictions: it shows the classification results obtained from the models, indicating the counts of the predictions for True Positives (TPs), True Negatives (TNs), False Positives (FPs), and False Negatives (FNs) for each class.
Figure 6.
Confusion matrices for proposed LJPE and other models.
The proposed LJPE model stands out immediately for its symmetry. Unlike the other models, it does not sacrifice one class to save the other. It correctly identified 237 losing cases (True Negatives) and 386 winning cases (True Positives), thus making it the only system to maintain high accuracy across both outcomes. Crucially, its error rates were minimal and balanced, with only 15 False Positives and 20 False Negatives. This balance is vital in a legal context, in which being unbiased is just as important as being correct.
An attractive and problematic pattern emerges when we look at the pre-trained language models (LegalBERT, CaseLawBERT, and Lawformer). At first glance, they seem effective because they catch nearly all winning cases (TPs ranging from 385 to 395). However, this comes at a steep cost: they are heavily biased toward class 1. For example, LegalBERT correctly identified only 80 negative cases while misclassifying 172 negative cases as wins (False Positives). CaseLawBERT and Lawformer followed suit, with similarly high False Positive counts of 166 and 178, respectively. This suggests that these models function almost as if they are very good at predicting a win but deeply struggle to recognize when a party will lose.
Among the traditional baselines, logistic regression handled the negative class better than the legal domain models, correctly identifying 157 True Negatives. However, it lacked the precision of the LJPE framework, thus resulting in 95 False Positives and a higher rate of missed wins (45 False Negatives). Finally, the SVM and KNN matrices visualize exactly why their performance metrics were so low. The SVM model completely collapsed into a majority class strategy; it predicted a “win” for every single case, resulting in 0 True Negatives and 252 False Positives. It did not learn to classify; it just learned that winning was statistically more likely. The KNN model was similarly unreliable, generating a chaotic mix of errors with 187 False Positives and 84 False Negatives, thus confirming that it could not find a clean decision boundary in the data.
In conclusion, the confusion matrices prove that the LJPE model’s superiority is not just related to obtaining a higher score, but it is also related to correctly understanding the difference between the two legal outcomes, which even the advanced pre-trained models struggled to achieve consistently.
4.5. Feature Importance Analysis
It is of critical importance to understand which features contribute to the predictions of the model for the purpose of interpretability and validation of feature engineering. In examining the effect of providing the feature importances for our LJPE model, we provide the following visualization of the top 20 feature importances in Figure 7.
Figure 7.
Top 20 most important features from the proposed LJPE model.
The feature importance analysis generated several findings that should align with the legal community:
- The Influence of Vote-Based Features: Vote-based features, “majority_vote”, “vote_margin”, and “vote_ratio”, were also highly ranked in importance. This suggests that the amount of unity among justices is a significant predictor of the result.
- Value is Added by Interaction Features: “legal_vote_interaction” being in the top 20 features implies that the link between legal term frequency and vote margin is a useful predictive indicator.
- Decision Type and Term: Decision_type_per curiam and term (the year of the Supreme Court term) also have moderate importance and indicate whether the decision is a per curiam opinion (meaning a decision rendered by the court as a whole, without identifying the individual justice who authored the opinion) and which term in history also matters to outcomes.
- Text-Based Features Matter: Several of the “text_feature_” aspects, which are latent semantic features derived from the case facts via SVD, appear among the top 20. This provides evidence that the proposed NLP pipeline is working correctly and that the text that makes up the case summary has predictive potential beyond the structured metadata.
The assessment of feature importance not only supports the validity of the proposed feature engineering methodology but also adds additional value to our findings for lawyers and practitioners about what elements of a case are the most predictive of its outcome. The importance of textual features validates that detailed fact narratives continue to be a key aspect of legal analysis.
4.6. Analysis of Model Robustness Validity
To ensure the reliability of our findings and address potential biases inherent in single train–test splits, we conducted a comprehensive cross-validation analysis. This validation provides a 95% confidence interval (CI) for each model, offering a rigorous measure of performance stability.
The results are summarized in the comparison in Table 4. When we look at the cross-validation data, the proposed LJPE model stands out for its consistency. It did not just perform well once; it held a mean accuracy of 95.78% across the folds, with a confidence interval staying tight between 0.9503 and 0.9653. We saw the same reliability in the AUC scores, which averaged at 0.9749 (95% CI: 0.9658–0.9840). This is significant because these numbers align almost perfectly with the standalone test set results (accuracy: 94.68%), thus confirming that the model is truly learning generalizable patterns rather than overfitting to a specific subset of the data.
Table 4.
Comparative analysis of model performance (cross-validation vs. test set).
The results for the pre-trained language models, however, tell a different story. If we had only looked at the test set, models like LegalBERT and CaseLawBERT seem like strong contenders, with accuracies in the high 80s. However, in the cross-validation analysis, their performance steeply declined, dropping to average accuracies of roughly 64% to 65%. These results can be attributed to variations in the model architecture and datasets; therefore, further research should be undertaken to analyze this factor in depth.
As for the traditional baselines, logistic regression was the only one with decent performance, maintaining a mean accuracy of 83.65% (CI: 0.8239–0.8491). While reliable, it still lagged significantly behind the proposed method. The SVM and KNN models confirmed their lack of suitability for this complex legal task, with KNN effectively performing at random chance levels (AUC of about 0.51) across the validated folds.
To conclude, the validation analysis confirms that the LJPE model provides not only the highest predictive power but also the greatest stability required for legal judgment prediction in this context.
4.7. Key Findings, Limitations, and Future Work
Based on the results and discussions above, the main findings of this study can be summarized as follows:
- The proposed LJPE model, which uses a two-level stacking ensemble with diverse base models and advanced feature engineering, outperforms individual models.
- Text features from case facts are highly predictive of case outcomes.
- The vote margin (difference between majority and minority votes) is an important feature.
- Different issue areas show different patterns in case outcomes.
- Legal domain features, such as constitutional amendment references, legal term density, entity mentions, and sentiment analysis, significantly improve prediction accuracy.
- Feature selection using mutual information helps in reducing noise and focusing on the most informative features.
- The two-level stacking approach with optimized weights creates a more robust and accurate ensemble.
Even though the proposed LJPE model demonstrates superior predictive performance, it is important to acknowledge specific constraints regarding its applicability and data scope:
- Domain Specificity: The LJPE model is trained specifically on U.S. Supreme Court cases and relies heavily on feature engineering tailored to American constitutional law, including specific amendments and legal terms.
- Case Summaries: The dataset used in this study depends on “case facts” rather than the full number of court documents. Whereas this method effectively captures the narrative logic of a case, it may miss deeper procedural nuances or technical legal arguments found only in detailed documents.
- Historical Bias and Legal Evolution: Similarly to all supervised learning models, the LJPE framework assumes that future judgment will follow historical patterns. However, the legal landscape is dynamic, and new regulations are continuously enacted. The model may struggle to predict outcomes in unique legal areas such as emerging AI regulations.
Although this study establishes a firm basis for future research, there are several promising opportunities to extend our work:
- Expanded Explainability: Instead of global feature importance, local, case-specific explanation techniques should be used like SHAP or LIME. Offering clear, human-understandable explanations for each prediction would vastly increase the model’s usefulness and trustworthiness for legal regulators.
- Global Datasets: The research scope should be expanded by considering different legal contexts, for example, ones with lower court decisions, international courts, or specific legal domains (patent law, corporate law, etc.). This will test the generalizability of the model and framework.
5. Conclusions
This study presented the dual task of creating a highly accurate AI model for legal judgment prediction while simultaneously creating a thorough architecture ensemble scheme. We developed the LJPE model, which is a novel two-level stacking ensemble model that uses more sophisticated natural language processing and domain-specific feature engineering to predict the outcomes of U.S. Supreme Court cases.
The primary contributions of this study lie in the domain-specific feature engineering and hierarchical architectural design tailored specifically for legal judgment prediction. Our methodology moves beyond standard application in three key ways. The first is feature interaction: We introduced specialized interaction features (e.g., Legal–Vote Interaction, Amendment–Vote Interaction) and complexity metrics that mathematically encode legal theory into the model. This transforms raw, unstructured text into high-dimensional, domain-aware inputs that standard models cannot generate on their own. The second is the hierarchical two-level architecture: Our ensemble method was designed with a custom Level 1 stacking structure followed by a Level 2 weighted soft voting mechanism. This specific architecture was engineered to balance the variance in non-linear deep learners (MLP) with the bias of linear classifiers (LR), optimizing them specifically for the nuances of legal language. Finally, the third is the hybrid input space: the integration of SVD-reduced TF-IDF vectors with our engineered legal features creates a robust hybrid input space.
The main outcomes of this study indicate that the proposed LJPE model achieved a top-tier accuracy of 94.68%, which is substantially better than that of conventional machine learning-based baselines. This high accuracy is likely due not only to the sophisticated ensemble model architecture but also to the proposed feature engineering approach that effectively assumes predictive signals from case metadata, voting history, and latent semantic content from legal texts. The feature importance analysis reaffirmed that the resolved procedural disposition and voting features were the strongest predictors and were consistent with legal domain knowledge.
Author Contributions
Conceptualization, A.M.S.S., Y.A., and A.O.E.; Methodology, A.M.S.S. and Y.A.; Software, A.M.S.S.; Validation, A.M.S.S., Y.A., and A.O.E.; Formal analysis, A.M.S.S., Y.A., and A.O.E.; Investigation, A.M.S.S. and A.O.E.; Resources, A.M.S.S.; Data curation, A.M.S.S. and Y.A.; Writing—original draft, A.M.S.S.; Writing—review and editing, Y.A. and A.O.E.; Visualization, A.M.S.S.; Project administration, A.M.S.S.; Funding acquisition, A.M.S.S. and Y.A. All authors have read and agreed to the published version of the manuscript.
Funding
This research was funded by Deanship of Research and Graduate Studies at the University of Tabuk grant number 2024-S-0124.
Data Availability Statement
The data presented in this study are openly available on Kaggle at https://www.kaggle.com/datasets/deepcontractor/supreme-court-judgment-prediction?resource=download, accessed on 3 April 2025.
Acknowledgments
The authors extend their appreciation to the Deanship of Research and Graduate Studies at the University of Tabuk for funding this work through Research no 2024-S-0124.
Conflicts of Interest
The authors declare no conflicts of interest.
References
- Kavak, M.; Rusu, L. Challenges and Opportunities of Artificial Intelligence in Digital Transformation: A Systematic Literature Review. Procedia Comput. Sci. 2025, 256, 369–377. [Google Scholar] [CrossRef] [Scilit]
- Aldoseri, A.; Al-Khalifa, K.N.; Hamouda, A.M. AI-Powered Innovation in Digital Transformation: Key Pillars and Industry Impact. Sustainability 2024, 16, 1790. [Google Scholar] [CrossRef] [Scilit]
- Sonali. Artificial Intelligence: Challenges, opportunities and its impact on society-2024 with respect to law and legal field. Int. J. Law Justice Jurisprud. 2024, 4, 238–247. [Google Scholar] [CrossRef] [Scilit]
- Villata, S.; Araszkiewicz, M.; Ashley, K.; Bench-Capon, T.; Branting, L.K.; Conrad, J.G.; Wyner, A. Thirty years of artificial intelligence and law: The third decade. Artif. Intell. Law 2022, 30, 561–591. [Google Scholar] [CrossRef] [Scilit]
- Kuppala, J.; Srinivas, K.K.; Anudeep, P.; Kumar, R.S.; Vardhini, P.A.H. Benefits of Artificial Intelligence in the Legal System and Law Enforcement. In Proceedings of the 2022 International Mobile and Embedded Technology Conference, MECON 2022, Noida, India, 10–11 March 2022; pp. 221–225. [Google Scholar] [CrossRef] [Scilit]
- Najafli, A. The Impact of Artificial Intelligence on the Legal System: Benefits, Risks, Legal, and Ethical Challenges. Acta Glob. Humanit. Linguarum 2025, 2, 247–263. [Google Scholar] [CrossRef] [Scilit]
- Zeleznikow, J. The benefits and dangers of using machine learning to support making legal predictions. Wiley Interdiscip. Rev. Data Min. Knowl. Discov. 2023, 13, e1505. [Google Scholar] [CrossRef] [Scilit]
- Rosengrün, S. Why AI is a Threat to the Rule of Law. Digit. Soc. 2022, 1, 1–15. [Google Scholar] [CrossRef] [Scilit]
- Ayinla, B.S.; Amoo, O.O.; Atadoga, A.; Abrahams, T.O.; Osasona, F.; Farayola, O.A. Ethical AI in practice: Balancing technological advancements with human values. Int. J. Sci. Res. Arch. 2024, 11, 1311–1326. [Google Scholar] [CrossRef] [Scilit]
- Hakim, H.A.; Praja, C.B.E.; Ming-Hsi, S. AI in law: Urgency of the implementation of artificial intelligence on law enforcement in Indonesia. J. Huk. Nov. 2023, 14, 122–134. [Google Scholar] [CrossRef] [Scilit]
- Paliwala, A. Rediscovering artificial intelligence and law: An inadequate jurisprudence? Int. Rev. Law Comput. Technol. 2016, 30, 107–114. [Google Scholar] [CrossRef] [Scilit]
- Medvedeva, M.; Wieling, M.; Vols, M. Rethinking the field of automatic prediction of court decisions. Artif. Intell. Law 2023, 31, 195–212. [Google Scholar] [CrossRef] [Scilit]
- Cui, J.; Shen, X.; Wen, S. A Survey on Legal Judgment Prediction: Datasets, Metrics, Models and Challenges. IEEE Access 2023, 11, 102050–102071. [Google Scholar] [CrossRef] [Scilit]
- Dina, N.Z.; Ravana, S.D.; Idris, N. Legal Judgment Prediction using Natural Language Processing and Machine Learning Methods: A Systematic Literature Review. Sage Open 2025, 15, 21582440251329663. [Google Scholar] [CrossRef] [Scilit]
- Medvedeva, M.; Vols, M.; Wieling, M. Using machine learning to predict decisions of the European Court of Human Rights. Artif. Intell. Law 2020, 28, 237–266. [Google Scholar] [CrossRef] [Scilit]
- Mumcuoğlu, E.; Öztürk, C.E.; Ozaktas, H.M.; Koç, A. Natural language processing in law: Prediction of outcomes in the higher courts of Turkey. Inf. Process. Manag. 2021, 58, 102684. [Google Scholar] [CrossRef] [Scilit]
- Socatiyanurak, V.; Klangpornkun, N.; Munthuli, A.; Phienphanich, P.; Kovudhikulrungsri, L.; Saksakulkunakorn, N.; Chairaungsri, P.; Tantibundhit, C. LAW-U: Legal Guidance through Artificial Intelligence Chatbot for Sexual Violence Victims and Survivors. IEEE Access 2021, 9, 131440–131461. [Google Scholar] [CrossRef] [Scilit]
- Shang, X. A Computational Intelligence Model for Legal Prediction and Decision Support. Comput. Intell. Neurosci. 2022, 2022, 5795189. [Google Scholar] [CrossRef] [Scilit]
- Rani, A.J.M.; Bharathwaj, K.S.; Swaroopan, N.M.J.; Kumar, K.H.; Geetha, R. A Legal Prediction Model Using Support Vector Machine and K-Means Clustering Algorithm for Predicting Judgements and Making Decisions. In Proceedings of the 2023 IEEE International Conference on Research Methodologies in Knowledge Management, Artificial Intelligence and Telecommunication Engineering, RMKMATE 2023, Chennai, India, 1–2 November 2023. [Google Scholar] [CrossRef] [Scilit]
- Bex, F.; Prakken, H. On the relevance of algorithmic decision predictors for judicial decision making. In Proceedings of the 18th International Conference on Artificial Intelligence and Law, ICAIL 2021, São Paulo, Brazil, 21–25 June 2021; pp. 175–179. [Google Scholar] [CrossRef] [Scilit]
- Mentzingen, H.; Antonio, N.; Lobo, V. Joining metadata and textual features to advise administrative courts decisions: A cascading classifier approach. Artif. Intell. Law 2024, 32, 201–230. [Google Scholar] [CrossRef] [Scilit]
- Wei, B.; Kuang, K.; Sun, C.; Feng, J.; Zhang, Y.; Zhu, X.; Zhou, J.; Zhai, Y.; Wu, F. A full-process intelligent trial system for smart court. Front. Inf. Technol. Electron. Eng. 2022, 23, 186–206. [Google Scholar] [CrossRef] [Scilit]
- Condevaux, C. Neural Legal Outcome Prediction with Partial Least Squares Compression. Stats 2020, 3, 396–411. [Google Scholar] [CrossRef] [Scilit]
- Dadgostari, F.; Guim, M.; Beling, P.A.; Livermore, M.A.; Rockmore, D.N. Modeling law search as prediction. Artif. Intell. Law 2021, 29, 3–34. [Google Scholar] [CrossRef] [Scilit]
- Lyu, Y.; Wang, Z.; Ren, Z.; Ren, P.; Chen, Z.; Liu, X.; Li, Y.; Li, H.; Song, H. Improving legal judgment prediction through reinforced criminal element extraction. Inf. Process. Manag. 2022, 59, 102780. [Google Scholar] [CrossRef] [Scilit]
- Paul, S.; Goyal, P.; Mandal, A.; Ghosh, S. Pre-trained Language Models for the Legal Domain: A Case Study on Indian Law. In Proceedings of the 19th International Conference on Artificial Intelligence and Law, ICAIL 2023—Proceedings of the Conference, Braga, Portugal, 19–23 June 2023; pp. 187–196. [Google Scholar] [CrossRef] [Scilit]
- Xiao, C.; Hu, X.; Liu, Z.; Tu, C.; Sun, M. Lawformer: A pre-trained language model for Chinese legal long documents. AI Open 2021, 2, 79–84. [Google Scholar] [CrossRef] [Scilit]
- Sil, R.; Sur, S.; Bhattacharya, S.; Bhushan, B.; Kumar, R.; Bhattacharya, P. Logistic Regression-Based Legal Prediction Model. In Proceedings of the Second International Conference on Intelligent System, Ho Chi Minh, Vietnam, 29–30 September 2023; pp. 323–331. [Google Scholar] [CrossRef] [Scilit]
- Bafna, P.; Thakur, H.K.; Singh, J.; Sadana, J.; Hassan, M.M.; Vani, M.S. An Intelligent Learning Approach to Case Analysis for Predicting Legal Outcomes Using Random Forest and K-Nearest Neighbors. In Proceedings of the 4th International Conference on Technological Advancements in Computational Sciences, ICTACS 2024, Tashkent, Uzbekistan, 13–15 November 2024; pp. 602–607. [Google Scholar] [CrossRef] [Scilit]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content. |
© 2026 by the authors. Licensee MDPI, Basel, Switzerland. This article is an open access article distributed under the terms and conditions of the Creative Commons Attribution (CC BY) license.






