Path: blob/master/Part 7 - Natural Language Processing/natural_language_processing.py
1002 views
# Natural Language Processing12# Importing the libraries3import numpy as np4import matplotlib.pyplot as plt5import pandas as pd67# Importing the dataset8dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\t', quoting = 3)910# Cleaning the texts11import re12import nltk13nltk.download('stopwords')14from nltk.corpus import stopwords15from nltk.stem.porter import PorterStemmer16corpus = []17for i in range(0, 1000):18review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i])19review = review.lower()20review = review.split()21ps = PorterStemmer()22review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]23review = ' '.join(review)24corpus.append(review)2526# Creating the Bag of Words model27from sklearn.feature_extraction.text import CountVectorizer28cv = CountVectorizer(max_features = 1500)29X = cv.fit_transform(corpus).toarray()30y = dataset.iloc[:, 1].values3132# Splitting the dataset into the Training set and Test set33from sklearn.cross_validation import train_test_split34X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)3536# Fitting Naive Bayes to the Training set37from sklearn.naive_bayes import GaussianNB38classifier = GaussianNB()39classifier.fit(X_train, y_train)4041# Predicting the Test set results42y_pred = classifier.predict(X_test)4344# Making the Confusion Matrix45from sklearn.metrics import confusion_matrix46cm = confusion_matrix(y_test, y_pred)4748