Machine Learning with PyTorch and Scikit-Learn
-- Code Examples
Package version checks
Add folder to path in order to load from the check_packages.py script:
Check recommended package versions:
Chapter 8 - Applying Machine Learning To Sentiment Analysis
Overview
Preparing the IMDb movie review data for text processing
Obtaining the IMDb movie review dataset
The IMDB movie review set can be downloaded from http://ai.stanford.edu/~amaas/data/sentiment/. After downloading the dataset, decompress the files.
A) If you are working with Linux or MacOS X, open a new terminal window, cd
into the download directory and execute
tar -zxf aclImdb_v1.tar.gz
B) If you are working with Windows, download an archiver such as 7Zip to extract the files from the download archive.
Optional code to download and unzip the dataset via Python:
Preprocessing the movie dataset into more convenient format
Install pyprind by uncommenting the next code cell.
Shuffling the DataFrame:
Optional: Saving the assembled data as CSV file:
Note
If you have problems with creating the movie_data.csv
, you can find a download a zip archive at https://github.com/rasbt/machine-learning-book/tree/main/ch08/
Introducing the bag-of-words model
...
Transforming documents into feature vectors
By calling the fit_transform method on CountVectorizer, we just constructed the vocabulary of the bag-of-words model and transformed the following three sentences into sparse feature vectors:
The sun is shining
The weather is sweet
The sun is shining, the weather is sweet, and one and one is two
Now let us print the contents of the vocabulary to get a better understanding of the underlying concepts:
As we can see from executing the preceding command, the vocabulary is stored in a Python dictionary, which maps the unique words to integer indices. Next let us print the feature vectors that we just created:
Each index position in the feature vectors shown here corresponds to the integer values that are stored as dictionary items in the CountVectorizer vocabulary. For example, the first feature at index position 0 resembles the count of the word "and", which only occurs in the last document, and the word "is" at index position 1 (the 2nd feature in the document vectors) occurs in all three sentences. Those values in the feature vectors are also called the raw term frequencies: tf (t,d)—the number of times a term t occurs in a document d.
Assessing word relevancy via term frequency-inverse document frequency
When we are analyzing text data, we often encounter words that occur across multiple documents from both classes. Those frequently occurring words typically don't contain useful or discriminatory information. In this subsection, we will learn about a useful technique called term frequency-inverse document frequency (tf-idf) that can be used to downweigh those frequently occurring words in the feature vectors. The tf-idf can be defined as the product of the term frequency and the inverse document frequency:
Here the tf(t, d) is the term frequency that we introduced in the previous section, and the inverse document frequency idf(t, d) can be calculated as:
where is the total number of documents, and df(d, t) is the number of documents d that contain the term t. Note that adding the constant 1 to the denominator is optional and serves the purpose of assigning a non-zero value to terms that occur in all training examples; the log is used to ensure that low document frequencies are not given too much weight.
Scikit-learn implements yet another transformer, the TfidfTransformer
, that takes the raw term frequencies from CountVectorizer
as input and transforms them into tf-idfs:
As we saw in the previous subsection, the word "is" had the largest term frequency in the 3rd document, being the most frequently occurring word. However, after transforming the same feature vector into tf-idfs, we see that the word "is" is now associated with a relatively small tf-idf (0.45) in document 3 since it is also contained in documents 1 and 2 and thus is unlikely to contain any useful, discriminatory information.
However, if we'd manually calculated the tf-idfs of the individual terms in our feature vectors, we'd have noticed that the TfidfTransformer
calculates the tf-idfs slightly differently compared to the standard textbook equations that we defined earlier. The equations for the idf and tf-idf that were implemented in scikit-learn are:
The tf-idf equation that was implemented in scikit-learn is as follows:
While it is also more typical to normalize the raw term frequencies before calculating the tf-idfs, the TfidfTransformer
normalizes the tf-idfs directly.
By default (norm='l2'
), scikit-learn's TfidfTransformer applies the L2-normalization, which returns a vector of length 1 by dividing an un-normalized feature vector v by its L2-norm:
To make sure that we understand how TfidfTransformer
works, let us walk through an example and calculate the tf-idf of the word "is" in the 3rd document.
The word "is" has a term frequency of 3 (tf = 3) in document 3 (), and the document frequency of this term is 3 since the term "is" occurs in all three documents (df = 3). Thus, we can calculate the idf as follows:
Now in order to calculate the tf-idf, we simply need to add 1 to the inverse document frequency and multiply it by the term frequency:
If we repeated these calculations for all terms in the 3rd document, we'd obtain the following tf-idf vectors: [3.39, 3.0, 3.39, 1.29, 1.29, 1.29, 2.0 , 1.69, 1.29]. However, we notice that the values in this feature vector are different from the values that we obtained from the TfidfTransformer
that we used previously. The final step that we are missing in this tf-idf calculation is the L2-normalization, which can be applied as follows:
As we can see, the results match the results returned by scikit-learn's TfidfTransformer
(below). Since we now understand how tf-idfs are calculated, let us proceed to the next sections and apply those concepts to the movie review dataset.
Cleaning text data
Processing documents into tokens
Training a logistic regression model for document classification
Strip HTML and punctuation to speed up the GridSearch later:
Important Note about n_jobs
Please note that it is highly recommended to use n_jobs=-1
(instead of n_jobs=1
) in the previous code example to utilize all available cores on your machine and speed up the grid search. However, some Windows users reported issues when running the previous code with the n_jobs=-1
setting related to pickling the tokenizer and tokenizer_porter functions for multiprocessing on Windows. Another workaround would be to replace those two functions, [tokenizer, tokenizer_porter]
, with [str.split]
. However, note that the replacement by the simple str.split
would not support stemming.
Start comment:
Please note that gs_lr_tfidf.best_score_
is the average k-fold cross-validation score. I.e., if we have a GridSearchCV
object with 5-fold cross-validation (like the one above), the best_score_
attribute returns the average score over the 5-folds of the best model. To illustrate this with an example:
By executing the code above, we created a simple data set of random integers that shall represent our class labels. Next, we fed the indices of 5 cross-validation folds (cv3_idx
) to the cross_val_score
scorer, which returned 5 accuracy scores -- these are the 5 accuracy values for the 5 test folds.
Next, let us use the GridSearchCV
object and feed it the same 5 cross-validation sets (via the pre-generated cv3_idx
indices):
As we can see, the scores for the 5 folds are exactly the same as the ones from cross_val_score
earlier.
Now, the best_score_ attribute of the GridSearchCV
object, which becomes available after fit
ting, returns the average accuracy score of the best model:
As we can see, the result above is consistent with the average score computed with cross_val_score
.
End comment.
Working with bigger data - online algorithms and out-of-core learning
Topic modeling
Decomposing text documents with Latent Dirichlet Allocation
Latent Dirichlet Allocation with scikit-learn
Based on reading the 5 most important words for each topic, we may guess that the LDA identified the following topics:
Generally bad movies (not really a topic category)
Movies about families
War movies
Art movies
Crime movies
Horror movies
Comedies
Movies somehow related to TV shows
Movies based on books
Action movies
To confirm that the categories make sense based on the reviews, let's plot 5 movies from the horror movie category (category 6 at index position 5):
Using the preceeding code example, we printed the first 300 characters from the top 3 horror movies and indeed, we can see that the reviews -- even though we don't know which exact movie they belong to -- sound like reviews of horror movies, indeed. (However, one might argue that movie #2 could also belong to topic category 1.)
Summary
...
Readers may ignore the next cell.