#importing pandas and numpy libraries
import numpy as np
import pandas as pd
#Loading the data from csv file
data = pd.read_csv('IMDB-Dataset.csv')
data.head()
#Displaying the columns in the data
data.info()
#Displaying the unique values in the sentiment columns
data["sentiment"].value_counts()
#replacing the sentiments of positive and negative with 0 and 1
data["sentiment"].replace('positive',1,inplace=True)
data["sentiment"].replace('negative',0,inplace=True)
data.head(10)
#Checking one of the review for sample
data.review[0]
#importing re
import re
#defining function to remove special characters from the text
def clean_text(text):
clean = re.compile(r'<.*?>')
return re.sub(clean,'',text)
#Cleaning the text in the review column
data["review"] = data["review"].apply(clean_text)
data["review"][0]
#Defining a function to filter the special characters
def is_special(text):
temp = ''
for i in text:
if i.isalnum():
temp = temp + i
else:
temp = temp + ' '
return temp
#Applying is_special function on top of review text data
data["review"] = data["review"].apply(is_special)
data["review"][0]
#Defining a function to return the text in lower case
def to_lower(text):
return text.lower()
#Lowering the case of the text using above function
data["review"] = data["review"].apply(to_lower)
data["review"][0]
#Importing NLTK library
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import SnowballStemmer
nltk.download('stopwords')
nltk.download('punkt')
#Defining function to remove stopwords from data
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]
#Stemming the text
def stem_text(text):
ss = SnowballStemmer('english')
return " ".join([ss.stem(w) for w in text])
#Stemming the text using ste_text function
data["review"] = data["review"].apply(stem_text)
data["review"][0]
#Checking the fist 5 rows in a DataFrame
data.head()
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
#Here we are creating the Bagging of words
X = np.array(data.iloc[:,0].values)
y = np.array(data["sentiment"].values)
counvec = CountVectorizer(max_features = 1000)
X = counvec.fit_transform(data.review).toarray()
#Printing x matrix
print(X)
#Splitting the training vs test data using 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))
#training the gaussian and bernoulli model
gauss,bernou = GaussianNB(),BernoulliNB(alpha=1.0,fit_prior=True)
gauss.fit(trainx,trainy)
bernou.fit(trainx,trainy)
ypg = gauss.predict(testx)
ypb = bernou.predict(testx)
#Accuracy score for Gaussian and Bernoulli
print("Gaussian Model = ",accuracy_score(testy,ypg))
print("Bernoulli Model = ",accuracy_score(testy,ypb))
#Dumping the brenoulli model to the pickle file
pickle.dump(bernou,open('model1.pkl','wb'))
#Testing the performance of the model
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_text(rev)
f2 = is_special(f1)
f3 = to_lower(f2)
f4 = rem_stopwords(f3)
f5 = stem_text(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 = counvec.vocabulary_
pickle.dump(word_dict,open('bow.pkl','wb'))
inp = []
for i in word_dict:
inp.append(f5.count(i[0]))
y_pred = bernou.predict(np.array(inp).reshape(1,1000))
#The output () refers to the negative Sentiment
y_pred
#Checking the model with unknown review
review="""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."""
#Testing the performance of the model
rev = review
f1 = clean_text(rev)
f2 = is_special(f1)
f3 = to_lower(f2)
f4 = rem_stopwords(f3)
f5 = stem_text(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 = counvec.vocabulary_
pickle.dump(word_dict,open('bow.pkl','wb'))
inp = []
for i in word_dict:
inp.append(f5.count(i[0]))
y_pred = bernou.predict(np.array(inp).reshape(1,1000))
#We are getting 1 as the review contains positive centiment
y_pred