Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
debakarr
GitHub Repository: debakarr/machinelearning
Path: blob/master/Part 7 - Natural Language Processing/natural_language_processing.py
1002 views
1
# Natural Language Processing
2
3
# Importing the libraries
4
import numpy as np
5
import matplotlib.pyplot as plt
6
import pandas as pd
7
8
# Importing the dataset
9
dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\t', quoting = 3)
10
11
# Cleaning the texts
12
import re
13
import nltk
14
nltk.download('stopwords')
15
from nltk.corpus import stopwords
16
from nltk.stem.porter import PorterStemmer
17
corpus = []
18
for i in range(0, 1000):
19
review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i])
20
review = review.lower()
21
review = review.split()
22
ps = PorterStemmer()
23
review = [ps.stem(word) for word in review if not word in set(stopwords.words('english'))]
24
review = ' '.join(review)
25
corpus.append(review)
26
27
# Creating the Bag of Words model
28
from sklearn.feature_extraction.text import CountVectorizer
29
cv = CountVectorizer(max_features = 1500)
30
X = cv.fit_transform(corpus).toarray()
31
y = dataset.iloc[:, 1].values
32
33
# Splitting the dataset into the Training set and Test set
34
from sklearn.cross_validation import train_test_split
35
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20, random_state = 0)
36
37
# Fitting Naive Bayes to the Training set
38
from sklearn.naive_bayes import GaussianNB
39
classifier = GaussianNB()
40
classifier.fit(X_train, y_train)
41
42
# Predicting the Test set results
43
y_pred = classifier.predict(X_test)
44
45
# Making the Confusion Matrix
46
from sklearn.metrics import confusion_matrix
47
cm = confusion_matrix(y_test, y_pred)
48