
In this Machine Learning Project, we’ll build binary classification that puts movie reviews texts into one of two categories — negative or positive sentiment. We’re going to have a brief look at the Bayes theorem and relax its requirements using the Naive assumption.
Let’s start by importing the Libraries
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import re # for regex from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem import SnowballStemmer from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import GaussianNB,MultinomialNB,BernoulliNB from sklearn.metrics import accuracy_score import pickle
You can download the data set you need for this task from here:
data = pd.read_csv('IMDB Dataset.csv') print(data.shape) data.head()

data.info()
#Output <class 'pandas.core.frame.DataFrame'> RangeIndex: 50000 entries, 0 to 49999 Data columns (total 2 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 review 50000 non-null object 1 sentiment 50000 non-null object dtypes: object(2) memory usage: 781.4+ KB
No null values, Label encode sentiment to 1(positive) and 0(negative)
data.sentiment.value_counts()
#Output positive 25000 negative 25000 Name: sentiment, dtype: int64
data.sentiment.replace('positive',1,inplace=True) data.sentiment.replace('negative',0,inplace=True) data.head(10)

data.review[0]
#Output One of the other reviewers has mentioned that after watching just 1 Oz episode you'll be hooked. They are right, as this is exactly what happened with me.<br /><br />The first thing that struck me about Oz was its brutality and unflinching scenes of violence, which set in right from the word GO. Trust me, this is not a show for the faint hearted or timid. This show pulls no punches with regards to drugs, sex or violence. Its is hardcore, in the classic use of the word.<br /><br />It is called OZ as that is the nickname given to the Oswald Maximum Security State Penitentary. It focuses mainly on Emerald City, an experimental section of the prison where all the cells have glass fronts and face inwards, so privacy is not high on the agenda. Em City is home to many..Aryans, Muslims, gangstas, Latinos, Christians, Italians, Irish and more....so scuffles, death stares, dodgy dealings and shady agreements are never far away.<br /><br />I would say the main appeal of the show is due to the fact that it goes where other shows wouldn't dare. Forget pretty pictures painted for mainstream audiences, forget charm, forget romance...OZ doesn't mess around. The first episode I ever saw struck me as so nasty it was surreal, I couldn't say I was ready for it, but as I watched more, I developed a taste for Oz, and got accustomed to the high levels of graphic violence. Not just violence, but injustice (crooked guards who'll be sold out for a nickel, inmates who'll kill on order and get away with it, well mannered, middle class inmates being turned into prison bitches due to their lack of street skills or prison experience) Watching Oz, you may become comfortable with what is uncomfortable viewing....thats if you can get in touch with your darker side.
STEPS TO CLEAN THE REVIEWS :
- Remove HTML tags
- Remove special characters
- Convert everything to lowercase
- Remove stopwords
- Stemming
1. Remove HTML tags
Regex rule : ‘<.*?>’
def clean(text): cleaned = re.compile(r'<.*?>') return re.sub(cleaned,'',text) data.review = data.review.apply(clean) data.review[0]
#Output "One of the other reviewers has mentioned that after watching just 1 Oz episode you'll be hooked. They are right, as this is exactly what happened with me.The first thing that struck me about Oz was its brutality and unflinching scenes of violence, which set in right from the word GO. Trust me, this is not a show for the faint hearted or timid. This show pulls no punches with regards to drugs, sex or violence. Its is hardcore, in the classic use of the word.It is called OZ as that is the nickname given to the Oswald Maximum Security State Penitentary. It focuses mainly on Emerald City, an experimental section of the prison where all the cells have glass fronts and face inwards, so privacy is not high on the agenda. Em City is home to many..Aryans, Muslims, gangstas, Latinos, Christians, Italians, Irish and more....so scuffles, death stares, dodgy dealings and shady agreements are never far away.I would say the main appeal of the show is due to the fact that it goes where other shows wouldn't dare. Forget pretty pictures painted for mainstream audiences, forget charm, forget romance...OZ doesn't mess around. The first episode I ever saw struck me as so nasty it was surreal, I couldn't say I was ready for it, but as I watched more, I developed a taste for Oz, and got accustomed to the high levels of graphic violence. Not just violence, but injustice (crooked guards who'll be sold out for a nickel, inmates who'll kill on order and get away with it, well mannered, middle class inmates being turned into prison bitches due to their lack of street skills or prison experience) Watching Oz, you may become comfortable with what is uncomfortable viewing....thats if you can get in touch with your darker side."
2. Remove special characters
def is_special(text): rem = '' for i in text: if i.isalnum(): rem = rem + i else: rem = rem + ' ' return rem data.review = data.review.apply(is_special) data.review[0]
#Output 'One of the other reviewers has mentioned that after watching just 1 Oz episode you ll be hooked They are right as this is exactly what happened with me The first thing that struck me about Oz was its brutality and unflinching scenes of violence which set in right from the word GO Trust me this is not a show for the faint hearted or timid This show pulls no punches with regards to drugs sex or violence Its is hardcore in the classic use of the word It is called OZ as that is the nickname given to the Oswald Maximum Security State Penitentary It focuses mainly on Emerald City an experimental section of the prison where all the cells have glass fronts and face inwards so privacy is not high on the agenda Em City is home to many Aryans Muslims gangstas Latinos Christians Italians Irish and more so scuffles death stares dodgy dealings and shady agreements are never far away I would say the main appeal of the show is due to the fact that it goes where other shows wouldn t dare Forget pretty pictures painted for mainstream audiences forget charm forget romance OZ doesn t mess around The first episode I ever saw struck me as so nasty it was surreal I couldn t say I was ready for it but as I watched more I developed a taste for Oz and got accustomed to the high levels of graphic violence Not just violence but injustice crooked guards who ll be sold out for a nickel inmates who ll kill on order and get away with it well mannered middle class inmates being turned into prison bitches due to their lack of street skills or prison experience Watching Oz you may become comfortable with what is uncomfortable viewing thats if you can get in touch with your darker side '
3. Convert everything to lowercase
def to_lower(text): return text.lower() data.review = data.review.apply(to_lower) data.review[0]
#Output 'one of the other reviewers has mentioned that after watching just 1 oz episode you ll be hooked they are right as this is exactly what happened with me the first thing that struck me about oz was its brutality and unflinching scenes of violence which set in right from the word go trust me this is not a show for the faint hearted or timid this show pulls no punches with regards to drugs sex or violence its is hardcore in the classic use of the word it is called oz as that is the nickname given to the oswald maximum security state penitentary it focuses mainly on emerald city an experimental section of the prison where all the cells have glass fronts and face inwards so privacy is not high on the agenda em city is home to many aryans muslims gangstas latinos christians italians irish and more so scuffles death stares dodgy dealings and shady agreements are never far away i would say the main appeal of the show is due to the fact that it goes where other shows wouldn t dare forget pretty pictures painted for mainstream audiences forget charm forget romance oz doesn t mess around the first episode i ever saw struck me as so nasty it was surreal i couldn t say i was ready for it but as i watched more i developed a taste for oz and got accustomed to the high levels of graphic violence not just violence but injustice crooked guards who ll be sold out for a nickel inmates who ll kill on order and get away with it well mannered middle class inmates being turned into prison bitches due to their lack of street skills or prison experience watching oz you may become comfortable with what is uncomfortable viewing thats if you can get in touch with your darker side '
4. Remove stopwords
def rem_stopwords(text): stop_words = set(stopwords.words('english')) words = word_tokenize(text) return [w for w in words if w not in stop_words] data.review = data.review.apply(rem_stopwords) data.review[0]
5. Stem the words
def stem_txt(text): ss = SnowballStemmer('english') return " ".join([ss.stem(w) for w in text]) data.review = data.review.apply(stem_txt) data.review[0]
data.head()

CREATING THE MODEL
1. Creating Bag Of Words (BOW)
X = np.array(data.iloc[:,0].values) y = np.array(data.sentiment.values) cv = CountVectorizer(max_features = 1000) X = cv.fit_transform(data.review).toarray() print("X.shape = ",X.shape) print("y.shape = ",y.shape)
#Output X.shape = (50000, 1000) y.shape = (50000,)
print(X)
#Output array([[0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0], [0, 0, 0, ..., 0, 1, 0], ..., [0, 0, 0, ..., 0, 0, 0], [0, 0, 1, ..., 0, 0, 0], [0, 0, 0, ..., 0, 0, 0]])
2. Train test split
trainx,testx,trainy,testy = train_test_split(X,y,test_size=0.2,random_state=9) print("Train shapes : X = {}, y = {}".format(trainx.shape,trainy.shape)) print("Test shapes : X = {}, y = {}".format(testx.shape,testy.shape))
#Output Train shapes : X = (40000, 1000), y = (40000,) Test shapes : X = (10000, 1000), y = (10000,)
3. Defining the models and Training them
gnb,mnb,bnb = GaussianNB(),MultinomialNB(alpha=1.0,fit_prior=True),BernoulliNB(alpha=1.0,fit_prior=True) gnb.fit(trainx,trainy) mnb.fit(trainx,trainy) bnb.fit(trainx,trainy)
#Output BernoulliNB(alpha=1.0, binarize=0.0, class_prior=None, fit_prior=True)
4. Prediction and accuracy metrics to choose best model
ypg = gnb.predict(testx) ypm = mnb.predict(testx) ypb = bnb.predict(testx) print("Gaussian = ",accuracy_score(testy,ypg)) print("Multinomial = ",accuracy_score(testy,ypm)) print("Bernoulli = ",accuracy_score(testy,ypb))
#Output Gaussian = 0.7843 Multinomial = 0.831 Bernoulli = 0.8386
pickle.dump(bnb,open('model1.pkl','wb'))
rev = """Terrible. Complete trash. Brainless tripe. Insulting to anyone who isn't an 8 year old fan boy. Im actually pretty disgusted that this movie is making the money it is - what does it say about the people who brainlessly hand over the hard earned cash to be 'entertained' in this fashion and then come here to leave a positive 8.8 review?? Oh yes, they are morons. Its the only sensible conclusion to draw. How anyone can rate this movie amongst the pantheon of great titles is beyond me. So trying to find something constructive to say about this title is hard...I enjoyed Iron Man? Tony Stark is an inspirational character in his own movies but here he is a pale shadow of that...About the only 'hook' this movie had into me was wondering when and if Iron Man would knock Captain America out...Oh how I wished he had :( What were these other characters anyways? Useless, bickering idiots who really couldn't organise happy times in a brewery. The film was a chaotic mish mash of action elements and failed 'set pieces'... I found the villain to be quite amusing. And now I give up. This movie is not robbing any more of my time but I felt I ought to contribute to restoring the obvious fake rating and reviews this movie has been getting on IMDb.""" f1 = clean(rev) f2 = is_special(f1) f3 = to_lower(f2) f4 = rem_stopwords(f3) f5 = stem_txt(f4) bow,words = [],word_tokenize(f5) for word in words: bow.append(words.count(word)) #np.array(bow).reshape(1,3000) #bow.shape word_dict = cv.vocabulary_ pickle.dump(word_dict,open('bow.pkl','wb'))
inp = [] for i in word_dict: inp.append(f5.count(i[0])) y_pred = bnb.predict(np.array(inp).reshape(1,1000))
[0]
0 mean negative.
I hope it will help you.
[…] Movie Reviews Sentiment Analysis -Binary Classification with Machine Learning […]