vignettes/supervised_learning.Rmd
supervised_learning.Rmd
library(fastrtext)
data("train_sentences")
data("test_sentences")
# prepare data
tmp_file_model <- tempfile()
train_labels <- paste0("__label__", train_sentences[,"class.text"])
train_texts <- tolower(train_sentences[,"text"])
train_to_write <- paste(train_labels, train_texts)
train_tmp_file_txt <- tempfile()
writeLines(text = train_to_write, con = train_tmp_file_txt)
test_labels <- paste0("__label__", test_sentences[,"class.text"])
test_labels_without_prefix <- test_sentences[,"class.text"]
test_texts <- tolower(test_sentences[,"text"])
test_to_write <- paste(test_labels, test_texts)
# learn model
execute(commands = c("supervised", "-input", train_tmp_file_txt, "-output", tmp_file_model, "-dim", 20, "-lr", 1, "-epoch", 20, "-wordNgrams", 2, "-verbose", 1))
##
Read 0M words
## Number of words: 5060
## Number of labels: 15
##
Progress: 100.0% words/sec/thread: 1108251 lr: 0.000000 loss: 0.306367 ETA: 0h 0m
## add .bin extension to the path
# prediction are returned as a list with words and probabilities
predictions <- predict(model, sentences = test_to_write)
print(head(predictions, 5))
## [[1]]
## OWNX
## 0.9996475
##
## [[2]]
## MISC
## 0.9847125
##
## [[3]]
## MISC
## 0.9911765
##
## [[4]]
## OWNX
## 0.9216562
##
## [[5]]
## AIMX
## 0.9848558
## [1] 0.8316667
# because there is only one category by observation, hamming loss will be the same
get_hamming_loss(as.list(test_labels_without_prefix), predictions)
## [1] 0.8316667
# test predictions
predictions <- predict(model, sentences = test_to_write)
print(head(predictions, 5))
## [[1]]
## OWNX
## 0.9996475
##
## [[2]]
## MISC
## 0.9847125
##
## [[3]]
## MISC
## 0.9911765
##
## [[4]]
## OWNX
## 0.9216562
##
## [[5]]
## AIMX
## 0.9848558
# you can get flat list of results when you are retrieving only one label per observation
print(head(predict(model, sentences = test_to_write, simplify = TRUE)))
## OWNX MISC MISC OWNX AIMX CONT
## 0.9996475 0.9847125 0.9911765 0.9216562 0.9848558 0.4192168
## used (Mb) gc trigger (Mb) max used (Mb)
## Ncells 641703 34.3 1212111 64.8 1212111 64.8
## Vcells 1311645 10.1 8388608 64.0 2061190 15.8