AnalyticsDojo

Vectorization Options

rpi.analyticsdojo.com

This is adopted from: Bag of Words Meets Bags of Popcorn wendykan/DeepLearningMovies

53. Vectorizors#

To be meaningfully modeled, words must be turned into Vectors. This covers a number of the approaches for text vectorazation 1.0.

54. Bag of Words#

import nltk
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
 
from gensim import similarities
import pandas as pd
import numpy as np
from gensim import models
# import custom filters
from gensim.parsing.preprocessing import preprocess_string
from gensim.parsing.preprocessing import strip_tags, strip_punctuation, strip_numeric, stem_text,  preprocess_string
from gensim.parsing.preprocessing import strip_multiple_whitespaces, strip_non_alphanum, remove_stopwords, strip_short
from gensim import corpora
from gensim.test.utils import common_corpus, common_dictionary
from gensim.similarities import MatrixSimilarity
from gensim.models.coherencemodel import CoherenceModel
import matplotlib.pyplot as plt
from gensim.test.utils import common_texts
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from gensim.test.utils import get_tmpfile
from gensim.models.doc2vec import TaggedDocument
import pyarrow.parquet as pq
import pyarrow as pa
import pyarrow.dataset as ds
import pandas as pd
from pathlib import Path
from gensim.models import Phrases
from gensim.models.phrases import Phraser
!wget https://github.com/rpi-techfundamentals/spring2019-materials/raw/master/input/labeledTrainData.tsv
!wget https://github.com/rpi-techfundamentals/spring2019-materials/raw/master/input/unlabeledTrainData.tsv
!wget https://github.com/rpi-techfundamentals/spring2019-materials/raw/master/input/testData.tsv
--2021-10-25 19:37:39--  https://github.com/rpi-techfundamentals/spring2019-materials/raw/master/input/labeledTrainData.tsv
Resolving github.com (github.com)... 140.82.113.4
Connecting to github.com (github.com)|140.82.113.4|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/labeledTrainData.tsv [following]
--2021-10-25 19:37:39--  https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/labeledTrainData.tsv
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 33556378 (32M) [text/plain]
Saving to: ‘labeledTrainData.tsv.1’

labeledTrainData.ts 100%[===================>]  32.00M   158MB/s    in 0.2s    

2021-10-25 19:37:39 (158 MB/s) - ‘labeledTrainData.tsv.1’ saved [33556378/33556378]

--2021-10-25 19:37:39--  https://github.com/rpi-techfundamentals/spring2019-materials/raw/master/input/unlabeledTrainData.tsv
Resolving github.com (github.com)... 140.82.113.4
Connecting to github.com (github.com)|140.82.113.4|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/unlabeledTrainData.tsv [following]
--2021-10-25 19:37:39--  https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/unlabeledTrainData.tsv
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 67281491 (64M) [text/plain]
Saving to: ‘unlabeledTrainData.tsv.1’

unlabeledTrainData. 100%[===================>]  64.16M   204MB/s    in 0.3s    

2021-10-25 19:37:40 (204 MB/s) - ‘unlabeledTrainData.tsv.1’ saved [67281491/67281491]

--2021-10-25 19:37:40--  https://github.com/rpi-techfundamentals/spring2019-materials/raw/master/input/testData.tsv
Resolving github.com (github.com)... 140.82.113.4
Connecting to github.com (github.com)|140.82.113.4|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/testData.tsv [following]
--2021-10-25 19:37:40--  https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/testData.tsv
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 32724746 (31M) [text/plain]
Saving to: ‘testData.tsv.1’

testData.tsv.1      100%[===================>]  31.21M   163MB/s    in 0.2s    

2021-10-25 19:37:40 (163 MB/s) - ‘testData.tsv.1’ saved [32724746/32724746]
train = pd.read_csv('labeledTrainData.tsv', header=0, \
                    delimiter="\t", quoting=3)
unlabeled_train= pd.read_csv('unlabeledTrainData.tsv', header=0, \
                    delimiter="\t", quoting=3)
test = pd.read_csv('testData.tsv', header=0, \
                    delimiter="\t", quoting=3)
import os
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import numpy as np
print(train.columns.values, test.columns.values)
['id' 'sentiment' 'review'] ['id' 'review']
train.head()
id sentiment review
0 "5814_8" 1 "With all this stuff going down at the moment ...
1 "2381_9" 1 "\"The Classic War of the Worlds\" by Timothy ...
2 "7759_3" 0 "The film starts with a manager (Nicholas Bell...
3 "3630_4" 0 "It must be assumed that those who praised thi...
4 "9495_8" 1 "Superbly trashy and wondrously unpretentious ...
print('The train shape is: ', train.shape)
print('The train shape is: ', test.shape)
The train shape is:  (25000, 3)
The train shape is:  (25000, 2)
print('The first review is:')
print(train["review"][0])
The first review is:
"With all this stuff going down at the moment with MJ i've started listening to his music, watching the odd documentary here and there, watched The Wiz and watched Moonwalker again. Maybe i just want to get a certain insight into this guy who i thought was really cool in the eighties just to maybe make up my mind whether he is guilty or innocent. Moonwalker is part biography, part feature film which i remember going to see at the cinema when it was originally released. Some of it has subtle messages about MJ's feeling towards the press and also the obvious message of drugs are bad m'kay.<br /><br />Visually impressive but of course this is all about Michael Jackson so unless you remotely like MJ in anyway then you are going to hate this and find it boring. Some may call MJ an egotist for consenting to the making of this movie BUT MJ and most of his fans would say that he made it for the fans which if true is really nice of him.<br /><br />The actual feature film bit when it finally starts is only on for 20 minutes or so excluding the Smooth Criminal sequence and Joe Pesci is convincing as a psychopathic all powerful drug lord. Why he wants MJ dead so bad is beyond me. Because MJ overheard his plans? Nah, Joe Pesci's character ranted that he wanted people to know it is he who is supplying drugs etc so i dunno, maybe he just hates MJ's music.<br /><br />Lots of cool things in this like MJ turning into a car and a robot and the whole Speed Demon sequence. Also, the director must have had the patience of a saint when it came to filming the kiddy Bad sequence as usually directors hate working with one kid let alone a whole bunch of them performing a complex dance scene.<br /><br />Bottom line, this movie is for people who like MJ on one level or another (which i think is most people). If not, then stay away. It does try and give off a wholesome message and ironically MJ's bestest buddy in this movie is a girl! Michael Jackson is truly one of the most talented people ever to grace this planet but is he guilty? Well, with all the attention i've gave this subject....hmmm well i don't know because people can be different behind closed doors, i know this for a fact. He is either an extremely nice but stupid guy or one of the most sickest liars. I hope he is not the latter."

54.1. Common Preprocessing#

Packages provide a variety of preprocessing routines. This results in a Tokenized set of data.

https://radimrehurek.com/gensim/parsing/preprocessing.html

from gensim.parsing.preprocessing import preprocess_string
from gensim.parsing.preprocessing import strip_tags, strip_punctuation, strip_numeric, stem_text,  preprocess_string
from gensim.parsing.preprocessing import strip_multiple_whitespaces, strip_non_alphanum, remove_stopwords, strip_short

# define custom filters
text_col='review'
CUSTOM_FILTERS = [
                  lambda x: x.encode('utf-8').strip(),
                  lambda x: x.lower(), #lowercase
                  strip_multiple_whitespaces,# remove repeating whitespaces
                  strip_numeric, # remove numbers
                  strip_punctuation, #remove punctuation
                  remove_stopwords,# remove stopwordsß
                  stem_text # return porter-stemmed text,
                 ]

def preprocess(x, filters):
    results=preprocess_string(x, filters )
    return results

train[text_col+'_pro']=train[text_col].apply(preprocess, filters=CUSTOM_FILTERS)
train
from gensim import corpora
from gensim.test.utils import common_corpus, common_dictionary

def bow(x, dictionary):
    return dictionary.doc2bow(x)

#Create a Dictionary.
cdict = corpora.Dictionary(train[text_col+'_pro'].to_list())


#Create a Bag of Words Model
train[text_col+'_bow']=train[text_col+'_pro'].apply(bow, dictionary=  cdict)
train
def transform(x, model):
    return model[x]
    
tfidf_bow = models.TfidfModel( train[text_col+'_bow'].to_list(),  normalize=True)
train[text_col+'_tfidf_bow']=train[text_col+'_bow'].apply(transform, model=tfidf_bow )
#Word to Vec
train[text_col+'_tag']=pd.Series(TaggedDocument(doc, [i]) for i, doc in enumerate(train[text_col+'_pro'].to_list()))
doc2vec = Doc2Vec(train[text_col+'_tag'] , vector_size=50, window=2, min_count=1, workers=4)
train[text_col+'_docvecs']=pd.Series([doc2vec.docvecs[x] for x in range(len(train))])
train
def create_dense(x, vlen=50):
    try:
        x=dict(x)
        output=[]
        for i in range(vlen):
            if i in x.keys():
                output.append(np.float64(x[i]))
            else:
                output.append(0)
        return output
    except:
        return np.nan
lsi_model_bow = models.LsiModel(train[text_col+'_bow'].to_list(), id2word=cdict, num_topics=50)
train[text_col+'_lsi_bow']=train[text_col+'_bow'].apply(transform, model=lsi_model_bow)
train[text_col+'_lsi_bow_d']=train[text_col+'_lsi_bow'].apply(create_dense, vlen=50)
lsi_model_tfidf = models.LsiModel(train[text_col+'_tfidf_bow'].to_list(), id2word=cdict, num_topics=50)
train[text_col+'_lsi_tfidf']=train[text_col+'_tfidf_bow'].apply(transform, model=lsi_model_tfidf)
train[text_col+'_lsi_tfidf_d']=train[text_col+'_lsi_tfidf'].apply(create_dense, vlen=50)
lda_model_bow = models.LdaModel(train[text_col+'_bow'].to_list(), id2word=cdict, num_topics=50, minimum_probability=0)
train[text_col+'_lda_bow']=train[text_col+'_bow'].apply(transform, model=lda_model_bow)
train[text_col+'_lda_bow_d']=train[text_col+'_lda_bow'].apply(create_dense, vlen=50)
lda_model_tfidf = models.LdaModel(train[text_col+'_tfidf_bow'].to_list(), id2word=cdict, num_topics=50, minimum_probability=0)      
train[text_col+'_lda_tfidf']=train[text_col+'_tfidf_bow'].apply(transform, model=lda_model_tfidf)
train[text_col+'_lda_tfidf_d']=train[text_col+'_lda_tfidf'].apply(create_dense, vlen=50)
train