library(tidyverse)
library(tidytext)
library(Matrix)
library(glmnet)
set.seed(607)Automating IT Support: Classifying Help Desk Tickets Using Machine Learning
Introduction
Working in IT, I see different kinds of support tickets every day. Some employees cannot access an application, while others need help with their computers or software. Sorting these tickets by hand can take a lot of time. I chose this project to find out if machine learning can learn from old tickets and help sort new ones.
Research Question
Can machine learning correctly sort IT support tickets based on their descriptions? I will compare Naive Bayes and Logistic Regression to see which model works better and which types of tickets are harder to identify.
Load Libraries
I used R for the entire project. If any of the packages are missing, run install.packages(c("tidyverse", "tidytext", "Matrix", "glmnet", "knitr")) in the RStudio Console. The Naive Bayes model is built directly in R, so it does not need a separate package.
Data Acquisition
I chose the public Classification of IT Support Tickets dataset. It contains 2,229 tickets that were already sorted into seven categories. Personal information was anonymized. The tickets are written in several languages, mainly English, German, Portuguese and Spanish. The dataset already has separate training and testing files, which I kept separate.
base_url <- "https://zenodo.org/records/7384758/files/"
dir.create("ticket_data", showWarnings = FALSE)
read_ticket_file <- function(name) {
path <- file.path("ticket_data", name)
if (!file.exists(path)) {
download.file(paste0(base_url, name, "?download=1"),
path, mode = "wb", quiet = TRUE)
}
readr::read_csv(path, col_types = cols(.default = col_character()),
show_col_types = FALSE)
}
x_train <- read_ticket_file("X_train.csv")
y_train <- read_ticket_file("y_train.csv")
x_test <- read_ticket_file("X_test.csv")
y_test <- read_ticket_file("y_test.csv")
summary_data <- tibble(File = c("Training text", "Training labels", "Test text", "Test labels"),
Rows = c(nrow(x_train), nrow(y_train), nrow(x_test), nrow(y_test)))
knitr::kable(summary_data)| File | Rows |
|---|---|
| Training text | 1572 |
| Training labels | 1572 |
| Test text | 657 |
| Test labels | 657 |
Data Cleaning
The ticket descriptions and their categories are stored in separate files. I used the ticket IDs to match them correctly. I removed empty tickets, repeated description-category pairs, and test descriptions that also appeared in the training data. I kept training descriptions with different labels because the same issue may fit more than one category.
combine_tickets <- function(x, y) {
stopifnot("id" %in% names(x), "id" %in% names(y),
"category_truth" %in% names(y))
text_cols <- names(x)[!grepl("^(id|\\.\\.\\.[0-9]+|unnamed.*|index|row.names|rowid)$", names(x), ignore.case = TRUE)]
stopifnot(length(text_cols) == 1, !anyDuplicated(x$id),
!anyDuplicated(y$id), setequal(x$id, y$id))
tibble(id = x$id, text = x[[text_cols]]) |>
inner_join(tibble(id = y$id, category = y$category_truth), by = "id") |>
mutate(text = str_squish(str_to_lower(text)), category = str_squish(category)) |>
filter(!is.na(text), !is.na(category), text != "", category != "") |>
select(text, category)
}
train <- combine_tickets(x_train, y_train) |> distinct(text, category)
test <- combine_tickets(x_test, y_test) |> distinct(text, category)
test <- anti_join(test, distinct(train, text), by = "text")
stopifnot(nrow(train) > 0, nrow(test) > 0, all(test$category %in% train$category))
train <- mutate(train, id = row_number())
test <- mutate(test, id = row_number())
knitr::kable(tibble(Set = c("Training", "Testing"), Tickets = c(nrow(train), nrow(test))))| Set | Tickets |
|---|---|
| Training | 952 |
| Testing | 520 |
knitr::kable(count(train, category, sort = TRUE), caption = "Training category counts after cleaning")| category | n |
|---|---|
| Support general | 344 |
| Fileservice | 205 |
| Software | 128 |
| O365 | 125 |
| Active Directory | 83 |
| Computer-Services | 65 |
| EOL | 2 |
After cleaning, the training set went from 1572 to 952 tickets. The testing set went from 657 to 520 tickets. Removing repeated descriptions helps make the test fairer because the models should be tested on tickets they have not seen before. The downside is that fewer tickets are left for training and testing.
Exploratory Data Analysis
Before building the models, I wanted to see how many tickets belonged to each category. This helps me understand whether some categories have more examples than others.
train |> count(category, sort = TRUE) |>
ggplot(aes(x = reorder(category, n), y = n)) +
geom_col(fill = "steelblue") + coord_flip() +
labs(title = "Training tickets by category", x = NULL, y = "Number of tickets") +
theme_minimal()# Keep negation and technical terms. Use only a small multilingual stop list.
common_words <- c("the", "a", "an", "and", "to", "of", "is", "in", "for", "please", "hello",
"der", "die", "das", "und", "ein", "eine", "ist", "mit",
"de", "da", "do", "o", "a", "e", "em", "para", "um", "uma",
"el", "la", "los", "las", "y", "en", "un", "una", "por")
tokenize <- function(data) {
data |> select(id, text) |>
unnest_tokens(word, text) |>
filter(str_detect(word, "\\p{L}"), !word %in% common_words)
}
train_tokens <- tokenize(train)
train_tokens |> inner_join(select(train, id, category), by = "id") |>
count(category, word, sort = TRUE) |>
group_by(category) |> slice_max(n, n = 8, with_ties = FALSE) |> ungroup() |>
ggplot(aes(tidytext::reorder_within(word, n, category), n)) +
geom_col(fill = "steelblue") + coord_flip() +
tidytext::scale_x_reordered() + facet_wrap(~category, scales = "free_y") +
labs(title = "Common words by ticket category", x = NULL, y = "Count") + theme_minimal()Support general and Fileservice had the most training tickets. In comparison, EOL (End of Life) had only 2 training tickets and 0 test tickets. Without any EOL tickets in the test set, I cannot tell how well the models recognize that category. This is one reason why having enough examples in each category matters.
Text Preprocessing
The models need numbers instead of sentences. I made a list of words using only the training tickets. I kept words that appeared in at least two training tickets, up to 5,000 words. Naive Bayes uses word counts, while Logistic Regression uses TF-IDF, which gives more weight to words that are less common across tickets. I did not use the test tickets to build the word list or calculate the IDF weights.
vocab <- train_tokens |> distinct(id, word) |> count(word, sort = TRUE) |>
filter(n >= 2) |> slice_head(n = 5000) |> pull(word)
stopifnot(length(vocab) > 1)
make_matrix <- function(data) {
counts <- tokenize(data) |> filter(word %in% vocab) |> count(id, word)
Matrix::sparseMatrix(i = as.integer(counts$id), j = match(counts$word, vocab),
x = as.numeric(counts$n), dims = c(nrow(data), length(vocab)),
dimnames = list(NULL, vocab))
}
train_x <- make_matrix(train)
test_x <- make_matrix(test)
classes <- sort(unique(train$category))
train_y <- factor(train$category, levels = classes)
test_y <- factor(test$category, levels = classes)Model 1: Multinomial Naive Bayes
Naive Bayes looks at how likely certain words are to appear in each ticket category. It uses those patterns to predict a category for a new ticket. I used Laplace smoothing, which prevents a word from getting a probability of zero just because it was not seen in a particular category during training.
word_counts <- vapply(classes, function(cl) {
Matrix::colSums(train_x[train_y == cl, , drop = FALSE])
}, numeric(length(vocab)))
log_likelihood <- log(sweep(word_counts + 1, 2, colSums(word_counts + 1), "/"))
log_prior <- log(as.numeric(table(train_y)) / length(train_y))
predict_nb <- function(x) {
scores <- sweep(as.matrix(x %*% log_likelihood), 2, log_prior, "+")
classes[max.col(scores, ties.method = "first")]
}
nb_pred <- predict_nb(test_x)Model 2: Logistic Regression
I used multinomial Logistic Regression because there are more than two ticket categories. The model uses TF-IDF to help identify useful words. I also used ridge regularization to keep the model from relying too heavily on individual words. The model is fitted using a series of decreasing penalty values. I selected a penalty of 0.01 before looking at the test results and used it for all predictions.
idf <- log((1 + nrow(train_x)) / (1 + Matrix::colSums(train_x > 0))) + 1
as_tfidf <- function(x) {
out <- Matrix::Diagonal(x = 1 / pmax(Matrix::rowSums(x), 1)) %*% x %*%
Matrix::Diagonal(x = as.numeric(idf))
colnames(out) <- vocab
as(out, "CsparseMatrix")
}
train_tf <- as_tfidf(train_x)
test_tf <- as_tfidf(test_x)
stopifnot(nrow(train_tf) == length(train_y), ncol(train_tf) == length(vocab),
length(classes) >= 2, all(table(train_y) >= 2))
# Explicitly named class indicator matrix prevents ambiguous class dimensions.
y_matrix <- outer(as.character(train_y), classes, FUN = "==") * 1
colnames(y_matrix) <- classes
# Fit a decreasing penalty path, but use the preselected 0.01 for predictions.
logistic_model <- glmnet::glmnet(train_tf, y_matrix, family = "multinomial",
alpha = 0, lambda = c(1, 0.3, 0.1, 0.03, 0.01))
predict_lr <- function(x) {
as.character(predict(logistic_model, newx = as_tfidf(x),
s = 0.01, type = "class")[, 1])
}
lr_pred <- predict_lr(test_x)Model Evaluation
I used accuracy, precision, recall and F1 to compare the models. Accuracy tells me how many tickets were classified correctly overall. Precision tells me how often a predicted category was correct, while recall tells me how many actual tickets in a category were found. F1 combines precision and recall. I also included a simple baseline that predicts the most common training category for every test ticket.
evaluate <- function(actual, predicted, model) {
cm <- table(factor(actual, levels = classes), factor(predicted, levels = classes))
tp <- diag(cm)
precision <- tp / pmax(colSums(cm), 1)
recall <- tp / pmax(rowSums(cm), 1)
f1 <- ifelse(precision + recall == 0, 0, 2 * precision * recall / (precision + recall))
tibble(Model = model, Accuracy = sum(tp) / sum(cm),
Precision = mean(precision), Recall = mean(recall), F1 = mean(f1))
}
majority <- names(which.max(table(train_y)))
results <- bind_rows(
evaluate(test_y, rep(majority, length(test_y)), "Majority baseline"),
evaluate(test_y, nb_pred, "Naive Bayes"),
evaluate(test_y, lr_pred, "Logistic Regression")
)
knitr::kable(results, digits = 3)| Model | Accuracy | Precision | Recall | F1 |
|---|---|---|---|---|
| Majority baseline | 0.340 | 0.049 | 0.143 | 0.073 |
| Naive Bayes | 0.608 | 0.546 | 0.474 | 0.473 |
| Logistic Regression | 0.731 | 0.628 | 0.535 | 0.561 |
results |> pivot_longer(-Model, names_to = "Metric", values_to = "Score") |>
ggplot(aes(Metric, Score, fill = Model)) + geom_col(position = "dodge") +
scale_y_continuous(limits = c(0, 1), labels = scales::label_percent()) +
labs(title = "Model performance on held-out tickets", x = NULL, y = "Score") +
theme_minimal() + theme(legend.position = "bottom")I used macro averages to ensure that all seven categories were accounted for equally, regardless of how many tickets there were for each category. In the summary, I used zero where precision or recall could not be computed, including the recall for the EOL category. I did this because, in the test data set, there were no EOL tickets to classify. This decreases overall macro scores, but does not imply that the models made incorrect predictions about the EOL test tickets. The category table indicates recall as missing for the case when there are no real examples.
Confusion Matrices
confusion_data <- function(pred, model) {
as.data.frame(table(Actual = factor(test_y, levels = classes),
Predicted = factor(pred, levels = classes))) |>
mutate(Model = model)
}
cm <- bind_rows(confusion_data(nb_pred, "Naive Bayes"),
confusion_data(lr_pred, "Logistic Regression"))
ggplot(cm, aes(Predicted, Actual, fill = Freq)) + geom_tile(color = "white") +
geom_text(aes(label = Freq), size = 3) +
scale_fill_gradient(low = "white", high = "steelblue") + facet_wrap(~Model, ncol = 1) +
labs(title = "Confusion matrices", fill = "Tickets") + theme_minimal() +
theme(axis.text.x = element_text(angle = 35, hjust = 1))Performance by Category
per_class <- function(pred, model) {
m <- table(factor(test_y, levels = classes), factor(pred, levels = classes))
tibble(Model = model, Category = classes, Actual = rowSums(m),
Correct = diag(m), Recall = ifelse(rowSums(m) > 0, diag(m) / rowSums(m), NA_real_))
}
category_results <- bind_rows(per_class(nb_pred, "Naive Bayes"), per_class(lr_pred, "Logistic Regression"))
knitr::kable(category_results, digits = 3)| Model | Category | Actual | Correct | Recall |
|---|---|---|---|---|
| Naive Bayes | Active Directory | 43 | 13 | 0.302 |
| Naive Bayes | Computer-Services | 41 | 13 | 0.317 |
| Naive Bayes | EOL | 0 | 0 | NA |
| Naive Bayes | Fileservice | 114 | 93 | 0.816 |
| Naive Bayes | O365 | 87 | 78 | 0.897 |
| Naive Bayes | Software | 58 | 27 | 0.466 |
| Naive Bayes | Support general | 177 | 92 | 0.520 |
| Logistic Regression | Active Directory | 43 | 13 | 0.302 |
| Logistic Regression | Computer-Services | 41 | 20 | 0.488 |
| Logistic Regression | EOL | 0 | 0 | NA |
| Logistic Regression | Fileservice | 114 | 102 | 0.895 |
| Logistic Regression | O365 | 87 | 56 | 0.644 |
| Logistic Regression | Software | 58 | 30 | 0.517 |
| Logistic Regression | Support general | 177 | 159 | 0.898 |
best <- results |> filter(Model != "Majority baseline") |> arrange(desc(F1), desc(Accuracy)) |> slice_head(n = 1)Logistic Regression had the highest macro F1 score of 0.561 and correctly classified 73.1% of the test tickets. The charts and tables help show how the models compare with the baseline and which categories are harder to identify.
Predicting New IT Support Tickets
I created a series of support tickets based upon typical support tickets found in an IT work environment. Please understand that the following is made up, and none of these support tickets are actual ones that were submitted to our company helpdesk. The purpose of this was to see how the different models would handle daily problems. As the tickets have not been labeled with regard to the rules of the original dataset, they are just examples.
new_tickets <- tibble(text = c(
"I cannot access the shared network folder or file server.",
"Microsoft Outlook cannot send or receive emails in Office 365.",
"My Active Directory account is locked and I need a password reset.",
"I need help installing a software application on my computer.",
"My laptop will not start after the latest update.",
"Please help me replace an unsupported end of life application.",
"I need general assistance with an IT support request."
)) |> mutate(id = row_number())
new_x <- make_matrix(new_tickets)
new_results <- new_tickets |> transmute(Ticket = text,
`Naive Bayes` = predict_nb(new_x),
`Logistic Regression` = predict_lr(new_x),
`Recognized word count` = as.numeric(Matrix::rowSums(new_x)))
knitr::kable(new_results)| Ticket | Naive Bayes | Logistic Regression | Recognized word count |
|---|---|---|---|
| I cannot access the shared network folder or file server. | Fileservice | Fileservice | 9 |
| Microsoft Outlook cannot send or receive emails in Office 365. | O365 | O365 | 8 |
| My Active Directory account is locked and I need a password reset. | Active Directory | Software | 9 |
| I need help installing a software application on my computer. | Software | Support general | 7 |
| My laptop will not start after the latest update. | Computer-Services | Computer-Services | 5 |
| Please help me replace an unsupported end of life application. | Computer-Services | EOL | 5 |
| I need general assistance with an IT support request. | Software | Support general | 7 |
If a new ticket has no words from the training vocabulary, the model has very little useful information to work with. I would not rely on that prediction to route a ticket. I would also have someone review tickets when the two models disagree.
Limitations
One thing that poses a major problem here is the fact that the ticket contents are written in various languages. Even if we were able to remove a very limited list of generic words from the model, this still will not be sufficient in accounting for the entire range of languages that were present here. Some ticket categories have a very small amount of ticket texts, and many descriptions are either not very clear or refer to several issues at the same time.
It should be noted as well that this dataset belongs to one unique environment and thus cannot be generalized in another one. At the same time, these models look at each individual word separately, but do not recognize the way in which an experienced IT professional would understand the problems.
For Logistic Regression, I used a fixed penalty value. In the future, I would like to use cross-validation to test different values and see if the model performs better. I also used only the training tickets to create the vocabulary and calculate the TF-IDF weights to avoid using information from the testing data.
Adjustments to the Original Approach
Some of the R packages in my original plan did not work with my R setup, especially textrecipes. I switched to tidytext, Matrix, and other R functions to prepare the text and build the models.
Even though I changed some of the tools, I kept the same research question, dataset, two models, and evaluation methods. I was still able to finish the project entirely in R.
Conclusion
This project allowed me to look into how machine learning could assist in categorizing IT Support Tickets. In doing so, I found that Logistic Regression achieved 73.1% accuracy for the test tickets, which outperformed both Naive Bayes that achieved an accuracy of 60.8% and the Majority baseline which achieved 34.0% for the same set of tickets. Logistic Regression was also the model that achieved the best macro-F1 of 0.561. The two trained models outperformed simply guessing the most common category.
I was curious about how these models handled examples that closely resembled the kinds of problems I deal with professionally. While both models successfully classified “Shared Folder Request” under File Service and “Outlook Request” under O365, they had varying classifications for other tickets. In creating these examples of the kinds of problems I see and without access to labels of the examples I made up, I am not able to evaluate their classification ability in terms of accuracy, nor am I able to assess the performance of these
I was curious about how these models would handle examples that closely resembled the kinds of problems I deal with at work. Both models classified the shared folder request under Fileservice and the Outlook request under O365. However, their predictions were different for some of the other tickets. Since I created these examples myself and did not have official category labels, I could not measure the accuracy of these predictions.
References
- Pereira, L. S. B. (2022). Classification of IT Support Tickets (Version 1). Zenodo. https://doi.org/10.5281/zenodo.7384758
- Silge, J., & Robinson, D. Text Mining with R: A Tidy Approach. https://www.tidytextmining.com/
- Friedman, J., Hastie, T., & Tibshirani, R. (2010). Regularization paths for generalized linear models via coordinate descent. Journal of Statistical Software, 33(1). https://doi.org/10.18637/jss.v033.i01
- OpenAI. ChatGPT was used to help troubleshoot R code.