-
Notifications
You must be signed in to change notification settings - Fork 0
/
spam-classifier.py
149 lines (118 loc) · 3.97 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import argparse
import arff
import os
import sys
import time
import numpy as np
from classifier.visualize import draw_chart, draw_matrix
from random import shuffle
from classifier import Classifier
from classifier.cross_validation import kfold_cross_validation
classifiers = [
"knn",
"svm",
"random-forest",
"naive-bayes",
"decision-tree",
]
def file_exist(file_path):
return os.path.exists(file_path)
def read_dataset(file_path):
with open(file_path) as handler:
return arff.load(handler)
def parse_samples_labels(data):
return data[:, :-1].astype(float), data[:, -1]
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-v",
"--verbose",
help="increase output verbosity",
default=False,
action='store_true'
)
parser.add_argument(
"-d",
"--dataset",
help="dataset in arff format",
required=True,
)
parser.add_argument(
"-c",
"--classifier",
help="classifier algorithm",
required=True,
)
parser.add_argument(
"-k",
"--kfold",
help="k in kfold cross validation",
default=10,
)
parser.add_argument(
"-s",
"--save",
help="save charts",
default=False,
action='store_true'
)
args = vars(parser.parse_args())
if not file_exist(args["dataset"]):
print("dataset file does not exist.")
sys.exit(1)
arg_classifiers = classifiers.copy()
arg_classifiers.append("all")
if args["classifier"] not in arg_classifiers:
print("invalid type of classifier. this program only support '{}'.".format(
", ".join(classifiers)))
sys.exit(2)
return args
def chart_file(save, algorithm, name):
if not save:
return None
return 'chart-{}-{}.png'.format(algorithm, name)
if __name__ == "__main__":
args = parse_args()
print("~ Reading dataset file ...")
dataset = read_dataset(args["dataset"])
data = dataset["data"]
shuffle(data)
data = np.array(data)
print("- Dataset relation: '{}'.".format(dataset["relation"]))
print("- Dataset size: {}.".format(len(data)))
selected_classifiers = classifiers if args["classifier"] == 'all' else [
args["classifier"]]
draw_confusion_matrix = args["classifier"] != "all"
confusion_matrix = None
all_accuracies_list = []
all_labels = []
for current_classifier in selected_classifiers:
print("~ Running program with {} classifier.".format(current_classifier))
classifier = Classifier(current_classifier)
accuracy_list = []
start_time = time.time()
for i, (train, test) in enumerate(kfold_cross_validation(data, k=int(args["kfold"]))):
samples, labels = parse_samples_labels(train)
classifier.fit(samples, labels)
samples, labels = parse_samples_labels(test)
accuracy = classifier.accuracy(samples, labels)
if args["verbose"]:
print("+ [{:02d}/10] accuracy: {:3d}%".format(i+1, int(accuracy*100)))
if draw_confusion_matrix:
confusion_matrix = classifier.confusion_matrix(samples, labels)
accuracy_list.append(accuracy)
all_accuracies_list.append(accuracy_list)
all_labels.append(current_classifier)
if args["verbose"]:
print("- Took {:.2f} seconds.".format(time.time() - start_time))
print("~ Drawing chart to visualize accuracy list ...")
draw_chart(
range(len(all_accuracies_list[0])),
all_accuracies_list,
y_labels=all_labels,
title='The accuracy graph for {} classifier(s).'.format(
args["classifier"]),
save_to=chart_file(args["save"], args["classifier"], 'accuracy')
)
if draw_confusion_matrix:
draw_matrix(confusion_matrix, save_to=chart_file(args["save"], args["classifier"], 'matrix'))