# coding: utf-8123import sys4from python_environment_check import check_packages5import os6import tarfile7import time8import urllib.request9import pyprind10import pandas as pd11import numpy as np12from sklearn.feature_extraction.text import CountVectorizer13from sklearn.feature_extraction.text import TfidfTransformer14import re15from nltk.stem.porter import PorterStemmer16import nltk17from nltk.corpus import stopwords18from packaging import version19from sklearn.pipeline import Pipeline20from sklearn.linear_model import LogisticRegression21from sklearn.feature_extraction.text import TfidfVectorizer22from sklearn.model_selection import GridSearchCV23from sklearn.model_selection import StratifiedKFold24from sklearn.model_selection import cross_val_score25import gzip26from sklearn.feature_extraction.text import HashingVectorizer27from sklearn.linear_model import SGDClassifier28from distutils.version import LooseVersion as Version29from sklearn import __version__ as sklearn_version30from sklearn.decomposition import LatentDirichletAllocation313233# # Machine Learning with PyTorch and Scikit-Learn34# # -- Code Examples3536# ## Package version checks3738# Add folder to path in order to load from the check_packages.py script:39404142sys.path.insert(0, '..')434445# Check recommended package versions:464748495051d = {52'numpy': '1.21.2',53'pandas': '1.3.2',54'sklearn': '1.0',55'pyprind': '2.11.3',56'nltk': '3.6',57}58check_packages(d)596061# # Chapter 8 - Applying Machine Learning To Sentiment Analysis6263# ### Overview6465# - [Preparing the IMDb movie review data for text processing](#Preparing-the-IMDb-movie-review-data-for-text-processing)66# - [Obtaining the IMDb movie review dataset](#Obtaining-the-IMDb-movie-review-dataset)67# - [Preprocessing the movie dataset into more convenient format](#Preprocessing-the-movie-dataset-into-more-convenient-format)68# - [Introducing the bag-of-words model](#Introducing-the-bag-of-words-model)69# - [Transforming words into feature vectors](#Transforming-words-into-feature-vectors)70# - [Assessing word relevancy via term frequency-inverse document frequency](#Assessing-word-relevancy-via-term-frequency-inverse-document-frequency)71# - [Cleaning text data](#Cleaning-text-data)72# - [Processing documents into tokens](#Processing-documents-into-tokens)73# - [Training a logistic regression model for document classification](#Training-a-logistic-regression-model-for-document-classification)74# - [Working with bigger data – online algorithms and out-of-core learning](#Working-with-bigger-data-–-online-algorithms-and-out-of-core-learning)75# - [Topic modeling](#Topic-modeling)76# - [Decomposing text documents with Latent Dirichlet Allocation](#Decomposing-text-documents-with-Latent-Dirichlet-Allocation)77# - [Latent Dirichlet Allocation with scikit-learn](#Latent-Dirichlet-Allocation-with-scikit-learn)78# - [Summary](#Summary)798081# # Preparing the IMDb movie review data for text processing8283# ## Obtaining the IMDb movie review dataset8485# The IMDB movie review set can be downloaded from [http://ai.stanford.edu/~amaas/data/sentiment/](http://ai.stanford.edu/~amaas/data/sentiment/).86# After downloading the dataset, decompress the files.87#88# A) If you are working with Linux or MacOS X, open a new terminal windowm `cd` into the download directory and execute89#90# `tar -zxf aclImdb_v1.tar.gz`91#92# B) If you are working with Windows, download an archiver such as [7Zip](http://www.7-zip.org) to extract the files from the download archive.9394# **Optional code to download and unzip the dataset via Python:**9596979899source = 'http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz'100target = 'aclImdb_v1.tar.gz'101102if os.path.exists(target):103os.remove(target)104105def reporthook(count, block_size, total_size):106global start_time107if count == 0:108start_time = time.time()109return110duration = time.time() - start_time111progress_size = int(count * block_size)112speed = progress_size / (1024.**2 * duration)113percent = count * block_size * 100. / total_size114115sys.stdout.write(f'\r{int(percent)}% | {progress_size / (1024.**2):.2f} MB '116f'| {speed:.2f} MB/s | {duration:.2f} sec elapsed')117sys.stdout.flush()118119120if not os.path.isdir('aclImdb') and not os.path.isfile('aclImdb_v1.tar.gz'):121urllib.request.urlretrieve(source, target, reporthook)122123124125126if not os.path.isdir('aclImdb'):127128with tarfile.open(target, 'r:gz') as tar:129tar.extractall()130131132# ## Preprocessing the movie dataset into more convenient format133134# Install pyprind by uncommenting the next code cell.135136137138#!pip install pyprind139140141142143144# change the `basepath` to the directory of the145# unzipped movie dataset146147basepath = 'aclImdb'148149labels = {'pos': 1, 'neg': 0}150pbar = pyprind.ProgBar(50000, stream=sys.stdout)151df = pd.DataFrame()152for s in ('test', 'train'):153for l in ('pos', 'neg'):154path = os.path.join(basepath, s, l)155for file in sorted(os.listdir(path)):156with open(os.path.join(path, file),157'r', encoding='utf-8') as infile:158txt = infile.read()159if version.parse(pd.__version__) >= version.parse("1.3.2"):160x = pd.DataFrame([[txt, labels[l]]], columns=['review', 'sentiment'])161df = pd.concat([df, x], ignore_index=False)162163else:164df = df.append([[txt, labels[l]]],165ignore_index=True)166pbar.update()167df.columns = ['review', 'sentiment']168169170# Shuffling the DataFrame:171172173174175np.random.seed(0)176df = df.reindex(np.random.permutation(df.index))177178179# Optional: Saving the assembled data as CSV file:180181182183df.to_csv('movie_data.csv', index=False, encoding='utf-8')184185186187188189df = pd.read_csv('movie_data.csv', encoding='utf-8')190191# the following is necessary on some computers:192df = df.rename(columns={"0": "review", "1": "sentiment"})193194df.head(3)195196197198199df.shape200201202# ---203#204# ### Note205#206# If you have problems with creating the `movie_data.csv`, you can find a download a zip archive at207# https://github.com/rasbt/machine-learning-book/tree/main/ch08/208#209# ---210211212# # Introducing the bag-of-words model213214# ...215216# ## Transforming documents into feature vectors217218# 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:219# 1. The sun is shining220# 2. The weather is sweet221# 3. The sun is shining, the weather is sweet, and one and one is two222#223224225226227count = CountVectorizer()228docs = np.array([229'The sun is shining',230'The weather is sweet',231'The sun is shining, the weather is sweet, and one and one is two'])232bag = count.fit_transform(docs)233234235# Now let us print the contents of the vocabulary to get a better understanding of the underlying concepts:236237238239print(count.vocabulary_)240241242# As we can see from executing the preceding command, the vocabulary is stored in a Python dictionary, which maps the unique words that are mapped to integer indices. Next let us print the feature vectors that we just created:243244# 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 rst 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*.245246247248print(bag.toarray())249250251252# ## Assessing word relevancy via term frequency-inverse document frequency253254255256np.set_printoptions(precision=2)257258259# 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 downweight those frequently occurring words in the feature vectors. The tf-idf can be de ned as the product of the term frequency and the inverse document frequency:260#261# $$\text{tf-idf}(t,d)=\text{tf (t,d)}\times \text{idf}(t,d)$$262#263# Here the tf(t, d) is the term frequency that we introduced in the previous section,264# and the inverse document frequency *idf(t, d)* can be calculated as:265#266# $$\text{idf}(t,d) = \text{log}\frac{n_d}{1+\text{df}(d, t)},$$267#268# where $n_d$ 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.269#270# Scikit-learn implements yet another transformer, the `TfidfTransformer`, that takes the raw term frequencies from `CountVectorizer` as input and transforms them into tf-idfs:271272273274275tfidf = TfidfTransformer(use_idf=True,276norm='l2',277smooth_idf=True)278print(tfidf.fit_transform(count.fit_transform(docs))279.toarray())280281282# 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 is283# now associated with a relatively small tf-idf (0.45) in document 3 since it is284# also contained in documents 1 and 2 and thus is unlikely to contain any useful, discriminatory information.285#286287# 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 de ned earlier. The equations for the idf and tf-idf that were implemented in scikit-learn are:288289# $$\text{idf} (t,d) = log\frac{1 + n_d}{1 + \text{df}(d, t)}$$290#291# The tf-idf equation that was implemented in scikit-learn is as follows:292#293# $$\text{tf-idf}(t,d) = \text{tf}(t,d) \times (\text{idf}(t,d)+1)$$294#295# While it is also more typical to normalize the raw term frequencies before calculating the tf-idfs, the `TfidfTransformer` normalizes the tf-idfs directly.296#297# 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:298#299# $$v_{\text{norm}} = \frac{v}{||v||_2} = \frac{v}{\sqrt{v_{1}^{2} + v_{2}^{2} + \dots + v_{n}^{2}}} = \frac{v}{\big (\sum_{i=1}^{n} v_{i}^{2}\big)^\frac{1}{2}}$$300#301# To make sure that we understand how TfidfTransformer works, let us walk302# through an example and calculate the tf-idf of the word is in the 3rd document.303#304# The word is has a term frequency of 3 (tf = 3) in document 3 ($d_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:305#306# $$\text{idf}("is", d_3) = log \frac{1+3}{1+3} = 0$$307#308# 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:309#310# $$\text{tf-idf}("is", d_3)= 3 \times (0+1) = 3$$311312313314tf_is = 3315n_docs = 3316idf_is = np.log((n_docs+1) / (3+1))317tfidf_is = tf_is * (idf_is + 1)318print(f'tf-idf of term "is" = {tfidf_is:.2f}')319320321# 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 nal step that we are missing in this tf-idf calculation is the L2-normalization, which can be applied as follows:322323# $$\text{tfi-df}_{norm} = \frac{[3.39, 3.0, 3.39, 1.29, 1.29, 1.29, 2.0 , 1.69, 1.29]}{\sqrt{[3.39^2, 3.0^2, 3.39^2, 1.29^2, 1.29^2, 1.29^2, 2.0^2 , 1.69^2, 1.29^2]}}$$324#325# $$=[0.5, 0.45, 0.5, 0.19, 0.19, 0.19, 0.3, 0.25, 0.19]$$326#327# $$\Rightarrow \text{tfi-df}_{norm}("is", d3) = 0.45$$328329# 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.330331332333tfidf = TfidfTransformer(use_idf=True, norm=None, smooth_idf=True)334raw_tfidf = tfidf.fit_transform(count.fit_transform(docs)).toarray()[-1]335raw_tfidf336337338339340l2_tfidf = raw_tfidf / np.sqrt(np.sum(raw_tfidf**2))341l2_tfidf342343344345# ## Cleaning text data346347348349df.loc[0, 'review'][-50:]350351352353354def preprocessor(text):355text = re.sub('<[^>]*>', '', text)356emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)',357text)358text = (re.sub('[\W]+', ' ', text.lower()) +359' '.join(emoticons).replace('-', ''))360return text361362363364365preprocessor(df.loc[0, 'review'][-50:])366367368369370preprocessor("</a>This :) is :( a test :-)!")371372373374375df['review'] = df['review'].apply(preprocessor)376377378379# ## Processing documents into tokens380381382383384porter = PorterStemmer()385386def tokenizer(text):387return text.split()388389390def tokenizer_porter(text):391return [porter.stem(word) for word in text.split()]392393394395396tokenizer('runners like running and thus they run')397398399400401tokenizer_porter('runners like running and thus they run')402403404405406407nltk.download('stopwords')408409410411412413stop = stopwords.words('english')414[w for w in tokenizer_porter('a runner likes running and runs a lot')415if w not in stop]416417418419# # Training a logistic regression model for document classification420421# Strip HTML and punctuation to speed up the GridSearch later:422423424425X_train = df.loc[:25000, 'review'].values426y_train = df.loc[:25000, 'sentiment'].values427X_test = df.loc[25000:, 'review'].values428y_test = df.loc[25000:, 'sentiment'].values429430431432433434tfidf = TfidfVectorizer(strip_accents=None,435lowercase=False,436preprocessor=None)437438"""439param_grid = [{'vect__ngram_range': [(1, 1)],440'vect__stop_words': [stop, None],441'vect__tokenizer': [tokenizer, tokenizer_porter],442'clf__penalty': ['l1', 'l2'],443'clf__C': [1.0, 10.0, 100.0]},444{'vect__ngram_range': [(1, 1)],445'vect__stop_words': [stop, None],446'vect__tokenizer': [tokenizer, tokenizer_porter],447'vect__use_idf':[False],448'vect__norm':[None],449'clf__penalty': ['l1', 'l2'],450'clf__C': [1.0, 10.0, 100.0]},451]452"""453454small_param_grid = [{'vect__ngram_range': [(1, 1)],455'vect__stop_words': [None],456'vect__tokenizer': [tokenizer, tokenizer_porter],457'clf__penalty': ['l2'],458'clf__C': [1.0, 10.0]},459{'vect__ngram_range': [(1, 1)],460'vect__stop_words': [stop, None],461'vect__tokenizer': [tokenizer],462'vect__use_idf':[False],463'vect__norm':[None],464'clf__penalty': ['l2'],465'clf__C': [1.0, 10.0]},466]467468lr_tfidf = Pipeline([('vect', tfidf),469('clf', LogisticRegression(solver='liblinear'))])470471gs_lr_tfidf = GridSearchCV(lr_tfidf, small_param_grid,472scoring='accuracy',473cv=5,474verbose=1,475n_jobs=-1)476477478# **Important Note about `n_jobs`**479#480# 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.481482483484gs_lr_tfidf.fit(X_train, y_train)485486487488489print(f'Best parameter set: {gs_lr_tfidf.best_params_}')490print(f'CV Accuracy: {gs_lr_tfidf.best_score_:.3f}')491492493494495clf = gs_lr_tfidf.best_estimator_496print(f'Test Accuracy: {clf.score(X_test, y_test):.3f}')497498499500# #### Start comment:501#502# 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:503504505506507508np.random.seed(0)509np.set_printoptions(precision=6)510y = [np.random.randint(3) for i in range(25)]511X = (y + np.random.randn(25)).reshape(-1, 1)512513cv5_idx = list(StratifiedKFold(n_splits=5, shuffle=False).split(X, y))514515lr = LogisticRegression()516cross_val_score(lr, X, y, cv=cv5_idx)517518519# 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.520#521# Next, let us use the `GridSearchCV` object and feed it the same 5 cross-validation sets (via the pre-generated `cv3_idx` indices):522523524525526lr = LogisticRegression()527gs = GridSearchCV(lr, {}, cv=cv5_idx, verbose=3).fit(X, y)528529530# As we can see, the scores for the 5 folds are exactly the same as the ones from `cross_val_score` earlier.531532# Now, the best_score_ attribute of the `GridSearchCV` object, which becomes available after `fit`ting, returns the average accuracy score of the best model:533534535536gs.best_score_537538539# As we can see, the result above is consistent with the average score computed the `cross_val_score`.540541542543lr = LogisticRegression()544cross_val_score(lr, X, y, cv=cv5_idx).mean()545546547# #### End comment.548#549550551# # Working with bigger data - online algorithms and out-of-core learning552553554555# This cell is not contained in the book but556# added for convenience so that the notebook557# can be executed starting here, without558# executing prior code in this notebook559560561562if not os.path.isfile('movie_data.csv'):563if not os.path.isfile('movie_data.csv.gz'):564print('Please place a copy of the movie_data.csv.gz'565'in this directory. You can obtain it by'566'a) executing the code in the beginning of this'567'notebook or b) by downloading it from GitHub:'568'https://github.com/rasbt/machine-learning-book/'569'blob/main/ch08/movie_data.csv.gz')570else:571with gzip.open('movie_data.csv.gz', 'rb') as in_f, open('movie_data.csv', 'wb') as out_f:572out_f.write(in_f.read())573574575576577578579# The `stop` is defined as earlier in this chapter580# Added it here for convenience, so that this section581# can be run as standalone without executing prior code582# in the directory583stop = stopwords.words('english')584585586def tokenizer(text):587text = re.sub('<[^>]*>', '', text)588emoticons = re.findall('(?::|;|=)(?:-)?(?:\)|\(|D|P)', text)589text = re.sub('[\W]+', ' ', text.lower()) + ' '.join(emoticons).replace('-', '')590tokenized = [w for w in text.split() if w not in stop]591return tokenized592593594def stream_docs(path):595with open(path, 'r', encoding='utf-8') as csv:596next(csv) # skip header597for line in csv:598text, label = line[:-3], int(line[-2])599yield text, label600601602603604next(stream_docs(path='movie_data.csv'))605606607608609def get_minibatch(doc_stream, size):610docs, y = [], []611try:612for _ in range(size):613text, label = next(doc_stream)614docs.append(text)615y.append(label)616except StopIteration:617return None, None618return docs, y619620621622623624625vect = HashingVectorizer(decode_error='ignore',626n_features=2**21,627preprocessor=None,628tokenizer=tokenizer)629630631632633634clf = SGDClassifier(loss='log', random_state=1)635636637doc_stream = stream_docs(path='movie_data.csv')638639640641642pbar = pyprind.ProgBar(45)643644classes = np.array([0, 1])645for _ in range(45):646X_train, y_train = get_minibatch(doc_stream, size=1000)647if not X_train:648break649X_train = vect.transform(X_train)650clf.partial_fit(X_train, y_train, classes=classes)651pbar.update()652653654655656X_test, y_test = get_minibatch(doc_stream, size=5000)657X_test = vect.transform(X_test)658print(f'Accuracy: {clf.score(X_test, y_test):.3f}')659660661662663clf = clf.partial_fit(X_test, y_test)664665666# ## Topic modeling667668# ### Decomposing text documents with Latent Dirichlet Allocation669670# ### Latent Dirichlet Allocation with scikit-learn671672673674675df = pd.read_csv('movie_data.csv', encoding='utf-8')676677# the following is necessary on some computers:678df = df.rename(columns={"0": "review", "1": "sentiment"})679680df.head(3)681682683684685686count = CountVectorizer(stop_words='english',687max_df=.1,688max_features=5000)689X = count.fit_transform(df['review'].values)690691692693694695lda = LatentDirichletAllocation(n_components=10,696random_state=123,697learning_method='batch')698X_topics = lda.fit_transform(X)699700701702703lda.components_.shape704705706707708n_top_words = 5709feature_names = count.get_feature_names_out()710711for topic_idx, topic in enumerate(lda.components_):712print(f'Topic {(topic_idx + 1)}:')713print(' '.join([feature_names[i]714for i in topic.argsort()\715[:-n_top_words - 1:-1]]))716717718# Based on reading the 5 most important words for each topic, we may guess that the LDA identified the following topics:719#720# 1. Generally bad movies (not really a topic category)721# 2. Movies about families722# 3. War movies723# 4. Art movies724# 5. Crime movies725# 6. Horror movies726# 7. Comedies727# 8. Movies somehow related to TV shows728# 9. Movies based on books729# 10. Action movies730731# 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):732733734735horror = X_topics[:, 5].argsort()[::-1]736737for iter_idx, movie_idx in enumerate(horror[:3]):738print(f'\nHorror movie #{(iter_idx + 1)}:')739print(df['review'][movie_idx][:300], '...')740741742# 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.)743744745# # Summary746747# ...748749# ---750#751# Readers may ignore the next cell.752753754755756757758