October 19, 2026
Classification of short texts using SVM and Naive Bayes
Classificação de Textos Curtos Utilizando Svm e Naive Bayes
Stephanie Costa Vale Moura; Douglas Augusto De Paula
DOI: 10.22167/2675-6528-202603463
Article derived from a Course Conclusion Work (TCC), with content based on the student’s original work and adapted to the editorial format of the E&S Magazine with the support of the ResumeAI tool, an artificial intelligence solution developed by Instituto Pecege for textual synthesis and organization.
Summary
The study developed and compared automatic text classification models, using Naive Bayes and Support Vector Machine (SVM) machine learning algorithms, to categorize brief purchase item texts according to their relationship with the company’s production process. Automatic text classification represented a challenge in Natural Language Processing (NLP), essential for analyzing large volumes of textual data in corporate environments. The methodology applied text preprocessing techniques, TF-IDF vectorization with removal of Portuguese stopwords, and hyperparameter optimization by GridSearchCV with cross-validation. The data were stratifiably divided into training (70%) and testing (30%) sets. The models were evaluated by accuracy, precision, recall, F1-score, and confusion matrix. SVM achieved the best overall performance, with an accuracy of 92.37%, an F1-score of 0.9236, and an AUC-ROC of 0.9862 on the test set, registering 78 errors in 1,022 documents. Naive Bayes achieved an accuracy of 91.39%, an F1-score of 0.9139, and an AUC-ROC of 0.9817, with 88 errors, exhibiting greater stability in cross-validation (±0.57% versus ±1.32% for SVM). Both algorithms surpassed the random baseline (50.00%). The results confirmed the applicability of the algorithms for the proposed task and the productivity gain from automating textual categorization in organizational contexts, reducing manual triage and improving tax compliance and cost management.
Keywords: Performance metrics; Hyperparameter optimization; Natural language processing; Cross-validation; Text vectorization.
1. Introduction
Automatic Text Classification (ATC), also known as document categorization, represents a challenging task in the field of Natural Language Processing (NLP), involving the assignment of texts to predefined categories based on their textual attributes (Cândido, 2020). In a comprehensive review of over 150 deep learning models, Minaee et al. (2021) highlighted that ATC has diverse applications, ranging from sentiment analysis and spam detection to news categorization and user intent classification. The relevance of ATC extends to corporate environments, where the analysis of large volumes of textual data is essential for decision-making.
In this context, text mining techniques have been widely applied in organizational and industrial domains to extract relevant patterns from unstructured texts, providing decision support (Nassirtoussi et al., 2014). Despite the growing sophistication of machine learning methods, classical approaches such as Naive Bayes and Support Vector Machine (SVM) maintain their relevance. Kumar (2022) systematized the main approaches in the field, highlighting the consolidation of classical techniques, especially under computational constraints. Kadhim (2019) confirmed that SVM and Naive Bayes remain competitive and widely adopted, particularly when interpretability and computational efficiency are priorities.
The present study used data from a company in the steel and industrial pipe manufacturing sector, focusing on the classification of brief descriptions of acquired products and services. Examples of these descriptions include “Industrial Water”, “Support and Technical Support Services”, and “Plate 38.00mm A-131-Gr.AH36”. The challenge lies in automatically categorizing these items regarding their relationship with the company’s operational productivity. The manual classification of these short texts is a time-consuming process and is susceptible to errors, which directly impacts the efficiency and reliability of operations.
Manual knowledge extraction becomes humanly impossible given the volume of textual data generated in corporate environments (Batista et al., 2018). Furthermore, textual sources within organizations, such as emails, reports, and operational descriptions, remain underexplored in the literature (Pejić Bach et al., 2019), highlighting a gap in the application of NLP techniques to optimize internal processes. The automation of textual categorization, therefore, offers a path to increase team productivity, reduce manual effort, and improve the standardization of analyses.
The correct identification of production-related purchase items has direct implications for the company’s production management, accounting, and taxation, influencing cost control, expense allocation, and the calculation of tax credits. Given this scenario, the justification for this study lies in the need to develop efficient and reliable solutions for classifying short texts. Thus, this work aimed to develop and compare automatic text classification models using the Naive Bayes and Support Vector Machine algorithms, applying preprocessing and Term Frequency-Inverse Document Frequency (TF-IDF) vectorization techniques, to categorize brief purchase item texts regarding their relationship with production — that is, whether the acquired item or service is directly linked to the company’s production (manufacturing) process —, evaluating the models’ performance through quantitative metrics and cross-validation.
2. Material and Methods
The research was characterized as an applied case study, with a quantitative and experimental approach, using supervised machine learning techniques for text classification. The study was conducted between 2025 and 2026, employing data from the purchasing database of a company in the steel and industrial pipe manufacturing sector. The dataset consisted of brief textual descriptions of products and services, previously classified according to their relationship with production. The data, stored in Excel format (.xlsx), contained the variables “Brief text” and “Relation to prod?”, the latter being a binary variable indicating the link with the production process.
For supervised training, the textual items were manually labeled by experts, according to the supervised learning approach (Batista et al., 2018). The database was organized to allow exploratory analysis and supervised modeling, following fundamental principles of data organization for machine learning tasks (Monard and Baranauskas, 2003).
The preprocessing of texts was crucial to transform raw data into a format suitable for machine learning algorithms (Batista et al., 2018). The steps included converting all texts to lowercase, Unicode normalization using the Normalization Form Compatibility Decomposition (NFKD) method followed by ASCII encoding, and the removal of accented characters. Missing or null texts were handled by assigning empty strings to avoid errors in subsequent processing.
Additionally, empty words, or “stopwords”, in Portuguese were removed, using the list provided by the Natural Language Toolkit (NLTK) library. “Stopwords” are high-frequency terms with low semantic value, and their elimination contributed to reducing the number of words to be analyzed, optimizing textual representation and model performance (Batista et al., 2018).
The textual descriptions were transformed into numerical representations through vectorization, an essential process for words to be consumed by machine learning models (Batista et al., 2018). The Term Frequency-Inverse Document Frequency (TF-IDF) technique was employed, a statistical metric that reflects the degree of importance of a word in a document within a collection. For the Naive Bayes model, vectorization was configured considering only unigrams. For the Support Vector Machine (SVM) model, configurations that included both unigrams and bigrams were tested, allowing the capture of relationships between adjacent word pairs (Batista et al., 2018).
The dataset was divided into training and testing subsets, following a 70% proportion for training and 30% for testing. This division was performed in a stratified manner, maintaining the original class proportion in both subsets, ensuring category representativeness. A fixed random seed (random_state=42) was used to ensure the reproducibility of the results, an essential practice in machine learning experiments (Monard and Baranauskas, 2003).
Two classic supervised learning algorithms were evaluated: Naive Bayes (NB) and Support Vector Machine (SVM). Hyperparameter optimization was conducted using the grid search method (GridSearchCV), which performed an exhaustive search over a predefined space of hyperparameter values, evaluating each combination through cross-validation to maximize model performance (Monard and Baranauskas, 2003).
For the Naive Bayes model, the `alpha` parameter (Laplace smoothing) was optimized, testing the values 0.01, 0.05, 0.1, 0.5, and 1. This parameter controlled the level of smoothing applied to probabilities, preventing issues related to zero probabilities for terms not observed in the training set (Batista et al., 2018). For the SVM model, two main hyperparameters were adjusted: `C` (regularization parameter), testing the values 0.01, 0.05, 0.1, 0.5, and 1, and `kernel`, testing the values ‘linear’ and ‘rbf’, which defined the transformation function used to map the data to higher dimensions (Batista et al., 2018; Cândido, 2020).
The models were trained using the labeled dataset and the K-fold cross-validation method with five partitions. This method evaluated the models’ generalization capability, reducing bias and providing a robust estimate of expected performance on unseen data (Batista et al., 2018; Monard and Baranauskas, 2003). Model performance evaluation used quantitative metrics, including accuracy, precision, recall, and F1-score (Batista et al., 2018; Cândido, 2020). Confusion matrices were generated to analyze classification hits and misses. Robustness tests were conducted by classifying new purchase items.
All analyses and implementations were performed in Python language, version 3.12.2. The libraries used included pandas for data manipulation, numpy for numerical operations, scikit-learn for machine learning algorithms and evaluation metrics, nltk for natural language processing, and matplotlib and seaborn for data visualization. The development environment used was Jupyter Notebook, which provided interactive execution and integrated documentation, facilitating research reproducibility.
3. Results and Discussion
This section details the research findings, interpreting them in light of the study problem and the proposed objectives, with a focus on the automatic classification of short texts from purchase items. The dataset used for training the models comprised 3,406 textual documents, equally balanced between the classes “Yes” (related to production) and “No” (not related to production), with 1,703 documents in each category. This balanced distribution was crucial to avoid biases and ensure that the models could effectively learn the characteristics of both classes, according to the guidelines of Monard and Baranauskas (2003).
The analyzed texts were brief descriptions, containing an average of 4.55 words and 28.23 characters per document, with a variation of one to twelve words. This data profile, characterized by conciseness, required rigorous textual preprocessing to optimize the representation and quality of information for the algorithms. The preprocessing steps included converting all texts to lowercase, Unicode NFKD normalization, ASCII encoding, and removing 207 Portuguese “stopwords,” which are high-frequency words with low semantic value. These techniques, according to Batista et al. (2018), are essential for standardizing data and reducing vocabulary dimensionality, improving the generalization capability of the models.
After preprocessing, the texts were vectorized using the Term Frequency-Inverse Document Frequency (TF-IDF) technique. This approach transformed the textual descriptions into numerical representations, reflecting the importance of each word in the document relative to the total collection. The removal of “stopwords” was particularly relevant, as it positively impacted recall values by eliminating terms that did not significantly contribute to the distinction between classes (Batista et al., 2018). The resulting TF-IDF matrix presented 4,643 features and a sparsity of 99.91%, indicating an efficient representation of textual data in a high-dimensional space.
The dataset was stratificately divided into 70% for training (2,384 documents) and 30% for testing (1,022 documents), ensuring that the original class proportion was maintained in both subsets. This stratified division, with a fixed random seed, ensured the reproducibility of the results and provided an independent test set for an unbiased evaluation of the models’ performance, aligning with good practices in machine learning (Monard and Baranauskas, 2003).
Naive Bayes model performance
The Multinomial Naive Bayes model was optimized through grid search (GridSearchCV) with five “folds” cross-validation, adjusting the `alpha` hyperparameter (Laplace smoothing). Values of `alpha` tested were 0.01, 0.05, 0.1, 0.5, and 1. The optimal value identified for `alpha` was 0.50, which resulted in the highest average accuracy in cross-validation, reaching 93.46%. This parameter is fundamental for Naive Bayes, as it avoids zero-probability issues for terms not observed in the training set, ensuring the algorithm can adequately handle new words (Batista et al., 2018).
The evaluation of the Naive Bayes model on the test set revealed an overall accuracy of 91.39%, with 88 incorrect classifications out of a total of 1,022 documents. Performance metrics per class demonstrated a good balance: for the “No” class, precision was 0.9325, recall was 0.8924, and F1-score was 0.9120; for the “Yes” class, precision was 0.8968, recall was 0.9354, and F1-score was 0.9157. The weighted average F1-score was 0.9139, indicating that the model maintained consistent performance in both categories, which is crucial for practical application in organizational contexts (Cândido, 2020).
The analysis of the confusion matrix in absolute values showed that, out of 511 actual documents of the “No” class, 456 were correctly predicted as “No”, while 55 were erroneously classified as “Yes”. For the “Yes” class, out of 511 actual documents, 478 were correctly identified as “Yes”, and 33 were incorrectly classified as “No”. In normalized terms, the model achieved 89.24% accuracy in predictions for the “No” class and 93.54% for the “Yes” class. These results indicate that the Naive Bayes model has a good capacity to correctly identify items related to production, with a relatively low false negative rate.
The Receiver Operating Characteristic (ROC) curve of the Naive Bayes model obtained an Area Under the Curve (AUC-ROC) of 0.9817, indicating an excellent discrimination capacity between classes. This value is significantly higher than the random baseline of 0.5000, representing a 96.33% improvement in the model’s discriminative capacity. The overall accuracy of Naive Bayes also surpassed the baseline by 82.78%, confirming the algorithm’s effectiveness for the proposed classification task, as observed in similar studies applying Naive Bayes for textual classification (Batista et al., 2018).
Five-fold cross-validation for Naive Bayes demonstrated an average accuracy of 93.46% with a standard deviation of ±0.57%. This low standard deviation suggests that the model is stable and robust, showing little variability in results across different partitions of the training set. The distribution of prediction confidence revealed that 41.29% of predictions were in the high confidence range (between 0.90 and 1.00), with an average confidence of 0.8216. Error analysis indicated 33 false negatives and 55 false positives, totaling 88 errors, which demonstrates the model’s ability to minimize misclassification of critical items.
Support Vector Machine model performance
The Support Vector Machine (SVM) model was trained and evaluated using the same dataset, preprocessing, and TF-IDF vectorization applied to Naive Bayes, ensuring comparability between the models. SVM hyperparameter optimization was performed by GridSearchCV with five-fold cross-validation, testing different values for the regularization parameter `C` (0.01, 0.05, 0.1, 0.5, and 1.0) and for the `kernel` type (‘linear’ and ‘rbf’). The optimal combination of hyperparameters was `C = 1.0` with `kernel = RBF`, which achieved an average accuracy of 93.33% in cross-validation, with a standard deviation of ±1.32%.
In the test set, the SVM model achieved an overall accuracy of 92.37%, slightly outperforming Naive Bayes and committing 78 classification errors on 1,022 documents, which represents ten fewer errors than Naive Bayes. The per-class performance metrics for SVM were: for the class “No”, precision of 0.9577, recall of 0.8865, and F1-score of 0.9207; for the class “Yes”, precision of 0.8944, recall of 0.9609, and F1-score of 0.9264. The weighted average F1-score was 0.9236, indicating robust and balanced overall performance between classes, as highlighted by Mathivanan et al. (2019) in studies of short text classification.
The SVM confusion matrix on the test set showed that, out of 511 actual documents in the “No” class, 453 were correctly predicted as “No”, while 58 were erroneously classified as “Yes”. For the “Yes” class, out of 511 actual documents, 491 were correctly identified as “Yes”, and 20 were incorrectly classified as “No”. In normalized terms, the model achieved 88.65% accuracy for the “No” class and 96.09% for the “Yes” class. The reduction in false negatives (20 for SVM versus 33 for Naive Bayes) indicates SVM’s greater ability to correctly identify production-related items, minimizing the risk of overlooking critical inputs.
The ROC curve of the SVM model presented an AUC-ROC of 0.9862, which is superior to the value obtained by Naive Bayes (0.9817), confirming the excellent discrimination capability of SVM between classes. This result represents a 97.24% improvement over the random baseline, reinforcing the effectiveness of SVM for the proposed task. The superiority of SVM in terms of AUC-ROC is consistent with the literature that points to this algorithm as one of the most stable and effective for textual classification, especially in high-dimensional spaces (Palanivinayagam et al., 2023).
The analysis of the SVM prediction confidence revealed that 79.84% of the classifications presented confidence above 0.90, with an average confidence of 0.9306 and a median of 0.9946. This high concentration of high-confidence predictions suggests that the SVM produces better-calibrated classifications, conferring greater certainty to the results. Although the standard deviation of accuracy in cross-validation (±1.32%) was slightly higher than that of Naive Bayes, the SVM demonstrated a superior ability to identify optimal separation patterns, using the maximum margin hyperplane, which contributes to its robustness in unseen data (Batista et al., 2018).
Comparison between models
The comparison between the Naive Bayes and SVM models revealed that both presented adequate performance for the automatic classification of brief texts, significantly outperforming the random baseline. However, SVM demonstrated a slight superiority in quantitative performance metrics on the test set. SVM’s accuracy was 92.37% against Naive Bayes’ 91.39%, representing a difference of 0.98%. Similarly, SVM’s AUC-ROC was 0.9862, superior to Naive Bayes’ 0.9817, with a difference of 0.45%.
This superiority of the SVM was reflected in the reduction of the total number of classification errors, with the SVM committing 78 errors in 1,022 documents, while Naive Bayes committed 88 errors. The analysis of error types showed that the SVM reduced false negatives more (20 versus 33 for Naive Bayes), which is particularly relevant in contexts where the identification of production-related items is critical. On the other hand, Naive Bayes presented fewer false positives (55 versus 58 for SVM), indicating a difference in the models’ sensitivity and specificity.
In terms of stability, Naive Bayes demonstrated greater consistency in cross-validation, with a standard deviation of ±0.57% in average accuracy, compared to ±1.32% for SVM. This suggests that Naive Bayes is less sensitive to variations in training data and may offer greater predictability. The confidence analysis of predictions also indicated that SVM produced better-calibrated predictions, with 79.84% of classifications above 0.90, while Naive Bayes had 41.29% in this range, which gives greater certainty to SVM’s classifications.
The choice between the models depends on the operational priorities of the application. If the main objective is to maximize overall accuracy and confidence in predictions, SVM is the recommended model, due to its superior performance in accuracy on the test set and higher concentration of high-confidence predictions. However, if the priority is predictability, stability, interpretability, and more efficient processing, Naive Bayes presents itself as a suitable choice, given its lower variance in cross-validation and lower computational cost, as discussed by Kadhim (2019).
In summary, the results confirm the viability of automatic text classification for categorizing purchase items, with both algorithms demonstrating high performance. The applied methodology, including text preprocessing, TF-IDF vectorization, and hyperparameter optimization, proved effective for structuring short textual data and supporting decision-making. The low error rates and high AUC-ROC and accuracy values in cross-validation highlight the models’ ability to reduce the need for manual review, increasing team productivity, improving analysis standardization, and enhancing fiscal compliance and cost management within the company.
4. Conclusion
The study aimed to develop and compare automatic text classification models using Naive Bayes and Support Vector Machine machine learning algorithms to categorize brief item descriptions according to their relationship with the company’s production process. Through rigorous textual preprocessing, TF-IDF vectorization, and hyperparameter optimization, it was found that both algorithms demonstrated high effectiveness in the proposed task. The Support Vector Machine model achieved slightly superior performance on the test set, with an accuracy of 92.37% and an AUC-ROC of 0.9862, registering 78 errors. In turn, Naive Bayes achieved an accuracy of 91.39% and an AUC-ROC of 0.9817, with 88 errors, exhibiting greater stability in cross-validation. These findings confirm the applicability of machine learning techniques for short text classification in corporate contexts, significantly outperforming the random baseline and offering a robust solution for automating textual categorization. The main contribution lies in the ability to increase team productivity, reduce manual effort, and improve analysis standardization, with direct implications for cost management, expense allocation, and tax credit calculation, optimizing tax compliance and production management.
Despite the quantitative superiority of SVM in accuracy and discriminative power, Naive Bayes demonstrated greater consistency and predictability in cross-validation, as well as lower computational cost. This distinction suggests that the choice of the ideal model depends on the operational priorities of the implementation, whether it is to maximize performance or prioritize stability and interpretability. For future studies, it is recommended to expand the research with new databases, explore more advanced textual representation techniques, and include additional algorithms, aiming to deepen the comparison and strengthen the applicability of the models in various organizational scenarios.
Bibliographic References
Batista, R.A.; Bagatini, D.D.S.; Frozza, R. 2018. Automatic classification of NCM codes using the Naïve Bayes algorithm. iSys: Revista Brasileira de Sistemas de Informação 11(2):
Cândido, E.C.R. 2020. Um Estudo Comparativo de Redes Neurais Profundas para Classificação Automática de Texto. Dissertação de Mestrado. Universidade Federal de Minas Gerais, Belo Horizonte, MG, Brasil.
Kadhim, A.I. 2019. Survey on supervised machine learning techniques for automatic text classification. Artificial Intelligence Review.
Kumar, S.N.P. 2022. Text classification: a comprehensive survey of methods, applications, and future directions. International Journal of Technology, Management and Humanities 8(3): 39-9.
Minaee, S.; Kalchbrenner, N.; Cambria, E.; Nikzad, N.; Chenaghlu, M.; Gao, J. 2021. Deep learning-based text classification: a comprehensive review. ACM Computing Surveys 54(3): 62.
Nassirtoussi, A.K.; Aghabozorgi, S.; Wah, T.Y.; Ngo, D.C.L. 2014. Text mining for market prediction: a systematic review. Expert Systems with Applications 41(16): 7653-7670.
Article originating from the Final Course Project of the Specialization in Data Science and Analytics of the MBA USP/Esalq
To learn more about the course, click here and access the MBX Academy platform