Classical Out-of-Distribution Detection Methods Benchmark in Text Classification Tasks
Year: 2023

Abstract:
State-of-the-art models can perform well in controlled environments, but they often struggle when presented with out-of-distribution (OOD) examples, making OOD detection a critical component of NLP systems. In this paper, we focus on highlighting the limitations of existing approaches to OOD detection in NLP. Specifically, we evaluated eight OOD detection methods that are easily integrable into existing NLP systems and require no additional OOD data or model modifications. One of our contributions is providing a well-structured research environment that allows for full reproducibility of the results. Additionally, our analysis shows that existing OOD detection methods for NLP tasks are not yet sufficiently sensitive to capture all samples characterized by various types of distributional shifts. Particularly challenging testing scenarios arise in cases of background shift and randomly shuffled word order within in domain texts. This highlights the need for future work to develop more effective OOD detection approaches for the NLP problems, and our work provides a well-defined foundation for further research in this area.

heading: 1 Introduction
text: Systems based on artificial intelligence (AI) have to be safe and trustworthy (Amodei et al., 2016). Ensuring user reliance on these systems requires a cautious approach in making predictions. AI tools should avoid decisions on examples that significantly deviate from the training data. This is especially risky when the classifier shows excessive confidence in its incorrect decisions, leading to the propagation of errors in the system pipeline (Commission et al., 2019). However, current models are often trained under the closed-world assumption, limited to specific domains (Park et al., 2022). Test sets drawn from the same domain for evaluation may not reflect real-world scenarios accurately (Teney et al., 2020). This poses challenges
when deploying such models in production environments (Schrouff et al., 2022).
Real-world data is often completely different from training one. The change in data distribution can be caused by several factors such as user behavior, legal regulations, market trends or seasonal changes. In an open-world scenario, the AI-based system can be even exposed to inputs that deviate from the trained task. A significant risk that may arise is the possibility of model overconfidence while predicting data of this nature. As a result, there is a business need for detecting examples outside the domain (Hendrycks and Gimpel, 2017). Out-of-distribution (OOD) detection techniques can be well applied in a production system with human-in-the-loop technology (Wu et al., 2022), where it is important to quickly identify whether an input sample is characterized by a distributional shift. Such an example should be handled then by a human expert in order to avoid potential misclassification by the model. The essence of such systems is to find a trade-off between the accuracy and automation (Mosqueira-Rey et al., 2022) (Figure 1). This way, the model can achieve the highest possible performance on in-distribution (ID) data and difficult shifted data can be given to human verification, thus increasing the credibility of the overall system. The bottleneck here is a well-designed OOD detection method, which must be sensitive enough to capture all examples outside the domain.
119
The problem of OOD identification is mainly investigated for vision classification tasks (Yang et al., 2022a; Kuan and Mueller, 2022), whereas in the field of NLP, studies on this topic are limited. We fill the missing gap by proposing a comprehensive analysis of existing OOD approaches for text classification tasks. In this work, we focus on the post-hoc techniques which are most suitable for business applications i.e. they have to fulfil the requirement of smooth integration into existing systems, without the need for additional OOD training data or any changes in model architecture. Ultimately, we evaluated eight methods in two different scenarios. The first one includes grouping test data into three splits according to the similarity to the in-distribution set: Near-OOD, Far-OOD and Distinct-OOD (Yang et al., 2021). The AI system is evaluated based on the degree of domain difference between training and test samples. The second scenario considers the division of datasets according to the shift of distribution (Arora et al., 2021). There are many categories of distribution shift (Hupkes et al., 2022), but in this study, we consider two types – semantic and background. Semantic shift occurs when new labels appear, which may be due to the lack of a sufficient number of classes representing the training data or the emergence of new classes over time. In distinction, the background shift is class independent. It appears when the characteristic features of text change (e.g. source origin, writing style), which can happen even within the same class. The reason may be language evolution, regional conditions, etc. – such factors are difficult to predict and adequately address in the training set. By preparing data separated into different kinds of shift, we gain an in-depth insight into the origin of the data, on which a particular OOD detection method performs better or worse.
We also provide a well-structured research environment that allows the full reproducibility of the achieved outcomes and evaluation of another NLP models. The source code is available on GitHub1. To summarize, our contribution is as follows:
• we adjust the existing OOD detection techniques to the text classification problems, • we comprehensively evaluate the revised methods using two different scenarios tailored to the NLP domain, • we deliver the complete experimental framework for evaluating the OOD methods.
1https://github.com/mateuszbaransanok/TrustworthyAI

heading: 2 Related Work
text: In recent years, there has been a growing interest in developing robust methods that can detect outof-distribution examples. The work of Hendrycks and Gimpel (2017) has played a significant role in advancing this field. Their Maximum Softmax Probability (MSP) method, which relies on the softmax output of a neural network, has become a reference for subsequent research and still remains as the solid baseline approach (Zhang et al., 2023). The benefit of the MSP was its independence from the specific task domain. Since then, many researchers have extended this method or proposed novel techniques to address the challenge of detecting OOD data.
The first to popularize the interest in the OOD topic were computer vision (CV) researchers (Bengio et al., 2011). The emerged techniques in this field were summarized in a survey by Yang et al. (2021). The authors proposed a unified framework that groups OOD detection methods into categories based on their common underlying mechanisms. Among them, the following ones can be distinguished: (1) output-based (Liu et al., 2020; Liang et al., 2018) techniques which detect OOD samples based on output vector obtained by classification model for given input; (2) gradient-based (Huang et al., 2021) focus on analyzing the fluctuation of the gradient flow through the model layers to verify that the input is OOD; (3) density-based (Zong et al., 2018) methods involve modeling a density function from the training set and then determining whether a new example belongs to the same distribution; (4) distance-based (Sun et al., 2022; Ren et al., 2021) measure the dissimilarity between a new input and the training data by computing standard metrics such as cosine similarity, Euclidean or Mahalanobis distance. Another work of Yang et al. (2022a) provides a comprehensive evaluation of 13 methods for OOD detection in CV. Notably, the experimental results show that simple preprocessing techniques can be highly effective, outperforming even more sophisticated methods in identifying OOD examples. In addition, post-hoc methods have demonstrated considerable effectiveness in OOD detection and have made significant impact in this task. The NLP community is also more and more interested in addressing the challenge of OOD detection data, especially after the appearance of text processing automation systems. Despite the expectation that pre-trained language models (PLMs)
would generalize well to unseen data, many existing transformer-based architectures perform poorly in an open-world assumption setup. This was proven by the work (Yang et al., 2022b) where the authors created the GLUE-X benchmark to reliably test the robustness of PLMs against OOD samples exposure, without using any of the previously mentioned techniques dedicated to OOD. Their achieved results confirm the necessity of further development of OOD detection methods. Currently, researchers are continuously proposing techniques tailored for the NLP tasks (Rawat et al., 2021; Zhou et al., 2021), revisiting existing ones (Podolskiy et al., 2021) or designing completely novel approaches that can address specific shifts in data distribution (Arora et al., 2021; Chen et al., 2023). The latter two publications particularly highlight the importance of dividing datasets into semantic and background shift sets, as they provide valuable findings and a better understanding of how the model works on different data types.
Evidently, there have been several NLP articles addressing OOD detection, but their comparison to existing methods has been limited. A comprehensive study which evaluates various OOD detection approaches on a larger scale and addressing the specific needs of businesses is still lacking. To fill this gap, we have developed a benchmark that provides a fair comparison of these techniques while testing their performance across different distributional shift scenarios. All the selected methods have been inspired by CV achievements, and we have specifically chosen those that can be easily integrated into an existing AI system with minimal complexity.

heading: 3 Benchmark Outline
text: This section provides an overview of the datasets and the model architecture, with a detailed description of the techniques reimplemented in our benchmark for detecting out-of-domain examples. The metrics used for evaluating the effectiveness of the detection methods are also presented.

heading: 3.1 Datasets
text: News Category Dataset (Misra, 2022) is one of the biggest news dataset. It contains around 210k news headlines from HuffPost published between 2012 and 2022. The dataset comprises of 42 classes that are heavily imbalanced. Therefore, the most similar classes were combined to avoid confusion
between similar classes. Ultimately, we obtained 17 representative classes.
Twitter Topic Classification (Antypas et al., 2022) is a topic classification dataset collected from Twitter posts. It consists of 3184 high-quality tweets that have been assigned to one of six classes.
SST-2 (The Stanford Sentiment Treebank) (Socher et al., 2013) is a corpus with fully labeled parse trees that allows for an analysis of the compositional effects in language sentiment. The corpus includes almost 70k sentences extracted from movie reviews. Sentences were annotated with regard to their polarization (positive or negative).
IMDB (Maas et al., 2011) is a large collection of movie reviews from the Internet Movie Database created for the binary sentiment classification task. According to the original 10-point movie rating scale from the website, the dataset samples were filtered to include only highly polarized texts annotated as positive (≥ 7) or negative (≤ 4). Yelp Polarity Review (Zhang et al., 2015) dataset includes almost 600k customer reviews which are labeled as positive or negative based on the number of stars given by the reviewer. Specifically, texts with ≤ 2 stars are labeled as negative, while those with ≥ 3 are labeled as positive. Due to the large size of the dataset, we created a smaller version by randomly selecting a subset of 75k reviews.
Language Detection Dataset (Saji, 2021) is a small dataset for language detection task. It contains texts in 17 different languages. For benchmark purposes, we filter out languages that do not use Latin alphabet. We’ve also excluded English texts to create a clear out-of-distribution dataset. Finally, dataset consist around 6k samples and all of them are used for OOD evaluation.
20 Newsgroups (McGraw Hill, 1995) consists of around 18k newsgroups posts on 20 topics. It is divided in two sets for training and evaluation. Moreover, we allocated an additional subset from the training set for validation purposes.

heading: 3.2 Model
text: In all experiments, we used transformerbased (Vaswani et al., 2017) RoBERTabase (Liu et al., 2019) model as a backbone with a fully connected layer as a classification head. The model was pretrained on English corpora, but it supports multiple languages.

heading: 3.3 Methods
text: We decided to compare post-hoc methods that are suitable to apply to trained models. They mainly use information based on model statistics such as intermediate layer values, gradients or nondeterministic properties of dropout regularization, etc. Their implementation is technically straightforward and independent of the type of model used.
An overview of our benchmark methodology is outlined in Figure 2. In addition to label prediction, we obtain a real-valued confidence score that indicates the level of confidence that the model has in whether the given sample belongs to the ID data. We reimplemented eight OOD detection techniques and adapted them to the NLP classification pipeline.
(1) Maximum Softmax Probability (MSP) (Hendrycks and Gimpel, 2017) employs the softmax score to check the certainty of whether an example belongs to a domain – we refer to it as the baseline method in our work.
(2) Energy-based (Liu et al., 2020) uses an energy score function to indicate model confidence.
(3) Rectified Activations (ReAct) (Sun et al., 2021) is a simple technique for reducing model overconfidence on OOD examples by truncating the high activations during evaluation.
(4) KL-Matching (KLM) (Hendrycks et al., 2022) calculates the minimum KL-divergence between the softmax probabilities and the mean classconditional distributions.
(5) GradNorm (Huang et al., 2021) utilizes information obtained from the gradient space of model’s classification layer. This approach uses the vector norm of gradients to distinguish between ID and OOD samples, with the assumption that higher norm values correspond to in-distribution data.
(6) Directed Sparisification (DICE) (Sun and Li, 2022) selectively chooses a subset of weights through sparsification, which helps to eliminate irrelevant information from the output.
(7) Virtual-logit Matching (ViM) (Wang et al., 2022a) combines information from feature space (PLM embedding) and output logits, providing both class-agnostic and class-dependent knowledge simultaneously for better separation of OOD data.
(8) K-nearest neighbors (KNN) (Sun et al., 2022) computes the distance between the embedding of an input example and the embeddings of the training set, and uses it to determine whether the example belongs to the ID or not.
The first four methods use signals originating from the output layer of the model. GradNorm focuses solely on the gradients that flow through the classification head, while methods from 6 to 8 operate on the embedding of a PLM. Most techniques (specifically no. 3-4, 6-8) need an initial configuration on the training or validation set to estimate the required statistics for ID data. To ensure consistency in the benchmarking process, the hyperparameters for the above methods were set to the values recommended in their original papers.

heading: 3.4 Metrics
text: To compare the chosen methods, we used three the most common metrics for OOD detection. AUROC calculates the area under the Receiver Operating Characteristic (ROC) curve. The ROC curve plots the true positive rate against the false positive rate, and a larger area under the curve indicates better performance. This was used as our primary evaluation metric. AUPR-IN measures the area under the PrecisionRecall (PR) curve. The PR curve displays how well the method can identify true positives with high precision, and AUPR provides a measure of overall performance. The "IN" suffix indicates that this metric pertains to in-distribution data. FPR@95 is the false positive rate when the true positive rate is set to 95%. Lower scores indicate better performance.

heading: 4 Data Preparation
text: In our study, we have paid particular attention to provide a complete and unbiased comparison of OOD detection methods. To achieve this goal, we adopted two diverse perspectives: one inspired by the field of computer vision (Yang et al., 2022a) and the other drawn from works dedicated to the NLP domain (Rawat et al., 2021; Arora et al., 2021).

heading: 4.1 Scenario 1
text: The first perspective intends to provide a detailed analysis of considered techniques based on the similarity between OOD examples and the training set. The degree of similarity is defined here in a human-intuitive way, taking into account such factors as thematic proximity, task dissimilarity or the sentence correctness.
As a base in-distribution data, we chose News Category dataset using the seven most popular classes (NC/I). The remaining classes were considered as out-of-distribution split (NC/O) which represents data in close semantic shift. The Twitter Topic Classification dataset has categories that are similar to those in the News Category dataset, but the sentence construction is significantly different. Both sets create the Near-OOD data setup. Another prepared collection, Far-OOD includes datasets with reviews of movies, hotels and restaurants that are vastly different from NC/I data – it is a connection of SST-2, Yelp and IMDB. Additionally, we prepared one more group named Distinct-OOD containing Language Detection dataset. With the inclusion of non-English texts there, we obtain a distinct set of tokens that the RoBERTa model has not encountered before, creating a completely separate dataset from the in-distribution data.
Finally, we also designed two collections derived from the News Category dataset by randomly shuf-
fling words from all those available within each category. The new dataset, called News Category Random, retained the original number of examples and the number of words in each sample. These sets aimed to examine the classification system behavior when presented with input sentences that are completely disrupted from their original context. The previous partition into ID (NCR/I) and OOD (NCR/O) subsets was maintained.

heading: 4.2 Scenario 2
text: This scenario investigated the performance of detection methods for OOD examples under semantic and background shift. For semantic shift, we utilized the 20 Newsgroups dataset that is a hierarchical collection of documents. Among the four top-level categories, we selected three - Computer, Sports, and Politics - as training sets for the model, while excluding the "misc" category due to potential data leakage issues. Subsequently, we generated various combinations of these categories, treating each one in turn as an in-distribution set, while considering the others as a OOD data. For example, the model could be trained on the samples from Computer class (ID dataset) and evaluated later on Sports and Politics (OOD).
In order to test the impact of background shift, we took three sentiment classification datasets – IMDB, SST-2 and Yelp, which are based on user reviews and represent different domains. Although these datasets have similar linguistic properties, the topics they address are distinct. Again, we constructed various combinations of these collections by treating each one as the ID set and the others as OOD sets.

heading: 5 Experiments
text: In this section, we describe the details of a training procedure and present the outcomes from the experiments.

heading: 5.1 Training Setup
text: The PLM fine-tuning duration took maximally 100 epochs with an early stopping mechanism (Raskutti et al., 2011) applied (patience = 10 epochs). By using this technique, we were able to conserve computational resources while still obtaining highperforming models. The learning rate hyperparameter was always set to 2e−5. To prevent overfitting and enhance the model’s generalization capabilities, we used a weight decay wd = 0.01 with
Adam optimizer (Zhang, 2018). The best performing model was selected based on F1-score achieved on the validation set, and the final results were reported on the test set (see Appendix A). To minimize the influence of randomness on the outcomes, we trained PLM five times for each task using different initial seeds.
During each experiment, the PLM was finetuned on ID data, which consisted of training and validation splits. The evaluation of the OOD detection methods themselves was performed on predefined test data. A complete overview of the split sizes along with the number of classes in all data collections is presented in Table 1.

heading: 5.2 Results
text: The outcomes from experiments on data prepared in the first scenario (Section 4.1) are shown in Table 2. The KNN clearly outperformed the other OOD detection techniques on all three data groups. Energy-based method also stands out with its good results as well as ViM, except with its results on IMDB and Yelp dataset (worse than baseline MSP). As expected, the values of evaluation metrics on the NC/O dataset were the lowest among Near-OOD and Far-OOD divisions. This dataset was separated from the original dataset used in the training, making it the most difficult to properly identify as OOD due to the distributional closeness. The most challenging among the Far-OOD collections appeared to be SST-2, probably because of a small average number of words per example. The Language turned out to be the easiest dataset to detect OOD samples, and almost all methods performed well on it. The two worst performing approaches on the presented NLP tasks can be distinguished, i.e. DICE and KLM. Their measures were always
worse than MSP, sometimes even nearly random (a little above 50%) – DICE on NC/O and KLM on Twitter.
Interesting results can be seen in the last part of Table 2. Randomization of words in case of NC/O dataset (which created NCR/O) significantly increased the model confidence in detecting OOD examples comparing with initial NC/O samples. However, the OOD methods could not cope well with shuffled in-domain News category data (NCR/I), which a human would recognize as the OOD.
Table 3 presents AUROC scores obtained from the second scenario (Section 4.2) evaluation. The results demonstrate that the ViM method is more effective in detecting OOD samples with semantic shift to ID data. However, for background shift data, ViM is not always the best and is outperformed by KNN on IMDB and Yelp datasets. The SST-2 dataset proved to be problematic again, but
only when used as a training set. It is worth noting that the average length of texts per SST-2 is considerably different from IMDB and Yelp collections, which mainly contain longer texts. These observations suggest that KNN is more stable in terms of different data characteristics. To further emphasize the importance of comparing methods based on the type of shift, we created a visualization in Figure 3. The ReAct, Energy, and GradNorm techniques turned out to be better than the baseline, but only for the semantic shift case.
To summarize, either KNN or ViM is the preferred choice among all the analyzed OOD detection approaches. Other reported metric values (AUPR-IN and FPR@95) from all experiments are attached in Appendix B.

heading: 5.3 Computational Resources
text: All experiments were conducted on a workstation equipped with a mid-range Nvidia RTX 3060 GPU with 12GB of memory, a high-end Intel(R) Core(TM) i9-10900X CPU with 20 cores and 40 threads, and 256 GB RAM. These resources provided sufficient capacity for running the experiments and training the models used in this work, including analysis and processing of large datasets. In total, we trained 35 models, taking 222 GPUhours while evaluation alone lasted 124 GPUhours.

heading: 6 Conclusions
text: The latest advancements in OOD detection techniques have surpassed the conventional MSP baseline. In this work, we applied some of them to the
NLP classification problems, selecting only posthoc approaches because of their easy integration to already trained PLM model. Most of the examined techniques achieved better results than the MSP, but their performance varied when subjected to different types of data distributional shift. Background shift was particularly challenging for the majority of methods to properly distinguish OOD examples. The KNN and ViM methods were found to be the most effective, and their performance was also stable. Hence, they are better alternatives to MSP for out-of-distribution detection. However, it should be kept in mind that it is likely that the ViM method is sensitive to cases where the language model was trained on short texts and later exposed to a long text from outside the domain.
The proposed by us the unique analysis of Distinct-OOD scenario, allowed to draw interesting findings. The tested methods were able to identify texts in different languages very easily as a OOD examples, but they had problems detecting OOD on the News Category Random with shuffled data. This means that PLM models, despite their ability to detect contextual nuances in text, still tends to behave like Bag-of-Words (Zhang et al., 2010) in text classification tasks. Business-wise, such structurally disturbed examples should not be further processed by AI systems. Therefore, OOD methods employed in NLP should better address semantic disorders in input sentences.
In conclusion, the overall performance of current OOD detection techniques is still low and unsatisfactory, particularly when presented with the Near-OOD samples. Further research is necessary for the development of OOD detection methods, es-
pecially in the field of NLP, where more and more document processing automation systems are being developed, where ensuring reliability is important for users. Our work addresses the need for a comprehensive framework to evaluate the quality of OOD detection and provides easy extensibility to emerging methods.

heading: 7 Limitations
text: While our study provides valuable insights, it is important to keep in mind its limitations. Firstly, it was confined to text classification and did not include other NLP problems such as Named Entity Recognition (NER) (Wang et al., 2022b), Question Answering (QA) (Pandya and Bhatt, 2021), etc. Expanding this research to a wider range of tasks would provide a better understanding of the methods’ performance in diverse data scenarios. Additionally, the inclusion of a task shift can be valuable, where the model is trained on a single task but OOD data come from a totally different prediction problems.
Secondly, we conducted our experiments using only RoBERTa model. We chose a widely used language model for text classification, but there are several other architectures worth testing, especially large language models (LLMs) (Zhao et al., 2023) that now becoming extremely popular. A more comprehensive evaluation of the models and methods could provide more insights into whether the development of transformer-based methods contributes to better detection of OOD data.
Finally, due to restricted computational time, we did not perform a hyperparameter search for either model or methods. We just used recommend values from the original publications. This may have affected the obtained results, and it is certainly an aspect worth investigating in the future.

heading: 8 Ethics Statement
text: The authors believe that their work does not raise any ethical questions of harm or discrimination. Moreover, they acknowledge that the benchmark has a wide range of potential applications and want to make it clear that they are not responsible for any unethical applications of their work.

heading: Acknowledgements
text: The research was conducted under the Implementation Doctorate programme of Polish Ministry of Science and Higher Education
(DWD/6/0322/2022) with cooperation of the Artificial Intelligence Department at Wroclaw University of Science and Technology. It was partially co-funded by the European Regional Development Fund within the Priority Axis 1 “Enterprises and innovation”, Measure 1.2. “Innovative enterprises, sub-measure 1.2.1. “Innovative enterprises – horizontal competition” as part of ROP WD 2014-2020, support contract no. RPDS.01.02.01-02-0063/2000. The work conducted by Maciej Zieba was supported by the National Centre of Science (Poland) Grant No. 2021/43/B/ST6/02853.

heading: A Training Details
text: Each model was trained on five different seeds from range [2021, 2025]. Table 4 includes averaged classification metrics with standard deviation.

heading: B Evaluation Details
text: The values for all metrics that were considered in our experiments are listed below. Tables 5 and 6 refer to the Scenario 1 of OOD data preparation; Tables 7 and 8 report the results from the Scenario 2.

heading: Future Work
text: This may have affected the obtained results, and it is certainly an aspect worth investigating in the future