12

Suppose I have text based training data and testing data. To be more specific, I have two data sets - training and testing - and both of them have one column which contains text and is of interest for the job at hand.

I used tm package in R to process the text column in the training data set. After removing the white spaces, punctuation, and stop words, I stemmed the corpus and finally created a document term matrix of 1 grams containing the frequency/count of the words in each document. I then took a pre-determined cut-off of, say, 50 and kept only those terms that have a count of greater than 50.

Following this, I train a, say, GLMNET model using the DTM and the dependent variable (which was present in the training data). Everything runs smooth and easy till now.

However, how do I proceed when I want to score/predict the model on the testing data or any new data that might come in the future?

Specifically, what I am trying to find out is that how do I create the exact DTM on new data?

If the new data set does not have any of the similar words as the original training data then all the terms should have a count of zero (which is fine). But I want to be able to replicate the exact same DTM (in terms of structure) on any new corpus.

Any ideas/thoughts?

4
  • If I understood your question correctly (and I'm not sure I have, without a reproducible example demonstrating what you're trying to do.), it seems the simplest way to do this would be to create the term-document matrix using all of your data, and then split that matrix into a testing and training set. That way, you have all the terms represented in both matrices, even if one matrix only has zeros for several terms. You're running into trouble because you're splitting the data before you create your term-document matrices.
    – SchaunW
    May 19, 2013 at 2:27
  • 2
    I agree Schaun, but I can only do that with the testing data that I have currently. I am looking for a solution that will work when I get new data tomorrow. Else if it would be a pain to always add new data to exiting ones, recreate the DTM and retrain the model every time.
    – Godel
    May 19, 2013 at 2:43
  • 1
    Again, having example data to work with would make it easier to answer your question. How about this: turn your new data into a term-document matrix, then bind it to the old data using the plyr package's rbind.fill function, which would create a new matrix with all columns from both original matrices. Your training data would have columns of NAs for any terms in your new data that were not in your training data. You could then delete those columns. Your new data would have columns of NAs for any terms in your training data but not in your new data, You could replace those NAs with zeros.
    – SchaunW
    May 19, 2013 at 11:44
  • Thanks Schaun; that does help. Unfortunately I don't have any sample data. Essentially, I was trying to figure out if there exists a function in any package that should do this neatly. For example, one a dtm is created, it uses the structure of existing one to create a new one when provided with new data. Searching on the web did not reveal anything so I thought of posting it here.
    – Godel
    May 19, 2013 at 15:56

2 Answers 2

16

tm has so many pitfalls... See much more efficient text2vec and vectorization vignette which fully answers to the question.

For tm here is probably one more simple way to reconstruct DTM matrix for second corpus:

crude2.dtm <- DocumentTermMatrix(crude2, control = list
               (dictionary=Terms(crude1.dtm), wordLengths = c(3,10)) )
4
  • 4
    That works also great, but Dictionary() is not longer supported and you have to use Terms() instead.
    – Khozzy
    Dec 28, 2014 at 11:49
  • 1
    Great example, will definetly give it a try, have been looking for a native way of doing this. I guess I should actually read vingietes of packages I use :)
    – Tetlanesh
    Jul 20, 2015 at 10:04
  • 2
    I think this solution is much better since it does not convert from sparse matrix Feb 3, 2016 at 16:38
  • This is the best/shortest solution. Thx! There are so many tutorial out there, which discuss text analysis in R. However, not a single one I looked at discussed how to make "out of sample" predictions on new documents.
    – Peter
    Nov 13, 2018 at 17:15
12

If I understand correctly, you have made a dtm, and you want to make a new dtm from new documents that has the same columns (ie. terms) as the first dtm. If that's the case, then it should be a matter of sub-setting the second dtm by the terms in the first, perhaps something like this:

First set up some reproducible data...

This is your training data...

library(tm)
# make corpus for text mining (data comes from package, for reproducibility) 
data("crude")
corpus1 <- Corpus(VectorSource(crude[1:10]))    
# process text (your methods may differ)
skipWords <- function(x) removeWords(x, stopwords("english"))
funcs <- list(tolower, removePunctuation, removeNumbers,
              stripWhitespace, skipWords)
crude1 <- tm_map(corpus1, FUN = tm_reduce, tmFuns = funcs)
crude1.dtm <- DocumentTermMatrix(crude1, control = list(wordLengths = c(3,10))) 

And this is your testing data...

corpus2 <- Corpus(VectorSource(crude[15:20]))  
# process text (your methods may differ)
skipWords <- function(x) removeWords(x, stopwords("english"))
funcs <- list(tolower, removePunctuation, removeNumbers,
              stripWhitespace, skipWords)
crude2 <- tm_map(corpus2, FUN = tm_reduce, tmFuns = funcs)
crude2.dtm <- DocumentTermMatrix(crude2, control = list(wordLengths = c(3,10))) 

Here is the bit that does what you want:

Now we keep only the terms in the testing data that are present in the training data...

# convert to matrices for subsetting
crude1.dtm.mat <- as.matrix(crude1.dtm) # training
crude2.dtm.mat <- as.matrix(crude2.dtm) # testing

# subset testing data by colnames (ie. terms) or training data
xx <- data.frame(crude2.dtm.mat[,intersect(colnames(crude2.dtm.mat),
                                           colnames(crude1.dtm.mat))])

Finally add to the testing data all the empty columns for terms in the training data that are not in the testing data...

# make an empty data frame with the colnames of the training data
yy <- read.table(textConnection(""), col.names = colnames(crude1.dtm.mat),
                 colClasses = "integer")

# add incols of NAs for terms absent in the 
# testing data but present # in the training data
# following SchaunW's suggestion in the comments above
library(plyr)
zz <- rbind.fill(xx, yy)

So zz is a data frame of the testing documents, but has the same structure as the training documents (ie. same columns, though many of them contain NA, as SchaunW notes).

Is that along the lines of what you want?

4
  • Yes Ben. This helps quite a bit. Thanks a lot. :)
    – Godel
    May 21, 2013 at 13:03
  • No worries! And now you know how to make sample data to include in any related questions you might want to ask.
    – Ben
    May 21, 2013 at 19:04
  • I've been looking for a solution for this for a while, thanks, although will try also one prowided below by Dmitriy
    – Tetlanesh
    Jul 20, 2015 at 10:03
  • 1
    This requires the deconstruction of your sparse matrix, consider the solution using dictionary=Terms(crude1.dtm) Feb 3, 2016 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.