---
title: "text-embedding"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{text-embedding}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  message = FALSE,
  fig.path = "figures/",
  comment = "#>"
)
options(tidyverse.quiet = TRUE)
options(rollama_verbose = TRUE)
```

Ollama, and hence `rollama`, can be used for text embedding.
In short, text embedding uses the knowledge of the meaning of words inferred from the context that is saved in a large language model through its training to turn text into meaningful vectors of numbers.
This technique is a powerful preprocessing step for supervised machine learning and often increases the performance of a classification model substantially.
Compared to using `rollama` directly for classification, the advantage is that converting text into embeddings and then using these embeddings for classification is usually faster and more resource efficient -- especially if you re-use embeddings for multiple tasks.

```{r}
library(rollama)
library(tidyverse)
```

```{r}
reviews_df <- read_csv("https://raw.githubusercontent.com/AFAgarap/ecommerce-reviews-analysis/master/Womens%20Clothing%20E-Commerce%20Reviews.csv",
                       show_col_types = FALSE)
glimpse(reviews_df)
```

Now this is a rather big dataset, and I don't want to stress my GPU too much, so I only select the first 500 reviews for embedding.
I also process the data slightly by combining the title and review text into a single column and turning the rating into a binary variable:

```{r processing}
reviews <- reviews_df |>
  slice_head(n = 500) |>
  rename(id = ...1) |>
  mutate(rating = factor(Rating == 5, c(TRUE, FALSE), c("5", "<5"))) |>
  mutate(full_text = paste0(ifelse(is.na(Title), "", Title), `Review Text`))
```

To turn one or multiple texts into embeddings, you can simply use `embed_text`:

```{r embeddingsmal, message=TRUE}
embed_text(text = reviews$full_text[1:3])
```

To use this on the sample of reviews, I put the embeddings into a new column, before unnesting the resulting data.frame.
The reason behind this is that I want to make sure the embeddings belong to the correct review ID.
I also use a different model this time: [`nomic-embed-text`](https://ollama.com/library/nomic-embed-text).
While models like `llama3.1` are extremely powerful at handling conversations and natural language requests, they are also computationally intensive, and hence relatively slow.
As of version 0.1.26, Ollama support using dedicated embedding models, which can perform the task a lot faster and with fewer resources.
Download the model with `pull_model("nomic-embed-text")` then we can run:

```{r embedding, message=TRUE}
reviews_embeddings <- reviews |>
  mutate(embeddings = embed_text(text = full_text, model = "nomic-embed-text")) |>
  select(id, rating, embeddings) |>
  unnest_wider(embeddings)
```

The resulting data.frame contains the ID and rating along the 768 embedding dimensions:

```{r}
reviews_embeddings
```

As said above, these embeddings are often used in supervised machine learning.
I use part of [a blog post by Emil Hvitfeldt](https://emilhvitfeldt.com/post/textrecipes-series-pretrained-word-embeddings/) show how this can be done using the data we embedded above in the powerful `tidymodels` collection of packages:

```{r smldemo}
library(tidymodels)
# split data into training an test set (for validation)
set.seed(1)
reviews_split <- initial_split(reviews_embeddings)

reviews_train <- training(reviews_split)

# set up the model we want to use
lasso_spec <- logistic_reg(penalty = tune(), mixture = 1) |>
  set_engine("glmnet")

# we specify that we want to do some hyperparameter tuning and bootstrapping
param_grid <- grid_regular(penalty(), levels = 50)
reviews_boot <- bootstraps(reviews_train, times = 10)

# and we define the model. Here we use the embeddings to predict the rating
rec_spec <- recipe(rating ~ ., data = select(reviews_train, -id))

# bringing this together in a workflow
wf_fh <- workflow() |>
  add_recipe(rec_spec) |>
  add_model(lasso_spec)

# now we do the tuning
set.seed(42)
lasso_grid <- tune_grid(
  wf_fh,
  resamples = reviews_boot,
  grid = param_grid
)

# select the best model
wf_fh_final <- wf_fh |>
  finalize_workflow(parameters = select_best(lasso_grid, metric = "roc_auc"))

# and train a new model + predict the classes for the test set
final_res <- last_fit(wf_fh_final, reviews_split)

# we extract these predictions
final_pred <- final_res |>
  collect_predictions()

# and evaluate them with a few standard metrics
my_metrics <- metric_set(accuracy, precision, recall, f_meas)

my_metrics(final_pred, truth = rating, estimate = .pred_class)

# and the ROC curve
final_pred |>
  roc_curve(rating, .pred_5) |>
  autoplot()
```

