Как суммировать текст электронной почты, используя LDA в R - PullRequest
0 голосов
/ 27 мая 2019

Я работаю над анализом данных о жалобах, где я адаптирую технику текстового резюме для сокращения ненужного текста и вывода только полезного текста.

Я использовал LDA - скрытое выделение дирихле в R для обобщения текста, но я не в состоянии выполнить его в полной мере.

 library(igraph) 
 library(iterators)      

#create a TCM using skip grams, we'll use a 5-word window
tcm <- CreateTcm(doc_vec = datacopy$Text,skipgram_window = 10,
verbose = FALSE,cpus = 2)

# LDA to get embeddings into probability space
embeddings <- FitLdaModel(dtm = tcm, k = 50, iterations = 300,       
burnin = 180, alpha = 0.1,beta = 0.05, optimize_alpha = TRUE, 
calc_likelihood = FALSE,calc_coherence = FALSE, calc_r2 = FALSE,cpus=2)

#Summarizer function
summarizer <- function(doc, gamma) {

# handle multiple docs at once
if (length(doc) > 1 )
    return(sapply(doc, function(d) try(summarizer(d, gamma))))

# parse it into sentences
sent <- stringi::stri_split_boundaries(doc, type = "sentence")[[ 1 ]]
names(sent) <- seq_along(sent) # so we know index and order

# embed the sentences in the model
e <- CreateDtm(sent, ngram_window = c(1,1), verbose = FALSE, cpus = 2)

# remove any documents with 2 or fewer words
#e <- e[ rowSums(e) > 2 , ]
vocab <- intersect(colnames(e), colnames(gamma))
e <- e / rowSums(e)
e <- e[ , vocab ] %*% t(gamma[ , vocab ])
e <- as.matrix(e)
# get the pairwise distances between each embedded sentence
e_dist <- CalcHellingerDist(e)
# turn into a similarity matrix
g <- (1 - e_dist) * 100
# we don't need sentences connected to themselves
diag(g) <- 0

# turn into a nearest-neighbor graph
g <- apply(g, 1, function(x){
x[ x < sort(x, decreasing = TRUE)[ 3 ] ] <- 0
x
})

# by taking pointwise max, we'll make the matrix symmetric again
g <- pmax(g, t(g))
g <- graph.adjacency(g, mode = "undirected", weighted = TRUE)
# calculate eigenvector centrality
ev <- evcent(g)

# format the result
result<-sent[names(ev$vector)[order(ev$vector,decreasing=TRUE)[1:3]]]
result <- result[ order(as.numeric(names(result))) ]
paste(result, collapse = " ")
}

docs <- datacopy$Text[1:10]
names(docs) <- datacopy$Reference[1:10]
sums <- summarizer(docs,gamma = embeddings$gamma)
sums

Ошибка -

Error in base::rowSums(x, na.rm = na.rm, dims = dims, ...) : 
'x' must be an array of at least two dimensions
Error in if (nrow(adjmatrix) != ncol(adjmatrix)) { : 
argument is of length zero
Error in base::rowSums(x, na.rm = na.rm, dims = dims, ...) : 
'x' must be an array of at least two dimensions

Error in if (nrow(adjmatrix) != ncol(adjmatrix)) 
  {:argument is of length zero
  Error in if (nrow(adjmatrix) != ncol(adjmatrix)) 
  {:argument is of length zero 

Фактический текст: Совет несет ответственность за работу со свободной крышкой люка. Не могли бы вы предоставить обновленную информацию о следующих шагах, предпринятых советом. ** Trail Mails Текст следует - около 50 строк текста **

Обобщенный текст: Совет обязан разобраться со свободной крышкой люка. Я прочитал ветку электронной почты, пожалуйста, свяжитесь с номерами, предоставленными ABC "

...