Tutorial - build MNB with sklearn

This tutorial demonstrates how to use the Sci-kit Learn (sklearn) package to build Multinomial Naive Bayes model, rank features, and use the model for prediction.

The data from the Kaggle Sentiment Analysis on Movie Review Competition are used in this tutorial. Check out the details of the data and the competition on Kaggle. https://www.kaggle.com/c/sentiment-analysis-on-movie-reviews

The tutorial also includes sample code to prepare your prediction result for submission to Kaggle. Although the competition is over, you can still submit your prediction to get an evaluation score.

This revised script changed two places in the original script: (1) Exercise A: replaced the outdated "itemfreq" function with new one so no more warnings (2) Exercise C: replace the "coef_" variable with the "feature_logprob" variable. Although the sklearn manual said coef_ mirrors feature_logprob, we found that in case of binary classification, coef_ has only one dimension but feature_logprob keeps the original two dimensions of positive and negative conditional probs. The code was also cleaned and simplified.# Step 1: Read in data

In [1]:
# read in the training data

# the data set includes four columns: PhraseId, SentenceId, Phrase, Sentiment
# In this data set a sentence is further split into phrases 
# in order to build a sentiment classification model
# that can not only predict sentiment of sentences but also shorter phrases

# A data example:
# PhraseId SentenceId Phrase Sentiment
# 1 1 A series of escapades demonstrating the adage that what is good for the goose is also good for the gander , some of which occasionally amuses but none of which amounts to much of a story .1

# the Phrase column includes the training examples
# the Sentiment column includes the training labels
# "0" for very negative
# "1" for negative
# "2" for neutral
# "3" for positive
# "4" for very positive

import numpy as np
import pandas as p
train=p.read_csv("kaggle-sentiment/train.tsv", delimiter='\t')
y=train['Sentiment'].values
X=train['Phrase'].values

train[:5]
Out[1]:
PhraseId SentenceId Phrase Sentiment
0 1 1 A series of escapades demonstrating the adage ... 1
1 2 1 A series of escapades demonstrating the adage ... 2
2 3 1 A series 2
3 4 1 A 2
4 5 1 series 2

Step 2: Split train/test data for hold-out test

In [2]:
# check the sklearn documentation for train_test_split
# http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
# "test_size" : float, int, None, optional
# If float, should be between 0.0 and 1.0 and represent the proportion of the dataset to include in the test split. 
# If int, represents the absolute number of test samples. 
# If None, the value is set to the complement of the train size. 
# By default, the value is set to 0.25. The default will change in version 0.21. It will remain 0.25 only if train_size is unspecified, otherwise it will complement the specified train_size.    

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=None, random_state=0)

print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
print(X_train[0])
print(y_train[0])
print(X_test[0])
print(y_test[0])
(117045,) (117045,) (39015,) (39015,)
illusion
2
escape movie
2

Sample output from the code above:

(93636,) (93636,) (62424,) (62424,) almost in a class with that of Wilde 3 escape movie 2

Step 2.1 Data Checking

In [3]:
# Check how many training examples in each category
# this is important to see whether the data set is balanced or skewed

unique, counts = np.unique(y_train, return_counts=True)
print(np.asarray((unique, counts)))

unique, counts = np.unique(y_test, return_counts=True)
print(np.asarray((unique, counts))) 
[[    0     1     2     3     4]
 [ 5228 20482 59601 24837  6897]]
[[    0     1     2     3     4]
 [ 1844  6791 19981  8090  2309]]

The sample output shows that the data set is skewed with 47718/93636=51% "neutral" examples. All other categories are smaller.

{0, 1, 2, 3, 4} [[ 0 4141] [ 1 16449] [ 2 47718] [ 3 19859] [ 4 5469]]

In [ ]:
 

Exercise A

In [4]:
# Print out the category distribution in the test data set. 
# Is the test data set's category distribution similar to the training data set's?

# Your code starts here
training_labels = set(y_train)
print(training_labels)
from scipy.stats import itemfreq
training_category_dist = itemfreq(y_train)
# ^^ apparently being depreciated 
training_cateory_dist = np.unique(y_train, return_counts=True)
print(training_category_dist)
testing_category_dist = np.unique(y_test, return_counts=True)
print(testing_category_dist)
{0, 1, 2, 3, 4}
[[    0  5228]
 [    1 20482]
 [    2 59601]
 [    3 24837]
 [    4  6897]]
(array([0, 1, 2, 3, 4]), array([ 1844,  6791, 19981,  8090,  2309]))
/usr/local/lib/python3.7/site-packages/ipykernel_launcher.py:8: DeprecationWarning: `itemfreq` is deprecated!
`itemfreq` is deprecated and will be removed in a future version. Use instead `np.unique(..., return_counts=True)`
  
In [5]:
import matplotlib.pyplot as plt
plt.bar(testing_category_dist[0], testing_category_dist[1], align='center', alpha=0.5)
plt.ylabel('Num Reviews')
plt.title('Test Distribution')
plt.show()
<Figure size 640x480 with 1 Axes>
In [11]:
## REPLICATING THE CODE
training_labels = set(y_train)
print(training_labels)
from scipy.stats import itemfreq
# training_category_dist = itemfreq(y_train)
# ^^ being depreciated 
training_cateory_dist = np.unique(y_train, return_counts=True)
print(training_category_dist)
testing_category_dist = np.unique(y_test, return_counts=True)
print(testing_category_dist)

## PLOTTING TEST AND TRAIN
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

unique, counts = np.unique(y_train, return_counts=True)
train_arr = np.asarray((unique, counts))

unique, counts = np.unique(y_test, return_counts=True)
test_arr = np.asarray((unique, counts))

# x = testing_category_dist[0].tolist()
# print(x)
# train = train_arr[1].tolist()
# print(z)
# test = test_arr[1].tolist()
# print(k)

# df = pd.DataFrame(zip(x*2, ["train"]*len(x)+["test"]*len(x), train+test), columns=["sentiment", "dataset", "reviews"])
# print(df)
# plt.figure(figsize=(10, 6))
# sns.barplot(x="sentiment", hue="dataset", y="reviews", data=df)
# plt.show()
{0, 1, 2, 3, 4}
[[    0  5228]
 [    1 20482]
 [    2 59601]
 [    3 24837]
 [    4  6897]]
(array([0, 1, 2, 3, 4]), array([ 1844,  6791, 19981,  8090,  2309]))
In [14]:
# df = pd.DataFrame(zip(x*2, ["z"]*5+["k"]*5, z+k), columns=["sentiment", "kind", "reviews"])
# ["z"]*5+["k"]*5
# z+k

Step 3: Vectorization

In [15]:
# sklearn contains two vectorizers

# CountVectorizer can give you Boolean or TF vectors
# http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html

# TfidfVectorizer can give you TF or TFIDF vectors
# http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html

# Read the sklearn documentation to understand all vectorization options

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer

# several commonly used vectorizer setting

#  unigram boolean vectorizer, set minimum document frequency to 5
unigram_bool_vectorizer = CountVectorizer(encoding='latin-1', binary=True, min_df=5, stop_words='english')

#  unigram term frequency vectorizer, set minimum document frequency to 5
unigram_count_vectorizer = CountVectorizer(encoding='latin-1', binary=False, min_df=5, stop_words='english')

#  unigram and bigram term frequency vectorizer, set minimum document frequency to 5
gram12_count_vectorizer = CountVectorizer(encoding='latin-1', ngram_range=(1,2), min_df=5, stop_words='english')

#  unigram tfidf vectorizer, set minimum document frequency to 5
unigram_tfidf_vectorizer = TfidfVectorizer(encoding='latin-1', use_idf=True, min_df=5, stop_words='english')

Step 3.1: Vectorize the training data

In [17]:
# The vectorizer can do "fit" and "transform"
# fit is a process to collect unique tokens into the vocabulary
# transform is a process to convert each document to vector based on the vocabulary
# These two processes can be done together using fit_transform(), or used individually: fit() or transform()

# fit vocabulary in training documents and transform the training documents into vectors
X_train_vec = unigram_count_vectorizer.fit_transform(X_train)

# check the content of a document vector

# check the size of the constructed vocabulary
print(len(unigram_count_vectorizer.vocabulary_))

# print out the first 10 items in the vocabulary
print(list(unigram_count_vectorizer.vocabulary_.items())[:10])

# check word index in vocabulary
print(unigram_count_vectorizer.vocabulary_.get('imaginative'))
13247
[('illusion', 5790), ('gore', 5084), ('entertaining', 3918), ('somewhat', 10851), ('standardized', 11090), ('surprise', 11484), ('mayhem', 7255), ('geared', 4915), ('maximum', 7253), ('comfort', 2241)]
5800

Sample output:

(93636, 11967) [[0 0 0 ..., 0 0 0]] 11967 [('imaginative', 5224), ('tom', 10809), ('smiling', 9708), ('easy', 3310), ('diversity', 3060), ('impossibly', 5279), ('buy', 1458), ('sentiments', 9305), ('households', 5095), ('deteriorates', 2843)] 5224

Step 3.2: Vectorize the test data

In [18]:
# use the vocabulary constructed from the training data to vectorize the test data. 
# Therefore, use "transform" only, not "fit_transform", 
# otherwise "fit" would generate a new vocabulary from the test data

X_test_vec = unigram_count_vectorizer.fit_transform(X_test)

# print out #examples and #features in the test set
print(X_test_vec.shape)
(39015, 6429)

Sample output:

(62424, 14324)

Exercise B

In [19]:
# In the above sample code, the term-frequency vectors were generated for training and test data.

# Some people argue that 
# because the MultinomialNB algorithm is based on word frequency, 
# we should not use boolean representation for MultinomialNB.
# While in theory it is true, you might see people use boolean representation for MultinomialNB
# especially when the chosen tool, e.g. Weka, does not provide the BernoulliNB algorithm.

# sklearn does provide both MultinomialNB and BernoulliNB algorithms.
# http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.BernoulliNB.html
# You will practice that later

# In this exercise you will vectorize the training and test data using boolean representation
# You can decide on other options like ngrams, stopwords, etc.

# Your code starts here
# test_bool = unigram_count_vectorizer.transform(X_test)
# train_bool = unigram_count_vectorizer.transform(X_train)
In [20]:
# This kept giving me this error
# NotFittedError: CountVectorizer - Vocabulary wasn't fitted.

test_bool = unigram_bool_vectorizer.fit_transform(X_test)
train_bool = unigram_bool_vectorizer.fit_transform(X_train)

# # So I did this
# import sklearn
# vocabulary_to_load = X_test
# loaded_vectorizer = sklearn.feature_extraction.text.CountVectorizer(ngram_range=(1,
#                                         2), binary = True, min_df=1, vocabulary=vocabulary_to_load)
# loaded_vectorizer._validate_vocabulary()
# print('loaded_vectorizer.get_feature_names(): {0}'.
#   format(loaded_vectorizer.get_feature_names()))
train_bool
test_bool
Out[20]:
<39015x6429 sparse matrix of type '<class 'numpy.int64'>'
	with 124934 stored elements in Compressed Sparse Row format>

Step 4: Train a MNB classifier

In [21]:
# import the MNB module
from sklearn.naive_bayes import MultinomialNB

# initialize the MNB model
nb_clf= MultinomialNB()

# use the training data to train the MNB model
nb_clf.fit(X_train_vec,y_train)
Out[21]:
MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True)

Step 4.1 Interpret a trained MNB model

In [22]:
## interpreting naive Bayes models
## by consulting the sklearn documentation you can also find out feature_log_prob_, 
## which are the conditional probabilities
## http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html

# the code below will print out the conditional prob of the word "worthless" in each category
# sample output
# -8.98942647599 -> logP('worthless'|very negative')
# -11.1864401922 -> logP('worthless'|negative')
# -12.3637684625 -> logP('worthless'|neutral')
# -11.9886066961 -> logP('worthless'|positive')
# -11.0504454621 -> logP('worthless'|very positive')
# the above output means the word feature "worthless" is indicating "very negative" 
# because P('worthless'|very negative) is the greatest among all conditional probs

unigram_count_vectorizer.vocabulary_.get('worthless')
for i in range(0,5):
    print(nb_clf.feature_log_prob_[i][unigram_count_vectorizer.vocabulary_.get('worthless')])
-10.686292605026608
-9.943179308577442
-10.682714947521708
-11.695088675894803
-10.832635277912791

Sample output:

-8.5389826392 -10.6436375867 -11.8419845779 -11.4778370023 -10.6297551464

In [23]:
# sort the conditional probability for category 0 "very negative"
# print the words with highest conditional probs
# these can be words popular in the "very negative" category alone, or words popular in all cateogires

feature_ranks = sorted(zip(nb_clf.feature_log_prob_[0], unigram_count_vectorizer.get_feature_names()))
very_negative_features = feature_ranks[-10:]
print(very_negative_features)
[(-6.409626486010553, 'anachronistic'), (-6.368804491490298, 'sharp'), (-6.304265970352727, 'knowing'), (-6.142997822756604, 'mermaid'), (-6.051563616796972, 'anakin'), (-5.994944722797465, 'lovely'), (-5.803490682440238, 'fleshed'), (-5.7959434768048546, 'enduring'), (-4.8993952236599005, 'chiefly'), (-4.8226614294285115, 'purpose')]

Exercise C

In [24]:
sorted(zip(nb_clf.feature_log_prob_[0], unigram_count_vectorizer.get_feature_names()))
Out[24]:
[(-10.686292605026608, '12'),
 (-10.686292605026608, '163'),
 (-10.686292605026608, '18'),
 (-10.686292605026608, '19'),
 (-10.686292605026608, '1920'),
 (-10.686292605026608, '1940s'),
 (-10.686292605026608, '1958'),
 (-10.686292605026608, '1970s'),
 (-10.686292605026608, '1984'),
 (-10.686292605026608, '1999'),
 (-10.686292605026608, '19th'),
 (-10.686292605026608, '20'),
 (-10.686292605026608, '2000'),
 (-10.686292605026608, '2002'),
 (-10.686292605026608, '21st'),
 (-10.686292605026608, '30'),
 (-10.686292605026608, '300'),
 (-10.686292605026608, '3000'),
 (-10.686292605026608, '3d'),
 (-10.686292605026608, '40'),
 (-10.686292605026608, '50'),
 (-10.686292605026608, '50s'),
 (-10.686292605026608, '52'),
 (-10.686292605026608, '7th'),
 (-10.686292605026608, '80s'),
 (-10.686292605026608, '84'),
 (-10.686292605026608, '85'),
 (-10.686292605026608, '88'),
 (-10.686292605026608, '90s'),
 (-10.686292605026608, '95'),
 (-10.686292605026608, 'abagnale'),
 (-10.686292605026608, 'abc'),
 (-10.686292605026608, 'abhors'),
 (-10.686292605026608, 'ability'),
 (-10.686292605026608, 'able'),
 (-10.686292605026608, 'abrasive'),
 (-10.686292605026608, 'abrupt'),
 (-10.686292605026608, 'absolute'),
 (-10.686292605026608, 'absolutely'),
 (-10.686292605026608, 'absorb'),
 (-10.686292605026608, 'abstract'),
 (-10.686292605026608, 'absurdities'),
 (-10.686292605026608, 'abundant'),
 (-10.686292605026608, 'academy'),
 (-10.686292605026608, 'accent'),
 (-10.686292605026608, 'accents'),
 (-10.686292605026608, 'accepting'),
 (-10.686292605026608, 'accident'),
 (-10.686292605026608, 'accomplished'),
 (-10.686292605026608, 'accurate'),
 (-10.686292605026608, 'accurately'),
 (-10.686292605026608, 'ache'),
 (-10.686292605026608, 'achievements'),
 (-10.686292605026608, 'achingly'),
 (-10.686292605026608, 'acknowledges'),
 (-10.686292605026608, 'acquired'),
 (-10.686292605026608, 'acted'),
 (-10.686292605026608, 'actions'),
 (-10.686292605026608, 'actress'),
 (-10.686292605026608, 'acts'),
 (-10.686292605026608, 'actual'),
 (-10.686292605026608, 'ad'),
 (-10.686292605026608, 'adams'),
 (-10.686292605026608, 'added'),
 (-10.686292605026608, 'addict'),
 (-10.686292605026608, 'adds'),
 (-10.686292605026608, 'admirably'),
 (-10.686292605026608, 'admission'),
 (-10.686292605026608, 'admit'),
 (-10.686292605026608, 'admittedly'),
 (-10.686292605026608, 'adolescent'),
 (-10.686292605026608, 'adrian'),
 (-10.686292605026608, 'adult'),
 (-10.686292605026608, 'adventures'),
 (-10.686292605026608, 'advice'),
 (-10.686292605026608, 'aesthetic'),
 (-10.686292605026608, 'aesthetics'),
 (-10.686292605026608, 'affair'),
 (-10.686292605026608, 'affect'),
 (-10.686292605026608, 'affected'),
 (-10.686292605026608, 'affirming'),
 (-10.686292605026608, 'afflicts'),
 (-10.686292605026608, 'aficionados'),
 (-10.686292605026608, 'afloat'),
 (-10.686292605026608, 'afterlife'),
 (-10.686292605026608, 'agenda'),
 (-10.686292605026608, 'agent'),
 (-10.686292605026608, 'ages'),
 (-10.686292605026608, 'aggrandizing'),
 (-10.686292605026608, 'agonizing'),
 (-10.686292605026608, 'ah'),
 (-10.686292605026608, 'ai'),
 (-10.686292605026608, 'aid'),
 (-10.686292605026608, 'aim'),
 (-10.686292605026608, 'aimed'),
 (-10.686292605026608, 'aimless'),
 (-10.686292605026608, 'al'),
 (-10.686292605026608, 'alabama'),
 (-10.686292605026608, 'alan'),
 (-10.686292605026608, 'album'),
 (-10.686292605026608, 'alert'),
 (-10.686292605026608, 'ali'),
 (-10.686292605026608, 'alien'),
 (-10.686292605026608, 'alienating'),
 (-10.686292605026608, 'alienation'),
 (-10.686292605026608, 'aliens'),
 (-10.686292605026608, 'alike'),
 (-10.686292605026608, 'allegory'),
 (-10.686292605026608, 'allen'),
 (-10.686292605026608, 'allow'),
 (-10.686292605026608, 'allowed'),
 (-10.686292605026608, 'allusions'),
 (-10.686292605026608, 'alternate'),
 (-10.686292605026608, 'alternative'),
 (-10.686292605026608, 'altman'),
 (-10.686292605026608, 'altogether'),
 (-10.686292605026608, 'amateur'),
 (-10.686292605026608, 'amazingly'),
 (-10.686292605026608, 'ambiguous'),
 (-10.686292605026608, 'ambition'),
 (-10.686292605026608, 'ambitious'),
 (-10.686292605026608, 'amble'),
 (-10.686292605026608, 'america'),
 (-10.686292605026608, 'american'),
 (-10.686292605026608, 'americans'),
 (-10.686292605026608, 'amiable'),
 (-10.686292605026608, 'amish'),
 (-10.686292605026608, 'amoral'),
 (-10.686292605026608, 'amounts'),
 (-10.686292605026608, 'analytical'),
 (-10.686292605026608, 'analyze'),
 (-10.686292605026608, 'ancient'),
 (-10.686292605026608, 'anew'),
 (-10.686292605026608, 'angels'),
 (-10.686292605026608, 'angle'),
 (-10.686292605026608, 'animation'),
 (-10.686292605026608, 'animatronic'),
 (-10.686292605026608, 'annals'),
 (-10.686292605026608, 'anne'),
 (-10.686292605026608, 'annex'),
 (-10.686292605026608, 'anniversary'),
 (-10.686292605026608, 'anomie'),
 (-10.686292605026608, 'anonymous'),
 (-10.686292605026608, 'answers'),
 (-10.686292605026608, 'anti'),
 (-10.686292605026608, 'anticipated'),
 (-10.686292605026608, 'antidote'),
 (-10.686292605026608, 'antiseptic'),
 (-10.686292605026608, 'antonio'),
 (-10.686292605026608, 'ants'),
 (-10.686292605026608, 'antwone'),
 (-10.686292605026608, 'anybody'),
 (-10.686292605026608, 'apart'),
 (-10.686292605026608, 'aplenty'),
 (-10.686292605026608, 'aplomb'),
 (-10.686292605026608, 'apollo'),
 (-10.686292605026608, 'appalling'),
 (-10.686292605026608, 'apparatus'),
 (-10.686292605026608, 'apparent'),
 (-10.686292605026608, 'apparently'),
 (-10.686292605026608, 'appeal'),
 (-10.686292605026608, 'appealing'),
 (-10.686292605026608, 'appeared'),
 (-10.686292605026608, 'appears'),
 (-10.686292605026608, 'applauded'),
 (-10.686292605026608, 'apply'),
 (-10.686292605026608, 'appointed'),
 (-10.686292605026608, 'appreciate'),
 (-10.686292605026608, 'appreciated'),
 (-10.686292605026608, 'approach'),
 (-10.686292605026608, 'appropriate'),
 (-10.686292605026608, 'ararat'),
 (-10.686292605026608, 'arbitrary'),
 (-10.686292605026608, 'arc'),
 (-10.686292605026608, 'arcane'),
 (-10.686292605026608, 'archibald'),
 (-10.686292605026608, 'architect'),
 (-10.686292605026608, 'archival'),
 (-10.686292605026608, 'ardently'),
 (-10.686292605026608, 'arduous'),
 (-10.686292605026608, 'area'),
 (-10.686292605026608, 'argentine'),
 (-10.686292605026608, 'argue'),
 (-10.686292605026608, 'arguments'),
 (-10.686292605026608, 'armageddon'),
 (-10.686292605026608, 'armed'),
 (-10.686292605026608, 'armenia'),
 (-10.686292605026608, 'arms'),
 (-10.686292605026608, 'array'),
 (-10.686292605026608, 'arrest'),
 (-10.686292605026608, 'arresting'),
 (-10.686292605026608, 'artful'),
 (-10.686292605026608, 'artfully'),
 (-10.686292605026608, 'articulate'),
 (-10.686292605026608, 'artifice'),
 (-10.686292605026608, 'artificial'),
 (-10.686292605026608, 'artistes'),
 (-10.686292605026608, 'artistry'),
 (-10.686292605026608, 'arts'),
 (-10.686292605026608, 'artsy'),
 (-10.686292605026608, 'ascends'),
 (-10.686292605026608, 'ash'),
 (-10.686292605026608, 'ashley'),
 (-10.686292605026608, 'asian'),
 (-10.686292605026608, 'ask'),
 (-10.686292605026608, 'asking'),
 (-10.686292605026608, 'asks'),
 (-10.686292605026608, 'asleep'),
 (-10.686292605026608, 'aspect'),
 (-10.686292605026608, 'aspects'),
 (-10.686292605026608, 'aspires'),
 (-10.686292605026608, 'assassin'),
 (-10.686292605026608, 'assembly'),
 (-10.686292605026608, 'assets'),
 (-10.686292605026608, 'associated'),
 (-10.686292605026608, 'association'),
 (-10.686292605026608, 'astonishingly'),
 (-10.686292605026608, 'athletes'),
 (-10.686292605026608, 'atmospheric'),
 (-10.686292605026608, 'attached'),
 (-10.686292605026608, 'attackers'),
 (-10.686292605026608, 'attempt'),
 (-10.686292605026608, 'attempts'),
 (-10.686292605026608, 'attention'),
 (-10.686292605026608, 'attitude'),
 (-10.686292605026608, 'attraction'),
 (-10.686292605026608, 'audiard'),
 (-10.686292605026608, 'audience'),
 (-10.686292605026608, 'audiences'),
 (-10.686292605026608, 'auschwitz'),
 (-10.686292605026608, 'austerity'),
 (-10.686292605026608, 'australia'),
 (-10.686292605026608, 'auteil'),
 (-10.686292605026608, 'auteur'),
 (-10.686292605026608, 'author'),
 (-10.686292605026608, 'auto'),
 (-10.686292605026608, 'averting'),
 (-10.686292605026608, 'awakening'),
 (-10.686292605026608, 'awards'),
 (-10.686292605026608, 'awfully'),
 (-10.686292605026608, 'awkward'),
 (-10.686292605026608, 'awkwardly'),
 (-10.686292605026608, 'awkwardness'),
 (-10.686292605026608, 'baby'),
 (-10.686292605026608, 'backdrops'),
 (-10.686292605026608, 'backlash'),
 (-10.686292605026608, 'bad'),
 (-10.686292605026608, 'badly'),
 (-10.686292605026608, 'badness'),
 (-10.686292605026608, 'baffled'),
 (-10.686292605026608, 'baffling'),
 (-10.686292605026608, 'bag'),
 (-10.686292605026608, 'bai'),
 (-10.686292605026608, 'baker'),
 (-10.686292605026608, 'balanced'),
 (-10.686292605026608, 'balances'),
 (-10.686292605026608, 'balancing'),
 (-10.686292605026608, 'balding'),
 (-10.686292605026608, 'banal'),
 (-10.686292605026608, 'banderas'),
 (-10.686292605026608, 'bank'),
 (-10.686292605026608, 'barbarism'),
 (-10.686292605026608, 'barbershop'),
 (-10.686292605026608, 'bare'),
 (-10.686292605026608, 'barely'),
 (-10.686292605026608, 'barf'),
 (-10.686292605026608, 'barney'),
 (-10.686292605026608, 'baroque'),
 (-10.686292605026608, 'barrel'),
 (-10.686292605026608, 'barrels'),
 (-10.686292605026608, 'barry'),
 (-10.686292605026608, 'barrymore'),
 (-10.686292605026608, 'bars'),
 (-10.686292605026608, 'bartleby'),
 (-10.686292605026608, 'bartlett'),
 (-10.686292605026608, 'base'),
 (-10.686292605026608, 'bates'),
 (-10.686292605026608, 'bathing'),
 (-10.686292605026608, 'bathtub'),
 (-10.686292605026608, 'battle'),
 (-10.686292605026608, 'battlefield'),
 (-10.686292605026608, 'beach'),
 (-10.686292605026608, 'bearable'),
 (-10.686292605026608, 'bears'),
 (-10.686292605026608, 'beast'),
 (-10.686292605026608, 'beat'),
 (-10.686292605026608, 'beautiful'),
 (-10.686292605026608, 'bed'),
 (-10.686292605026608, 'befallen'),
 (-10.686292605026608, 'begin'),
 (-10.686292605026608, 'begins'),
 (-10.686292605026608, 'begrudge'),
 (-10.686292605026608, 'beguiling'),
 (-10.686292605026608, 'behold'),
 (-10.686292605026608, 'belgian'),
 (-10.686292605026608, 'believing'),
 (-10.686292605026608, 'belly'),
 (-10.686292605026608, 'belt'),
 (-10.686292605026608, 'beneath'),
 (-10.686292605026608, 'benefit'),
 (-10.686292605026608, 'bent'),
 (-10.686292605026608, 'bernard'),
 (-10.686292605026608, 'best'),
 (-10.686292605026608, 'betrayal'),
 (-10.686292605026608, 'better'),
 (-10.686292605026608, 'bewilderingly'),
 (-10.686292605026608, 'bewitched'),
 (-10.686292605026608, 'bible'),
 (-10.686292605026608, 'bielinsky'),
 (-10.686292605026608, 'big'),
 (-10.686292605026608, 'bigger'),
 (-10.686292605026608, 'bilked'),
 (-10.686292605026608, 'billy'),
 (-10.686292605026608, 'bind'),
 (-10.686292605026608, 'bio'),
 (-10.686292605026608, 'biographical'),
 (-10.686292605026608, 'biography'),
 (-10.686292605026608, 'biopic'),
 (-10.686292605026608, 'birkenau'),
 (-10.686292605026608, 'birot'),
 (-10.686292605026608, 'bit'),
 (-10.686292605026608, 'bite'),
 (-10.686292605026608, 'bites'),
 (-10.686292605026608, 'biting'),
 (-10.686292605026608, 'bitter'),
 (-10.686292605026608, 'bittersweet'),
 (-10.686292605026608, 'bizarre'),
 (-10.686292605026608, 'blackout'),
 (-10.686292605026608, 'blade'),
 (-10.686292605026608, 'bladerunner'),
 (-10.686292605026608, 'blame'),
 (-10.686292605026608, 'bland'),
 (-10.686292605026608, 'blank'),
 (-10.686292605026608, 'blanket'),
 (-10.686292605026608, 'bleak'),
 (-10.686292605026608, 'blemishes'),
 (-10.686292605026608, 'blip'),
 (-10.686292605026608, 'blob'),
 (-10.686292605026608, 'block'),
 (-10.686292605026608, 'blockbuster'),
 (-10.686292605026608, 'blonde'),
 (-10.686292605026608, 'blood'),
 (-10.686292605026608, 'blooded'),
 (-10.686292605026608, 'bloodstream'),
 (-10.686292605026608, 'bloodsucker'),
 (-10.686292605026608, 'blowing'),
 (-10.686292605026608, 'blown'),
 (-10.686292605026608, 'blue'),
 (-10.686292605026608, 'blues'),
 (-10.686292605026608, 'bluescreen'),
 (-10.686292605026608, 'boasting'),
 (-10.686292605026608, 'boasts'),
 (-10.686292605026608, 'bob'),
 (-10.686292605026608, 'bodied'),
 (-10.686292605026608, 'bodily'),
 (-10.686292605026608, 'body'),
 (-10.686292605026608, 'bogs'),
 (-10.686292605026608, 'bogus'),
 (-10.686292605026608, 'bold'),
 (-10.686292605026608, 'bollywood'),
 (-10.686292605026608, 'bombastic'),
 (-10.686292605026608, 'bond'),
 (-10.686292605026608, 'books'),
 (-10.686292605026608, 'boom'),
 (-10.686292605026608, 'boomer'),
 (-10.686292605026608, 'boost'),
 (-10.686292605026608, 'boot'),
 (-10.686292605026608, 'boredom'),
 (-10.686292605026608, 'boring'),
 (-10.686292605026608, 'born'),
 (-10.686292605026608, 'borrows'),
 (-10.686292605026608, 'bother'),
 (-10.686292605026608, 'bouncing'),
 (-10.686292605026608, 'bowling'),
 (-10.686292605026608, 'boy'),
 (-10.686292605026608, 'bracing'),
 (-10.686292605026608, 'brain'),
 (-10.686292605026608, 'brainless'),
 (-10.686292605026608, 'brains'),
 (-10.686292605026608, 'brand'),
 (-10.686292605026608, 'bravado'),
 (-10.686292605026608, 'brave'),
 (-10.686292605026608, 'bravery'),
 (-10.686292605026608, 'bravura'),
 (-10.686292605026608, 'brawny'),
 (-10.686292605026608, 'breadth'),
 (-10.686292605026608, 'break'),
 (-10.686292605026608, 'breakdown'),
 (-10.686292605026608, 'breaks'),
 (-10.686292605026608, 'breath'),
 (-10.686292605026608, 'breathe'),
 (-10.686292605026608, 'breathing'),
 (-10.686292605026608, 'breathtaking'),
 (-10.686292605026608, 'breezy'),
 (-10.686292605026608, 'brew'),
 (-10.686292605026608, 'bride'),
 (-10.686292605026608, 'bridge'),
 (-10.686292605026608, 'bridget'),
 (-10.686292605026608, 'brief'),
 (-10.686292605026608, 'bright'),
 (-10.686292605026608, 'brightly'),
 (-10.686292605026608, 'brilliant'),
 (-10.686292605026608, 'bring'),
 (-10.686292605026608, 'bringing'),
 (-10.686292605026608, 'brings'),
 (-10.686292605026608, 'brio'),
 (-10.686292605026608, 'brisk'),
 (-10.686292605026608, 'brit'),
 (-10.686292605026608, 'british'),
 (-10.686292605026608, 'britney'),
 (-10.686292605026608, 'brits'),
 (-10.686292605026608, 'brittle'),
 (-10.686292605026608, 'broad'),
 (-10.686292605026608, 'bronx'),
 (-10.686292605026608, 'brooding'),
 (-10.686292605026608, 'bros'),
 (-10.686292605026608, 'brother'),
 (-10.686292605026608, 'brought'),
 (-10.686292605026608, 'bruce'),
 (-10.686292605026608, 'brusqueness'),
 (-10.686292605026608, 'brutal'),
 (-10.686292605026608, 'brutality'),
 (-10.686292605026608, 'brutally'),
 (-10.686292605026608, 'bubbly'),
 (-10.686292605026608, 'bucks'),
 (-10.686292605026608, 'budding'),
 (-10.686292605026608, 'buffs'),
 (-10.686292605026608, 'bull'),
 (-10.686292605026608, 'bumbling'),
 (-10.686292605026608, 'bump'),
 (-10.686292605026608, 'buoyant'),
 (-10.686292605026608, 'burger'),
 (-10.686292605026608, 'buried'),
 (-10.686292605026608, 'burkina'),
 (-10.686292605026608, 'burn'),
 (-10.686292605026608, 'burr'),
 (-10.686292605026608, 'burst'),
 (-10.686292605026608, 'business'),
 (-10.686292605026608, 'butler'),
 (-10.686292605026608, 'buy'),
 (-10.686292605026608, 'buzz'),
 (-10.686292605026608, 'byatt'),
 (-10.686292605026608, 'bygone'),
 (-10.686292605026608, 'cackles'),
 (-10.686292605026608, 'cage'),
 (-10.686292605026608, 'caine'),
 (-10.686292605026608, 'california'),
 (-10.686292605026608, 'callar'),
 (-10.686292605026608, 'called'),
 (-10.686292605026608, 'calls'),
 (-10.686292605026608, 'calm'),
 (-10.686292605026608, 'calories'),
 (-10.686292605026608, 'calvin'),
 (-10.686292605026608, 'camaraderie'),
 (-10.686292605026608, 'came'),
 (-10.686292605026608, 'camera'),
 (-10.686292605026608, 'camouflage'),
 (-10.686292605026608, 'camp'),
 (-10.686292605026608, 'campaign'),
 (-10.686292605026608, 'campus'),
 (-10.686292605026608, 'canned'),
 (-10.686292605026608, 'cannes'),
 (-10.686292605026608, 'cannon'),
 (-10.686292605026608, 'canny'),
 (-10.686292605026608, 'capable'),
 (-10.686292605026608, 'capacity'),
 (-10.686292605026608, 'caper'),
 (-10.686292605026608, 'capitalize'),
 (-10.686292605026608, 'captain'),
 (-10.686292605026608, 'captivating'),
 (-10.686292605026608, 'capture'),
 (-10.686292605026608, 'capturing'),
 (-10.686292605026608, 'car'),
 (-10.686292605026608, 'card'),
 (-10.686292605026608, 'care'),
 (-10.686292605026608, 'career'),
 (-10.686292605026608, 'careers'),
 (-10.686292605026608, 'carefully'),
 (-10.686292605026608, 'caricature'),
 (-10.686292605026608, 'caricatures'),
 (-10.686292605026608, 'caring'),
 (-10.686292605026608, 'carnage'),
 (-10.686292605026608, 'carol'),
 (-10.686292605026608, 'carpenter'),
 (-10.686292605026608, 'carried'),
 (-10.686292605026608, 'carries'),
 (-10.686292605026608, 'cartoonish'),
 (-10.686292605026608, 'carved'),
 (-10.686292605026608, 'carvey'),
 (-10.686292605026608, 'case'),
 (-10.686292605026608, 'cast'),
 (-10.686292605026608, 'castro'),
 (-10.686292605026608, 'cat'),
 (-10.686292605026608, 'catches'),
 (-10.686292605026608, 'catching'),
 (-10.686292605026608, 'catholic'),
 (-10.686292605026608, 'cedar'),
 (-10.686292605026608, 'celebrate'),
 (-10.686292605026608, 'celebrated'),
 (-10.686292605026608, 'celebrates'),
 (-10.686292605026608, 'celebration'),
 (-10.686292605026608, 'celebrity'),
 (-10.686292605026608, 'cell'),
 (-10.686292605026608, 'celluloid'),
 (-10.686292605026608, 'center'),
 (-10.686292605026608, 'centered'),
 (-10.686292605026608, 'centering'),
 (-10.686292605026608, 'central'),
 (-10.686292605026608, 'centuries'),
 (-10.686292605026608, 'century'),
 (-10.686292605026608, 'certain'),
 (-10.686292605026608, 'cgi'),
 (-10.686292605026608, 'chabrol'),
 (-10.686292605026608, 'chafing'),
 (-10.686292605026608, 'chair'),
 (-10.686292605026608, 'challenge'),
 (-10.686292605026608, 'challenges'),
 (-10.686292605026608, 'champion'),
 (-10.686292605026608, 'chan'),
 (-10.686292605026608, 'chance'),
 (-10.686292605026608, 'chances'),
 (-10.686292605026608, 'changing'),
 (-10.686292605026608, 'channel'),
 (-10.686292605026608, 'channeling'),
 (-10.686292605026608, 'chanukah'),
 (-10.686292605026608, 'chaplin'),
 (-10.686292605026608, 'characteristic'),
 (-10.686292605026608, 'characterization'),
 (-10.686292605026608, 'characterizations'),
 (-10.686292605026608, 'characters'),
 (-10.686292605026608, 'charged'),
 (-10.686292605026608, 'charismatic'),
 (-10.686292605026608, 'charitable'),
 (-10.686292605026608, 'charm'),
 (-10.686292605026608, 'charmer'),
 (-10.686292605026608, 'chateau'),
 (-10.686292605026608, 'cheatfully'),
 (-10.686292605026608, 'check'),
 (-10.686292605026608, 'checklist'),
 (-10.686292605026608, 'cheeky'),
 (-10.686292605026608, 'cheer'),
 (-10.686292605026608, 'cheering'),
 (-10.686292605026608, 'cheese'),
 (-10.686292605026608, 'cheesy'),
 (-10.686292605026608, 'chelsea'),
 (-10.686292605026608, 'chen'),
 (-10.686292605026608, 'cherish'),
 (-10.686292605026608, 'chest'),
 (-10.686292605026608, 'chicago'),
 (-10.686292605026608, 'chick'),
 (-10.686292605026608, 'chicken'),
 (-10.686292605026608, 'chief'),
 (-10.686292605026608, 'childlike'),
 (-10.686292605026608, 'chilling'),
 (-10.686292605026608, 'chilly'),
 (-10.686292605026608, 'chimes'),
 (-10.686292605026608, 'china'),
 (-10.686292605026608, 'chips'),
 (-10.686292605026608, 'choice'),
 (-10.686292605026608, 'choices'),
 (-10.686292605026608, 'chomp'),
 (-10.686292605026608, 'choose'),
 (-10.686292605026608, 'chooses'),
 (-10.686292605026608, 'choppy'),
 (-10.686292605026608, 'chops'),
 (-10.686292605026608, 'chopsocky'),
 (-10.686292605026608, 'chosen'),
 (-10.686292605026608, 'chou'),
 (-10.686292605026608, 'chris'),
 (-10.686292605026608, 'christian'),
 (-10.686292605026608, 'christmas'),
 (-10.686292605026608, 'chronicles'),
 (-10.686292605026608, 'chuck'),
 (-10.686292605026608, 'cinderella'),
 (-10.686292605026608, 'cinematic'),
 (-10.686292605026608, 'cinematically'),
 (-10.686292605026608, 'cipher'),
 (-10.686292605026608, 'circuit'),
 (-10.686292605026608, 'circumstances'),
 (-10.686292605026608, 'cities'),
 (-10.686292605026608, 'city'),
 (-10.686292605026608, 'civic'),
 (-10.686292605026608, 'civil'),
 (-10.686292605026608, 'clad'),
 (-10.686292605026608, 'claims'),
 (-10.686292605026608, 'clashing'),
 (-10.686292605026608, 'class'),
 (-10.686292605026608, 'classic'),
 (-10.686292605026608, 'claude'),
 (-10.686292605026608, 'clause'),
 (-10.686292605026608, 'clean'),
 (-10.686292605026608, 'cleaner'),
 (-10.686292605026608, 'cleavage'),
 (-10.686292605026608, 'cleverly'),
 (-10.686292605026608, 'cleverness'),
 (-10.686292605026608, 'cliche'),
 (-10.686292605026608, 'cliched'),
 (-10.686292605026608, 'clients'),
 (-10.686292605026608, 'climate'),
 (-10.686292605026608, 'clinic'),
 (-10.686292605026608, 'clinical'),
 (-10.686292605026608, 'clockstoppers'),
 (-10.686292605026608, 'clone'),
 (-10.686292605026608, 'clooney'),
 (-10.686292605026608, 'closed'),
 (-10.686292605026608, 'closely'),
 (-10.686292605026608, 'closer'),
 (-10.686292605026608, 'clothes'),
 (-10.686292605026608, 'clubs'),
 (-10.686292605026608, 'clue'),
 (-10.686292605026608, 'clumsily'),
 (-10.686292605026608, 'clumsy'),
 (-10.686292605026608, 'clunky'),
 (-10.686292605026608, 'clutching'),
 (-10.686292605026608, 'cobbled'),
 (-10.686292605026608, 'cocky'),
 (-10.686292605026608, 'code'),
 (-10.686292605026608, 'codswallop'),
 (-10.686292605026608, 'coen'),
 (-10.686292605026608, 'coffee'),
 (-10.686292605026608, 'cogent'),
 (-10.686292605026608, 'cold'),
 (-10.686292605026608, 'collapses'),
 (-10.686292605026608, 'college'),
 (-10.686292605026608, 'collide'),
 (-10.686292605026608, 'collision'),
 (-10.686292605026608, 'color'),
 (-10.686292605026608, 'colorful'),
 (-10.686292605026608, 'colors'),
 (-10.686292605026608, 'colour'),
 (-10.686292605026608, 'columbia'),
 (-10.686292605026608, 'column'),
 (-10.686292605026608, 'com'),
 (-10.686292605026608, 'coma'),
 (-10.686292605026608, 'combination'),
 (-10.686292605026608, 'combined'),
 (-10.686292605026608, 'combines'),
 (-10.686292605026608, 'combustible'),
 (-10.686292605026608, 'come'),
 (-10.686292605026608, 'comedian'),
 (-10.686292605026608, 'comedic'),
 (-10.686292605026608, 'comedy'),
 (-10.686292605026608, 'comes'),
 (-10.686292605026608, 'comfort'),
 (-10.686292605026608, 'comfortable'),
 (-10.686292605026608, 'comic'),
 (-10.686292605026608, 'comics'),
 (-10.686292605026608, 'commend'),
 (-10.686292605026608, 'comments'),
 (-10.686292605026608, 'common'),
 (-10.686292605026608, 'community'),
 (-10.686292605026608, 'companion'),
 (-10.686292605026608, 'company'),
 (-10.686292605026608, 'compare'),
 (-10.686292605026608, 'compared'),
 (-10.686292605026608, 'compelling'),
 (-10.686292605026608, 'compellingly'),
 (-10.686292605026608, 'compendium'),
 (-10.686292605026608, 'compensate'),
 (-10.686292605026608, 'competence'),
 (-10.686292605026608, 'competent'),
 (-10.686292605026608, 'competition'),
 (-10.686292605026608, 'complaint'),
 (-10.686292605026608, 'complexities'),
 (-10.686292605026608, 'complexity'),
 (-10.686292605026608, 'complicated'),
 (-10.686292605026608, 'comprehend'),
 (-10.686292605026608, 'comprehension'),
 (-10.686292605026608, 'compromise'),
 (-10.686292605026608, 'computer'),
 (-10.686292605026608, 'conceits'),
 (-10.686292605026608, 'concept'),
 (-10.686292605026608, 'conception'),
 (-10.686292605026608, 'concern'),
 (-10.686292605026608, 'concerned'),
 (-10.686292605026608, 'concession'),
 (-10.686292605026608, 'conclusion'),
 (-10.686292605026608, 'concocted'),
 (-10.686292605026608, 'condensed'),
 (-10.686292605026608, 'condition'),
 (-10.686292605026608, 'conditioning'),
 (-10.686292605026608, 'conditions'),
 (-10.686292605026608, 'conduct'),
 (-10.686292605026608, 'confessions'),
 (-10.686292605026608, 'confidence'),
 (-10.686292605026608, 'confident'),
 (-10.686292605026608, 'confirms'),
 (-10.686292605026608, 'conflicted'),
 (-10.686292605026608, 'confront'),
 (-10.686292605026608, 'confused'),
 (-10.686292605026608, 'confusing'),
 (-10.686292605026608, 'congratulation'),
 (-10.686292605026608, 'conjured'),
 (-10.686292605026608, 'connect'),
 (-10.686292605026608, 'connected'),
 (-10.686292605026608, 'connections'),
 (-10.686292605026608, 'conquer'),
 (-10.686292605026608, 'conscious'),
 (-10.686292605026608, 'consciousness'),
 (-10.686292605026608, 'consequences'),
 (-10.686292605026608, 'consider'),
 (-10.686292605026608, 'considerable'),
 (-10.686292605026608, 'consideration'),
 (-10.686292605026608, 'considered'),
 (-10.686292605026608, 'considering'),
 (-10.686292605026608, 'consistent'),
 (-10.686292605026608, 'consolation'),
 (-10.686292605026608, 'conspiracy'),
 (-10.686292605026608, 'constant'),
 (-10.686292605026608, 'constantly'),
 (-10.686292605026608, 'construct'),
 (-10.686292605026608, 'constructed'),
 (-10.686292605026608, 'construction'),
 (-10.686292605026608, 'constructs'),
 (-10.686292605026608, 'consuming'),
 (-10.686292605026608, 'contact'),
 (-10.686292605026608, 'contained'),
 (-10.686292605026608, 'contemplation'),
 (-10.686292605026608, 'contemporaries'),
 (-10.686292605026608, 'contemporary'),
 (-10.686292605026608, 'contemptible'),
 (-10.686292605026608, 'contenders'),
 (-10.686292605026608, 'content'),
 (-10.686292605026608, 'contest'),
 (-10.686292605026608, 'contradiction'),
 (-10.686292605026608, 'contradictory'),
 (-10.686292605026608, 'convenient'),
 (-10.686292605026608, 'convention'),
 (-10.686292605026608, 'conversation'),
 (-10.686292605026608, 'conversations'),
 (-10.686292605026608, 'conveying'),
 (-10.686292605026608, 'conviction'),
 (-10.686292605026608, 'convictions'),
 (-10.686292605026608, 'convince'),
 (-10.686292605026608, 'convincing'),
 (-10.686292605026608, 'cooler'),
 (-10.686292605026608, 'cop'),
 (-10.686292605026608, 'copy'),
 (-10.686292605026608, 'copycat'),
 (-10.686292605026608, 'corpse'),
 (-10.686292605026608, 'costly'),
 (-10.686292605026608, 'costumes'),
 (-10.686292605026608, 'costuming'),
 (-10.686292605026608, 'count'),
 (-10.686292605026608, 'counterparts'),
 (-10.686292605026608, 'countless'),
 (-10.686292605026608, 'country'),
 (-10.686292605026608, 'couple'),
 (-10.686292605026608, 'courage'),
 (-10.686292605026608, 'course'),
 (-10.686292605026608, 'cover'),
 (-10.686292605026608, 'cox'),
 (-10.686292605026608, 'crack'),
 (-10.686292605026608, 'cracked'),
 (-10.686292605026608, 'cracker'),
 (-10.686292605026608, 'cradles'),
 (-10.686292605026608, 'craft'),
 (-10.686292605026608, 'crafted'),
 (-10.686292605026608, 'crane'),
 (-10.686292605026608, 'crashing'),
 (-10.686292605026608, 'crass'),
 (-10.686292605026608, 'crassly'),
 (-10.686292605026608, 'craven'),
 (-10.686292605026608, 'crazy'),
 (-10.686292605026608, 'creating'),
 (-10.686292605026608, 'creation'),
 (-10.686292605026608, 'creativity'),
 (-10.686292605026608, 'creature'),
 (-10.686292605026608, 'creatures'),
 (-10.686292605026608, 'credibility'),
 (-10.686292605026608, 'credible'),
 (-10.686292605026608, 'credits'),
 (-10.686292605026608, 'creepy'),
 (-10.686292605026608, 'cricket'),
 (-10.686292605026608, 'crime'),
 (-10.686292605026608, 'crimes'),
 (-10.686292605026608, 'criminal'),
 (-10.686292605026608, 'crippled'),
 (-10.686292605026608, 'crises'),
 (-10.686292605026608, 'crisis'),
 (-10.686292605026608, 'critic'),
 (-10.686292605026608, 'critical'),
 (-10.686292605026608, 'critics'),
 (-10.686292605026608, 'critique'),
 (-10.686292605026608, 'crosses'),
 (-10.686292605026608, 'crossroads'),
 (-10.686292605026608, 'crowded'),
 (-10.686292605026608, 'crucial'),
 (-10.686292605026608, 'cruelty'),
 (-10.686292605026608, 'crush'),
 (-10.686292605026608, 'crushingly'),
 (-10.686292605026608, 'cuban'),
 (-10.686292605026608, 'cuisine'),
 (-10.686292605026608, 'culkin'),
 (-10.686292605026608, 'cult'),
 (-10.686292605026608, 'cultural'),
 (-10.686292605026608, 'curdling'),
 (-10.686292605026608, 'cure'),
 (-10.686292605026608, 'curiously'),
 (-10.686292605026608, 'current'),
 (-10.686292605026608, 'curse'),
 (-10.686292605026608, 'curves'),
 (-10.686292605026608, 'cut'),
 (-10.686292605026608, 'cuts'),
 (-10.686292605026608, 'cyber'),
 (-10.686292605026608, 'cynical'),
 (-10.686292605026608, 'cynicism'),
 (-10.686292605026608, 'dahmer'),
 (-10.686292605026608, 'damaged'),
 (-10.686292605026608, 'damme'),
 (-10.686292605026608, 'damning'),
 (-10.686292605026608, 'damon'),
 (-10.686292605026608, 'dampened'),
 (-10.686292605026608, 'dana'),
 (-10.686292605026608, 'danger'),
 (-10.686292605026608, 'dangerous'),
 (-10.686292605026608, 'dangerously'),
 (-10.686292605026608, 'dante'),
 (-10.686292605026608, 'darkness'),
 (-10.686292605026608, 'darling'),
 (-10.686292605026608, 'das'),
 (-10.686292605026608, 'dash'),
 (-10.686292605026608, 'dass'),
 (-10.686292605026608, 'daughters'),
 (-10.686292605026608, 'dawdle'),
 (-10.686292605026608, 'dawn'),
 (-10.686292605026608, 'dawns'),
 (-10.686292605026608, 'dawson'),
 (-10.686292605026608, 'daytime'),
 (-10.686292605026608, 'dazzling'),
 (-10.686292605026608, 'dead'),
 (-10.686292605026608, 'deadly'),
 (-10.686292605026608, 'deadpan'),
 (-10.686292605026608, 'deafening'),
 (-10.686292605026608, 'dean'),
 (-10.686292605026608, 'debate'),
 (-10.686292605026608, 'debated'),
 (-10.686292605026608, 'decade'),
 (-10.686292605026608, 'decency'),
 (-10.686292605026608, 'decent'),
 (-10.686292605026608, 'deception'),
 (-10.686292605026608, 'deceptions'),
 (-10.686292605026608, 'decibel'),
 (-10.686292605026608, 'decide'),
 (-10.686292605026608, 'decided'),
 (-10.686292605026608, 'decidedly'),
 (-10.686292605026608, 'decides'),
 (-10.686292605026608, 'decision'),
 (-10.686292605026608, 'decomposition'),
 (-10.686292605026608, 'deeds'),
 (-10.686292605026608, 'deep'),
 (-10.686292605026608, 'deeply'),
 (-10.686292605026608, 'defecates'),
 (-10.686292605026608, 'defense'),
 (-10.686292605026608, 'defiance'),
 (-10.686292605026608, 'defies'),
 (-10.686292605026608, 'defines'),
 (-10.686292605026608, 'degree'),
 (-10.686292605026608, 'del'),
 (-10.686292605026608, 'deliberately'),
 (-10.686292605026608, 'delicate'),
 (-10.686292605026608, 'delicately'),
 (-10.686292605026608, 'delight'),
 (-10.686292605026608, 'delightfully'),
 (-10.686292605026608, 'delights'),
 (-10.686292605026608, 'delinquent'),
 (-10.686292605026608, 'deliver'),
 (-10.686292605026608, 'delivered'),
 (-10.686292605026608, 'delivering'),
 (-10.686292605026608, 'delivers'),
 (-10.686292605026608, 'delivery'),
 (-10.686292605026608, 'demanding'),
 (-10.686292605026608, 'demands'),
 (-10.686292605026608, 'demented'),
 (-10.686292605026608, 'demme'),
 (-10.686292605026608, 'demographic'),
 (-10.686292605026608, 'demons'),
 (-10.686292605026608, 'denial'),
 (-10.686292605026608, 'denied'),
 (-10.686292605026608, 'denizens'),
 (-10.686292605026608, 'department'),
 (-10.686292605026608, 'departure'),
 (-10.686292605026608, 'dependence'),
 (-10.686292605026608, 'depraved'),
 (-10.686292605026608, 'deprecating'),
 (-10.686292605026608, 'depressed'),
 (-10.686292605026608, 'derivative'),
 (-10.686292605026608, 'derrida'),
 (-10.686292605026608, 'described'),
 (-10.686292605026608, 'deserve'),
 (-10.686292605026608, 'deserved'),
 (-10.686292605026608, 'deserves'),
 (-10.686292605026608, 'deserving'),
 (-10.686292605026608, 'desiccated'),
 (-10.686292605026608, 'designed'),
 (-10.686292605026608, 'desperate'),
 (-10.686292605026608, 'destined'),
 (-10.686292605026608, 'destiny'),
 (-10.686292605026608, 'destroy'),
 (-10.686292605026608, 'destructive'),
 (-10.686292605026608, 'determined'),
 (-10.686292605026608, 'deuces'),
 (-10.686292605026608, 'develop'),
 (-10.686292605026608, 'developed'),
 (-10.686292605026608, 'developing'),
 (-10.686292605026608, 'development'),
 (-10.686292605026608, 'developments'),
 (-10.686292605026608, 'devoid'),
 (-10.686292605026608, 'devotees'),
 (-10.686292605026608, 'diabolical'),
 (-10.686292605026608, 'dialogue'),
 (-10.686292605026608, 'diaries'),
 (-10.686292605026608, 'diary'),
 (-10.686292605026608, 'dick'),
 (-10.686292605026608, 'dickens'),
 (-10.686292605026608, 'die'),
 (-10.686292605026608, 'diesel'),
 (-10.686292605026608, 'differences'),
 (-10.686292605026608, 'dignity'),
 (-10.686292605026608, 'dim'),
 (-10.686292605026608, 'dimension'),
 (-10.686292605026608, 'dimensional'),
 (-10.686292605026608, 'dimensions'),
 (-10.686292605026608, 'dip'),
 (-10.686292605026608, 'dips'),
 (-10.686292605026608, 'direct'),
 (-10.686292605026608, 'directing'),
 (-10.686292605026608, 'directions'),
 (-10.686292605026608, 'director'),
 (-10.686292605026608, 'directorial'),
 (-10.686292605026608, 'directors'),
 (-10.686292605026608, 'directs'),
 (-10.686292605026608, 'dirty'),
 (-10.686292605026608, 'disaffected'),
 (-10.686292605026608, 'disappoint'),
 (-10.686292605026608, 'disappointed'),
 (-10.686292605026608, 'discomfort'),
 (-10.686292605026608, 'discordant'),
 (-10.686292605026608, 'discouraging'),
 (-10.686292605026608, 'discourse'),
 (-10.686292605026608, 'discover'),
 (-10.686292605026608, 'discoveries'),
 (-10.686292605026608, 'discussed'),
 (-10.686292605026608, 'discussion'),
 (-10.686292605026608, 'disease'),
 (-10.686292605026608, 'disguise'),
 (-10.686292605026608, 'disguised'),
 (-10.686292605026608, 'disgusting'),
 (-10.686292605026608, 'disingenuous'),
 (-10.686292605026608, 'disintegrating'),
 (-10.686292605026608, 'dismay'),
 (-10.686292605026608, 'dismiss'),
 (-10.686292605026608, 'disney'),
 (-10.686292605026608, 'displays'),
 (-10.686292605026608, 'disposable'),
 (-10.686292605026608, 'disregard'),
 (-10.686292605026608, 'distance'),
 (-10.686292605026608, 'distasteful'),
 (-10.686292605026608, 'distinct'),
 (-10.686292605026608, 'distinctive'),
 (-10.686292605026608, 'distinctly'),
 (-10.686292605026608, 'distinguish'),
 (-10.686292605026608, 'distinguished'),
 (-10.686292605026608, 'distort'),
 (-10.686292605026608, 'distraction'),
 (-10.686292605026608, 'disturbed'),
 (-10.686292605026608, 'disturbing'),
 (-10.686292605026608, 'ditsy'),
 (-10.686292605026608, 'diverting'),
 (-10.686292605026608, 'documentary'),
 (-10.686292605026608, 'dog'),
 (-10.686292605026608, 'dogma'),
 (-10.686292605026608, 'dogmatism'),
 (-10.686292605026608, 'dogs'),
 (-10.686292605026608, 'domestic'),
 (-10.686292605026608, 'dominated'),
 (-10.686292605026608, 'domination'),
 (-10.686292605026608, 'donald'),
 (-10.686292605026608, 'dong'),
 (-10.686292605026608, 'doo'),
 (-10.686292605026608, 'door'),
 (-10.686292605026608, 'dopey'),
 (-10.686292605026608, 'dose'),
 (-10.686292605026608, 'dots'),
 (-10.686292605026608, 'double'),
 (-10.686292605026608, 'douglas'),
 (-10.686292605026608, 'dour'),
 (-10.686292605026608, 'dover'),
 (-10.686292605026608, 'downbeat'),
 (-10.686292605026608, 'downright'),
 (-10.686292605026608, 'dozen'),
 (-10.686292605026608, 'dozens'),
 (-10.686292605026608, 'drab'),
 (-10.686292605026608, 'dragon'),
 (-10.686292605026608, 'dragonfly'),
 (-10.686292605026608, 'dragons'),
 (-10.686292605026608, 'dramatic'),
 (-10.686292605026608, 'dramatically'),
 (-10.686292605026608, 'dramedy'),
 (-10.686292605026608, 'draw'),
 ...]
In [25]:
# calculate log ratio of conditional probs

# In this exercise you will calculate the log ratio 
# between conditional probs in the "very negative" category
# and conditional probs in the "very positive" category,
# and then sort and print out the top and bottom 10 words

# the conditional probs for the "very negative" category is stored in nb_clf.feature_log_prob_[0]
# the conditional probs for the "very positive" category is stored in nb_clf.feature_log_prob_[4]

# You can consult with similar code in week 4's sample script on feature weighting
# Note that in sklearn's MultinomialNB the conditional probs have been converted to log values.

# Your code starts here

very_negative = sorted(zip(nb_clf.feature_log_prob_[0], unigram_count_vectorizer.get_feature_names()))
very_positive = sorted(zip(nb_clf.feature_log_prob_[4], unigram_count_vectorizer.get_feature_names()))

very_negative[:10]
very_positive[:10]
# Your code ends here

'''
[(-4.6685160302515563, 'worst'), (-4.1676048635427438, 'bad'), (-3.9753688496916109, 'stupid'), (-3.8602995199068237, 'worse'), (-3.7576453658467397, 'contrived'), (-3.7576453658467397, 'unfunny'), (-3.7302463916586257, 'awful'), (-3.7020755146919289, 'poorly'), (-3.6432350146689956, 'waste'), (-3.5479248348646717, 'pathetic')]
[(3.5668446135017922, 'rich'), (3.6374621807157457, 'wonderful'), (3.8045162653789113, 'excellent'), (3.8422565933617587, 'gorgeous'), (3.8786242375326339, 'touching'), (3.9308099907032039, 'solid'), (3.9641464109707956, 'powerful'), (4.027659816693121, 'beautifully'), (4.1437319879458752, 'beautiful'), (4.2352991814713654, 'moving')]
'''
Out[25]:
"\n[(-4.6685160302515563, 'worst'), (-4.1676048635427438, 'bad'), (-3.9753688496916109, 'stupid'), (-3.8602995199068237, 'worse'), (-3.7576453658467397, 'contrived'), (-3.7576453658467397, 'unfunny'), (-3.7302463916586257, 'awful'), (-3.7020755146919289, 'poorly'), (-3.6432350146689956, 'waste'), (-3.5479248348646717, 'pathetic')]\n[(3.5668446135017922, 'rich'), (3.6374621807157457, 'wonderful'), (3.8045162653789113, 'excellent'), (3.8422565933617587, 'gorgeous'), (3.8786242375326339, 'touching'), (3.9308099907032039, 'solid'), (3.9641464109707956, 'powerful'), (4.027659816693121, 'beautifully'), (4.1437319879458752, 'beautiful'), (4.2352991814713654, 'moving')]\n"
In [ ]:
 

Sample output for print(log_ratios[0])

-0.838009538739

Step 5: Test the MNB classifier

In [26]:
# test the classifier on the test data set, print accuracy score

nb_clf.score(X_test_vec,y_test)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-26-fe17fba8ea5c> in <module>
      1 # test the classifier on the test data set, print accuracy score
      2 
----> 3 nb_clf.score(X_test_vec,y_test)

/usr/local/lib/python3.7/site-packages/sklearn/base.py in score(self, X, y, sample_weight)
    355         """
    356         from .metrics import accuracy_score
--> 357         return accuracy_score(y, self.predict(X), sample_weight=sample_weight)
    358 
    359 

/usr/local/lib/python3.7/site-packages/sklearn/naive_bayes.py in predict(self, X)
     63             Predicted target values for X
     64         """
---> 65         jll = self._joint_log_likelihood(X)
     66         return self.classes_[np.argmax(jll, axis=1)]
     67 

/usr/local/lib/python3.7/site-packages/sklearn/naive_bayes.py in _joint_log_likelihood(self, X)
    735 
    736         X = check_array(X, accept_sparse='csr')
--> 737         return (safe_sparse_dot(X, self.feature_log_prob_.T) +
    738                 self.class_log_prior_)
    739 

/usr/local/lib/python3.7/site-packages/sklearn/utils/extmath.py in safe_sparse_dot(a, b, dense_output)
    135     """
    136     if sparse.issparse(a) or sparse.issparse(b):
--> 137         ret = a * b
    138         if dense_output and hasattr(ret, "toarray"):
    139             ret = ret.toarray()

/usr/local/lib/python3.7/site-packages/scipy/sparse/base.py in __mul__(self, other)
    515 
    516             if other.shape[0] != self.shape[1]:
--> 517                 raise ValueError('dimension mismatch')
    518 
    519             result = self._mul_multivector(np.asarray(other))

ValueError: dimension mismatch
In [27]:
# print confusion matrix (row: ground truth; col: prediction)

from sklearn.metrics import confusion_matrix
y_pred = nb_clf.fit(X_train_vec, y_train).predict(X_test_vec)
cm=confusion_matrix(y_test, y_pred, labels=[0,1,2,3,4])
print(cm)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-27-4f3817497aee> in <module>
      2 
      3 from sklearn.metrics import confusion_matrix
----> 4 y_pred = nb_clf.fit(X_train_vec, y_train).predict(X_test_vec)
      5 cm=confusion_matrix(y_test, y_pred, labels=[0,1,2,3,4])
      6 print(cm)

/usr/local/lib/python3.7/site-packages/sklearn/naive_bayes.py in predict(self, X)
     63             Predicted target values for X
     64         """
---> 65         jll = self._joint_log_likelihood(X)
     66         return self.classes_[np.argmax(jll, axis=1)]
     67 

/usr/local/lib/python3.7/site-packages/sklearn/naive_bayes.py in _joint_log_likelihood(self, X)
    735 
    736         X = check_array(X, accept_sparse='csr')
--> 737         return (safe_sparse_dot(X, self.feature_log_prob_.T) +
    738                 self.class_log_prior_)
    739 

/usr/local/lib/python3.7/site-packages/sklearn/utils/extmath.py in safe_sparse_dot(a, b, dense_output)
    135     """
    136     if sparse.issparse(a) or sparse.issparse(b):
--> 137         ret = a * b
    138         if dense_output and hasattr(ret, "toarray"):
    139             ret = ret.toarray()

/usr/local/lib/python3.7/site-packages/scipy/sparse/base.py in __mul__(self, other)
    515 
    516             if other.shape[0] != self.shape[1]:
--> 517                 raise ValueError('dimension mismatch')
    518 
    519             result = self._mul_multivector(np.asarray(other))

ValueError: dimension mismatch
In [28]:
# print classification report

from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
print(precision_score(y_test, y_pred, average=None))
print(recall_score(y_test, y_pred, average=None))

from sklearn.metrics import classification_report
target_names = ['0','1','2','3','4']
print(classification_report(y_test, y_pred, target_names=target_names))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-28-306b6b579f6c> in <module>
      3 from sklearn.metrics import precision_score
      4 from sklearn.metrics import recall_score
----> 5 print(precision_score(y_test, y_pred, average=None))
      6 print(recall_score(y_test, y_pred, average=None))
      7 

NameError: name 'y_pred' is not defined

Step 5.1 Interpret the prediction result

In [38]:
## find the calculated posterior probability
posterior_probs = nb_clf.predict_proba(X_test_vec)

## find the posterior probabilities for the first test example
print(posterior_probs[0])

# find the category prediction for the first test example
y_pred = nb_clf.predict(X_test_vec)
print(y_pred[0])

# check the actual label for the first test example
print(y_test[0])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-38-62d98beccd68> in <module>
      1 ## find the calculated posterior probability
----> 2 posterior_probs = nb_clf.predict_proba(X_test_vec)
      3 
      4 ## find the posterior probabilities for the first test example
      5 print(posterior_probs[0])

NameError: name 'X_test_vec' is not defined

sample output array([ 0.06434628 0.34275846 0.50433091 0.07276319 0.01580115]

Because the posterior probability for category 2 (neutral) is the greatest, 0.50, the prediction should be "2". Because the actual label is also "2", this is a correct prediction

Step 5.2 Error Analysis

In [39]:
# print out specific type of error for further analysis

# print out the very positive examples that are mistakenly predicted as negative
# according to the confusion matrix, there should be 53 such examples
# note if you use a different vectorizer option, your result might be different

err_cnt = 0
for i in range(0, len(y_test)):
    if(y_test[i]==4 and y_pred[i]==1):
        print(X_test[i])
        err_cnt = err_cnt+1
print("errors:", err_cnt)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-39-cb6eee7e8ea3> in <module>
      7 err_cnt = 0
      8 for i in range(0, len(y_test)):
----> 9     if(y_test[i]==4 and y_pred[i]==1):
     10         print(X_test[i])
     11         err_cnt = err_cnt+1

NameError: name 'y_pred' is not defined

Exercise D

In [40]:
# Can you find linguistic patterns in the above errors? 
# What kind of very positive examples were mistakenly predicted as negative?

# Can you write code to print out the errors that very negative examples were mistakenly predicted as very positive?
# Can you find lingustic patterns for this kind of errors?
# Based on the above error analysis, what suggestions would you give to improve the current model?

# Your code starts here
err_cnt = 0
for i in range(0, len(y_test)):
    if(y_test[i]==1 and y_pred[i]==4):
        print(X_test[i])
        err_cnt = err_cnt+1
print("errors:", err_cnt)
# Your code ends here

'''
this is the opposite of a truly magical movie .
achieves the remarkable feat of squandering a topnotch foursome of actors
a deeply unpleasant experience
hugely overwritten
is not Edward Burns ' best film
Once the expectation of laughter has been quashed by whatever obscenity is at hand , even the funniest idea is n't funny .
is a deeply unpleasant experience .
is hugely overwritten ,
is the opposite of a truly magical movie .
to this shocking testament to anti-Semitism and neo-fascism
is about as humorous as watching your favorite pet get buried alive
errors: 11
'''
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-40-f76b378b2b1f> in <module>
      9 err_cnt = 0
     10 for i in range(0, len(y_test)):
---> 11     if(y_test[i]==1 and y_pred[i]==4):
     12         print(X_test[i])
     13         err_cnt = err_cnt+1

NameError: name 'y_pred' is not defined

Step 6: write the prediction output to file

In [34]:
y_pred=nb_clf.predict(X_test_vec)
output = open('prediction_output_2.csv', 'w')
for x, value in enumerate(y_pred):
    output.write(str(value) + '\n') 
output.close()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-34-74c28b38f3cd> in <module>
----> 1 y_pred=nb_clf.predict(X_test_vec)
      2 output = open('prediction_output_2.csv', 'w')
      3 for x, value in enumerate(y_pred):
      4     output.write(str(value) + '\n')
      5 output.close()

NameError: name 'X_test_vec' is not defined

Step 6.1 Prepare submission to Kaggle sentiment classification competition

In [41]:
########## submit to Kaggle submission

# we are still using the model trained on 60% of the training data
# you can re-train the model on the entire data set 
#   and use the new model to predict the Kaggle test data
# below is sample code for using a trained model to predict Kaggle test data 
#    and format the prediction output for Kaggle submission

# read in the test data
# kaggle-sentiment/train.tsv
kaggle_test=p.read_csv("kaggle-sentiment/test.tsv", delimiter='\t') 

# preserve the id column of the test examples
kaggle_ids=kaggle_test['PhraseId'].values

# read in the text content of the examples
kaggle_X_test=kaggle_test['Phrase'].values

# vectorize the test examples using the vocabulary fitted from the 60% training data
kaggle_X_test_vec=unigram_count_vectorizer.transform(kaggle_X_test)

# predict using the NB classifier that we built
kaggle_pred=nb_clf.fit(X_train_vec, y_train).predict(kaggle_X_test_vec)

# combine the test example ids with their predictions
kaggle_submission=zip(kaggle_ids, kaggle_pred)

# prepare output file
outf=open('kaggle_submission_2.csv', 'w')

# write header
outf.write('PhraseId,Sentiment\n')

# write predictions with ids to the output file
for x, value in enumerate(kaggle_submission): outf.write(str(value[0]) + ',' + str(value[1]) + '\n')

# close the output file
outf.close()
---------------------------------------------------------------------------
NotFittedError                            Traceback (most recent call last)
<ipython-input-41-ff984db0c3d0> in <module>
     18 
     19 # vectorize the test examples using the vocabulary fitted from the 60% training data
---> 20 kaggle_X_test_vec=unigram_count_vectorizer.transform(kaggle_X_test)
     21 
     22 # predict using the NB classifier that we built

/usr/local/lib/python3.7/site-packages/sklearn/feature_extraction/text.py in transform(self, raw_documents)
   1107             self._validate_vocabulary()
   1108 
-> 1109         self._check_vocabulary()
   1110 
   1111         # use the same matrix-building strategy as fit_transform

/usr/local/lib/python3.7/site-packages/sklearn/feature_extraction/text.py in _check_vocabulary(self)
    387         """Check if vocabulary is empty or missing (not fit-ed)"""
    388         msg = "%(name)s - Vocabulary wasn't fitted."
--> 389         check_is_fitted(self, 'vocabulary_', msg=msg),
    390 
    391         if len(self.vocabulary_) == 0:

/usr/local/lib/python3.7/site-packages/sklearn/utils/validation.py in check_is_fitted(estimator, attributes, msg, all_or_any)
    912 
    913     if not all_or_any([hasattr(estimator, attr) for attr in attributes]):
--> 914         raise NotFittedError(msg % {'name': type(estimator).__name__})
    915 
    916 

NotFittedError: CountVectorizer - Vocabulary wasn't fitted.
In [42]:
test=p.read_csv("kaggle_submission_2.csv")
len(test)
Out[42]:
66292

Exercise E

In [43]:
# generate your Kaggle submissions with boolean representation and TF representation
# submit to Kaggle
# report your scores here
# which model gave better performance in the hold-out test
# which model gave better performance in the Kaggle test

Sample output:

(93636, 9968) [[0 0 0 ..., 0 0 0]] 9968 [('disloc', 2484), ('surgeon', 8554), ('camaraderi', 1341), ('sketchiest', 7943), ('dedic', 2244), ('impud', 4376), ('adopt', 245), ('worker', 9850), ('buy', 1298), ('systemat', 8623)] 245

BernoulliNB

In [44]:
from sklearn.naive_bayes import BernoulliNB
X_train_vec_bool = unigram_bool_vectorizer.fit_transform(X_train)
bernoulliNB_clf = BernoulliNB(X_train_vec_bool, y_train)

Cross Validation

In [45]:
# cross validation

from sklearn.pipeline import Pipeline
from sklearn.model_selection import cross_val_score
nb_clf_pipe = Pipeline([('vect', CountVectorizer(encoding='latin-1', binary=False)),('nb', MultinomialNB())])
scores = cross_val_score(nb_clf_pipe, X, y, cv=3)
avg=sum(scores)/len(scores)
print(avg)
0.5595474569680894

Exercise F

In [46]:
# run 3-fold cross validation to compare the performance of 
# (1) BernoulliNB (2) MultinomialNB with TF vectors (3) MultinomialNB with boolean vectors

# Your code starts here
nb_clf_pipe = Pipeline([('vect', CountVectorizer(encoding='latin-1', binary=False)),('nb', MultinomialNB())])
scores = cross_val_score(nb_clf_pipe, X, y, cv=3)
avg=sum(scores)/len(scores)
print(avg)
nb_clf_pipe = Pipeline([('vect', CountVectorizer(encoding='latin-1', binary=False)),('nb', BernoulliNB())])
scores = cross_val_score(nb_clf_pipe, X, y, cv=3)
avg=sum(scores)/len(scores)
print(avg)
nb_clf_pipe = Pipeline([('vect', CountVectorizer(encoding='latin-1', binary=True)),('nb', MultinomialNB())])
scores = cross_val_score(nb_clf_pipe, X, y, cv=3)
avg=sum(scores)/len(scores)
print(avg)


def runPipeline(classifier, boolean):
    nb_clf_pipe = Pipeline([('vect', CountVectorizer(encoding='latin-1', binary=boolean)),('nb', classifier)])
    scores = cross_val_score(nb_clf_pipe, X, y, cv=3)
    avg=sum(scores)/len(scores)
    print(classifier, boolean, avg)
    
runPipeline(BernoulliNB(), False)
runPipeline(MultinomialNB(), False)
runPipeline(MultinomialNB(), True)
    
    
    
    
# Your code ends here

'''
0.55315243657
0.553844611375
0.552306763002
0.560136963721
'''
0.5595474569680894
0.5531524365695574
0.5601369637205256
BernoulliNB(alpha=1.0, binarize=0.0, class_prior=None, fit_prior=True) False 0.5531524365695574
MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True) False 0.5595474569680894
MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True) True 0.5601369637205256
Out[46]:
'\n0.55315243657\n0.553844611375\n0.552306763002\n0.560136963721\n'
In [47]:
my_string = "{}, is a {} science portal for {}"
  
print (my_string.format("GeeksforGeeks", "computer", "geeks")) 
GeeksforGeeks, is a computer science portal for geeks
In [48]:
def runPipeline(classifier, boolean):
    nb_clf_pipe = Pipeline([('vect', CountVectorizer(encoding='latin-1', binary=boolean)),('nb', classifier)])
    scores = cross_val_score(nb_clf_pipe, X, y, cv=3)
    avg=sum(scores)/len(scores)
    pretty_line = "{} | Accuracy using {} -- and booleans? {}"
    print(pretty_line.format(avg, classifier, boolean))
    
runPipeline(BernoulliNB(), False)
runPipeline(MultinomialNB(), False)
runPipeline(MultinomialNB(), True)
0.5531524365695574 | Accuracy using BernoulliNB(alpha=1.0, binarize=0.0, class_prior=None, fit_prior=True) -- and booleans? False
0.5595474569680894 | Accuracy using MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True) -- and booleans? False
0.5601369637205256 | Accuracy using MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True) -- and booleans? True
In [53]:
type(X)
X[0]
Out[53]:
'A series of escapades demonstrating the adage that what is good for the goose is also good for the gander , some of which occasionally amuses but none of which amounts to much of a story .'
In [63]:
type(y)
y[:200]
Out[63]:
array([1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3,
       3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 3, 1, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 3, 2,
       4, 3, 2, 3, 3, 3, 2, 2, 4, 2, 3, 4, 2, 2, 2, 1, 2, 2, 2, 3, 2, 2,
       2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 1, 0, 2, 0, 2, 1, 1, 1, 2, 2,
       1, 2, 2, 2, 2, 2, 3, 4, 4, 3, 3, 3, 3, 4, 2, 2, 2, 2, 2, 2, 2, 1,
       2, 3, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 2, 1, 2, 2, 1, 2, 3, 3, 3, 1,
       2, 2, 1, 0, 2, 0, 1, 2, 1, 1, 2, 2, 4, 3, 2, 2, 3, 2, 4, 2, 3, 2,
       4, 3, 3, 3, 4, 2, 4, 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2,
       1, 2])

Optional: use external linguistic resources such as stemmer

In [204]:
from sklearn.feature_extraction.text import CountVectorizer
import nltk.stem

english_stemmer = nltk.stem.SnowballStemmer('english')
class StemmedCountVectorizer(CountVectorizer):
    def build_analyzer(self):
        analyzer = super(StemmedCountVectorizer, self).build_analyzer()
        return lambda doc: ([english_stemmer.stem(w) for w in analyzer(doc)])

stem_vectorizer = StemmedCountVectorizer(min_df=3, analyzer="word")
X_train_stem_vec = stem_vectorizer.fit_transform(X_train)
In [194]:
# check the content of a document vector
print(X_train_stem_vec.shape)
print(X_train_stem_vec[0].toarray())

# check the size of the constructed vocabulary
print(len(stem_vectorizer.vocabulary_))

# print out the first 10 items in the vocabulary
print(list(stem_vectorizer.vocabulary_.items())[:10])

# check word index in vocabulary
print(stem_vectorizer.vocabulary_.get('adopt'))
(93636, 9968)
[[0 0 0 ..., 0 0 0]]
9968
[('disloc', 2484), ('surgeon', 8554), ('camaraderi', 1341), ('sketchiest', 7943), ('dedic', 2244), ('impud', 4376), ('adopt', 245), ('worker', 9850), ('buy', 1298), ('systemat', 8623)]
245
In [ ]: