-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsms_classifier_model.py
73 lines (54 loc) · 2.1 KB
/
sms_classifier_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Importing essential libraries
import pandas as pd
import numpy as np
import pickle
# Loading the dataset
df = pd.read_csv("spam.csv",encoding="latin-1")
# Dropping the redundent looking columns
df.drop(['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], axis=1, inplace=True)
#renaming columns
df.rename(columns = {"v1":"label", "v2":"message"}, inplace = True)
df['label'] = df['label'].map({'ham': 0, 'spam': 1})
# Importing essential libraries for performing Natural Language Processing on 'SMS Spam Collection' dataset
import nltk
import re
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
# Cleaning the messages
corpus = []
ps = PorterStemmer()
for sms_string in list(df.message):
# Cleaning special character from the message
message = re.sub(pattern='[^a-zA-Z]', repl=' ', string=sms_string)
# Converting the entire message into lower case
message = message.lower()
# Tokenizing the review by words
words = message.split()
# Removing the stop words
words = [word for word in words if word not in set(stopwords.words('english'))]
# Stemming the words
words = [ps.stem(word) for word in words]
# Joining the stemmed words
message = ' '.join(words)
# Building a corpus of messages
corpus.append(message)
# Creating the Bag of Words model
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=2500)
X = cv.fit_transform(corpus).toarray()
# Extracting dependent variable from the dataset
y = pd.get_dummies(df['label'])
y = y.iloc[:, 1].values
# Creating a pickle file for the CountVectorizer
pickle.dump(cv, open('cv-transform.pkl', 'wb'))
# Model Building
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=0)
# Fitting Naive Bayes to the Training set
from sklearn.naive_bayes import MultinomialNB
classifier = MultinomialNB(alpha=0.3)
classifier.fit(X_train, y_train)
# Creating a pickle file for the Multinomial Naive Bayes model
filename = 'spam-sms-mnb-model.pkl'
pickle.dump(classifier, open(filename, 'wb'))