I am working on prediction problem using a large textual dataset. I am implementing Bag of Words Model.
What should be the best way to get the bag of words? Right now, I have tf-idf of the various words and the number of words is too large to use it for further assignments. If I use tf-idf criteria, what should be the tf-idf threshold for getting bag of words? Or should I use some other algorithms. I am using python.
Bag of words could be defined as a matrix where each row represents a document and columns representing the individual token. One more thing, the sequential order of text is not maintained. Building a "Bag of Words" involves 3 steps
Limitations to keep in mind: 1. Cannot capture phrases or multi-word expressions 2. Sensitive to misspellings, possible to work around that using a spell corrector or character representation,
e.g.
Bag-of-words model is a nice method for text representation to be applied in different machine learning tasks. But in the first step you need to clean up data from unnecessary data for example punctuation, html tags, stop-words,... For these tasks you may can easily exploit libraries like Beautiful Soup (to remove HTML Markups) or NLTK (to remove stop-words) in Python. After cleaning your data you need to create a vector features (numerical representation of data for machine learning) this is where Bag-Of-Words plays the role. scikit-learn has a module (feature_extraction module) which can help you create the bag-of-words features.
You may find all you need in detail in this tutorial also this one can be very helpful. I found both of them very useful.
From a book "Machine learning python":
As others already mentioned, using
nltk
would be your best option if you want something stable, and scalable. It's highly configurable.However, it has the downside of having a quite steep learning curve, if you want to tweak the defaults.
I once encountered a situation where I wanted to have a bag of words. Problem was, it concerned articles about technologies with exotic names full of
-
,_
, etc. Such asvue-router
or_.js
etc.The default configuration of nltk's
word_tokenize
is to splitvue-router
into two separatevue
androuter
words, for instance. I'm not even talking about_.js
.So for what it's worth, I ended up writing this little routine to get all the words tokenized into a
list
, based on my own punctuation criteria.This routine can be easily combined with Patty3118 answer about
collections.Counter
, which could lead you to know which number of times_.js
was mentioned in the article, for instance.Using the collections.Counter class