-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathspam_classifier.py
84 lines (62 loc) · 2.66 KB
/
spam_classifier.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
74
75
76
77
78
79
80
81
82
83
84
#Description: Spam Email Classifier
#Authors: Aubrianna Sample and Dustin Chavez
#Input: Email Subject and Body
#Output: Boolean value, spam or not spam
#Model: MultinomialNB()
#Libraries Used: Sklearn (Machine Learning), Pandas, Joblib (Model and Feature Extraction Saving)
#Purpose: Takes an email subject and body as input, runs email through preprocessing, text analysis, and trained machine learning model
#and outputs boolean value of spam or real.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import accuracy_score
import joblib
def train():
#Open dataset
df = pd.read_csv('spam_ham_dataset.csv')
"""Data Preprocessing"""
data = df.head(5)
print(data)
data = df.where((pd.notnull(df)), '')
data.head(10)
data.info()
data.shape
#Assign spam as 0 and ham(real) as 1.
data.loc[data['label'] == 'spam', 'label'] = 0
data.loc[data['label'] == 'ham', 'label'] = 1
X = data['text']
Y = data['label']
"""End data preprocessing"""
#Split data
X_train, X_test, Y_train, Y_test = train_test_split(X,Y, test_size= 0.2, random_state = 3)
"""Feature extraction (vectorization, fitting/transforming)"""
feature_extraction = TfidfVectorizer(min_df=2, max_df=0.5, stop_words='english',
lowercase=True, ngram_range=(1, 2))
X_train_features = feature_extraction.fit_transform(X_train)
X_test_features = feature_extraction.transform(X_test)
"""End feature extraction"""
#Put vectorization into file
joblib.dump(feature_extraction, 'feature_extraction.pkl')
#Check for NaN values and handle them
if Y_train.isnull().values.any():
Y_train = Y_train.fillna(0)
if Y_test.isnull().values.any():
Y_test = Y_test.fillna(0)
#Now convert to integer type
Y_train = Y_train.astype('int')
Y_test = Y_test.astype('int')
Y_train = Y_train.astype('int')
Y_test = Y_test.astype('int')
"Model training and fitting"
model = MultinomialNB()
model.fit(X_train_features, Y_train)
joblib.dump(model, 'model.pkl')
"""End model training and fitting"""
#The following are prediction and accuracy scores to check our model's accuracy and performance
prediction_on_training_data = model.predict(X_train_features)
accuracy_on_training_data = accuracy_score(Y_train, prediction_on_training_data)
print('Accuracy on training data: ', accuracy_on_training_data)
prediction_on_test_data = model.predict(X_test_features)
accuracy_on_test_data = accuracy_score(Y_test, prediction_on_test_data)
print('Accuracy on test data: ', accuracy_on_test_data)