anirudhacharya commented on a change in pull request #12670: [MXNET-833] [R] Char-level RNN tutorial fix URL: https://github.com/apache/incubator-mxnet/pull/12670#discussion_r220741000
########## File path: R-package/vignettes/CharRnnModel.Rmd ########## @@ -36,237 +32,262 @@ download.data <- function(data_dir) { } ``` -Make dictionary from text. - -```{r} -make.dict <- function(text, max.vocab=10000) { - text <- strsplit(text, '') - dic <- list() - idx <- 1 - for (c in text[[1]]) { - if (!(c %in% names(dic))) { - dic[[c]] <- idx - idx <- idx + 1 - } - } - if (length(dic) == max.vocab - 1) - dic[["UNKNOWN"]] <- idx - cat(paste0("Total unique char: ", length(dic), "\n")) - return (dic) -} -``` - -Transfer text into data feature. - -```{r} -make.data <- function(file.path, seq.len=32, max.vocab=10000, dic=NULL) { - fi <- file(file.path, "r") - text <- paste(readLines(fi), collapse="\n") - close(fi) - - if (is.null(dic)) - dic <- make.dict(text, max.vocab) - lookup.table <- list() - for (c in names(dic)) { - idx <- dic[[c]] - lookup.table[[idx]] <- c - } - - char.lst <- strsplit(text, '')[[1]] - num.seq <- as.integer(length(char.lst) / seq.len) - char.lst <- char.lst[1:(num.seq * seq.len)] - data <- array(0, dim=c(seq.len, num.seq)) - idx <- 1 - for (i in 1:num.seq) { - for (j in 1:seq.len) { - if (char.lst[idx] %in% names(dic)) - data[j, i] <- dic[[ char.lst[idx] ]]-1 - else { - data[j, i] <- dic[["UNKNOWN"]]-1 - } - idx <- idx + 1 - } - } - return (list(data=data, dic=dic, lookup.table=lookup.table)) +Next we transform the test into feature vectors that is fed into the RNN model. The `make_data` function reads the dataset, cleans it of any non-alphanumeric characters, splits it into individual characters and groups it into sequences of length `seq.len`. + + +```R +make_data <- function(path, seq.len=32, dic=NULL) { + + text_vec <- read_file(file = path) + text_vec <- stri_enc_toascii(str = text_vec) + text_vec <- str_replace_all(string = text_vec, pattern = "[^[:print:]]", replacement = "") + text_vec <- strsplit(text_vec, '') %>% unlist + + if (is.null(dic)) { + char_keep <- sort(unique(text_vec)) + } else char_keep <- names(dic)[!dic == 0] + + # Remove terms not part of dictionnary + text_vec <- text_vec[text_vec %in% char_keep] + + # Build dictionnary Review comment: will fix ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org With regards, Apache Git Services