Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions R/sentence-transformers.R
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,22 @@ hf_load_sentence_model <- function(model_id) {
##' examples
##' dontrun{
##' # Compute sentence embeddings
##' sentences <- c("Baby turtles are so cute!", "He walks as slowly as a turtle.")
##' sentences_one <- c("Baby turtles are so cute!", "He walks as slowly as a turtle.")
##' sentences_two <- c("The lake is cold today.", "I enjoy swimming in the lake.")
##' sentences <- c(sentences, sentences_two)
##' sentences <- c(sentences_one, sentences_two)
##' model <- hf_load_sentence_model('paraphrase-MiniLM-L6-v2')
##' embeddings <- model$encode(sentences)
##' embeddings %>% dist() %>% as.matrix() %>% as.data.frame() %>% setNames(sentences)
##' embddings <- embeddings %>% dplyr::mutate(`sentence 1` = sentences) %>% tidyr::pivot_longer(cols = -`sentence 1`, names_to = 'sentence 2', values_to = 'distance')
##' embeddings <- embeddings %>% filter(distance > 0)
##' distances <- embeddings %>% dist() %>% as.matrix() %>% as.data.frame() %>% setNames(sentences)
##' distances <- distances %>%
##' dplyr::mutate(`sentence 1` = sentences) %>%
##' tidyr::pivot_longer(cols = -`sentence 1`, names_to = 'sentence 2', values_to = 'distance')
##' distances <- distances %>% dplyr::filter(distance > 0)
##' distances
##' # Cluster sentences
##' embeddings <- embeddings %>% t() %>% prcomp() %>% purrr::pluck('rotation') %>% as.data.frame() %>% dplyr::mutate(sentence = sentences)
##' plot <- embedidings %>% ggplot2::ggplot(aes(PC1, PC2)) + ggplot2::geom_label(ggplot2::aes(PC1, PC2, label = sentence, vjust="inward", hjust="inward")) + ggplot2::theme_minimal()
##' embeddings_pca <- embeddings %>% t() %>% prcomp() %>% purrr::pluck('rotation') %>% as.data.frame() %>% dplyr::mutate(sentence = sentences)
##' embeddings_pca %>%
##' ggplot2::ggplot(ggplot2::aes(PC1, PC2)) +
##' ggplot2::geom_point() +
##' ggplot2::geom_text(ggplot2::aes(label = sentence), vjust="inward", hjust="inward") +
##' ggplot2::theme_minimal()
##' }