-
Notifications
You must be signed in to change notification settings - Fork 0
/
Logistic_Regression.py
275 lines (225 loc) · 10.4 KB
/
Logistic_Regression.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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import collections
import os
import re
import codecs
import numpy
Iteration = 10
ham = list()
spam = list()
countTrainHam = 0
countTrainSpam = 0
dictProbHam = dict()
dictProbSpam = dict()
learningRate = 0.001
regularization = 0.001
stopWords = ["a", "about", "above", "after", "again", "against", "all", "am", "an", "and",
"any", "are", "aren't", "as", "at", "be", "because", "been", "before", "being", "below",
"between", "both", "but", "by", "can't", "cannot", "could", "couldn't", "did", "didn't",
"do", "does", "doesn't", "doing", "don't", "down", "during", "each", "few", "for", "from",
"further", "had", "hadn't", "has", "hasn't", "have", "haven't", "having", "he", "he'd",
"he'll", "he's", "her", "here", "here's", "hers", "herself", "him", "himself", "his", "how",
"how's", "i", "i'd", "i'll", "i'm", "i've", "if", "in", "into", "is", "isn't", "it", "it's", "its",
"itself", "let's", "me", "more", "most", "mustn't", "my", "myself", "no", "nor", "not", "of",
"off", "on", "once", "only", "or", "other", "ought", "our", "ours", "ourselves", "out", "over",
"own", "same", "shan't", "she", "she'd", "she'll", "she's", "should", "shouldn't", "so", "some",
"such", "than", "that", "that's", "the", "their", "theirs", "them", "themselves", "then", "there",
"there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "through",
"to", "too", "under", "until", "up", "very", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've",
"were", "weren't", "what", "what's", "when", "when's", "where", "where's", "which", "while", "who",
"who's", "whom", "why", "why's", "with", "won't", "would", "wouldn't", "you", "you'd", "you'll",
"you're", "you've", "your", "yours", "yourself", "yourselves"]
stopword = True #Determines to remove stop words or not, It now removes the stop words
bias = 0
train_path = 'C:/Users/shash/Desktop/MS CE/Subject/Spring 2020/CS6375/CS-6375-Machine-Learning-master/Assignment 3/train'
directoryHam = train_path + '/ham'
directorySpam = train_path + '/spam'
test = 'C:/Users/shash/Desktop/MS CE/Subject/Spring 2020/CS6375/CS-6375-Machine-Learning-master/Assignment 3/test'
testHam = test + '/ham'
testSpam = test + '/spam'
# Regular expression to clean the data given in train ham and spam folder
regex = re.compile(r'[A-Za-z0-9\']')
def ReadFile(file,filepath):
fileHandler = codecs.open(filepath+"\\" + file,'rU','latin-1')
Findwords = re.findall('[A-Za-z0-9\']+', fileHandler.read())
allwords = list()
for word in Findwords:
word = word.lower()
allwords+=[word]
fileHandler.close()
return allwords
def numberofFiles(filepath):
wordList = list()
NumberOfFiles = 0
for files in os.listdir(filepath):
if files.endswith(".txt"):
wordList += ReadFile(files,filepath)
NumberOfFiles+=1
return wordList, NumberOfFiles
# iterating through train to get the list of ham words used to form combined bag of words
ham, countTrainHam = numberofFiles(directoryHam)
spam, countTrainSpam = numberofFiles(directorySpam)
# iterating through test to get the list of ham words used to form combined bag of words
hamTest, countTestHam = numberofFiles(testHam)
SpamTest, countTestSpam = numberofFiles(testSpam)
def removeStopWords():
for word in stopWords:
if word in ham:
i = 0
lengthh=len(ham)
while (i < lengthh):
if (ham[i] == word):
ham.remove(word)
lengthh = lengthh - 1
continue
i = i + 1
if word in spam:
i = 0
lengths=len(spam)
while (i < lengths):
if (spam[i] == word):
spam.remove(word)
lengths = lengths - 1
continue
i = i + 1
if word in hamTest:
i = 0
lengthht=len(hamTest)
while (i < lengthht):
if (hamTest[i] == word):
hamTest.remove(word)
lengthht = lengthht - 1
continue
i = i + 1
if word in SpamTest:
i = 0
lengthst=len(SpamTest)
while (i < lengthst):
if (SpamTest[i] == word):
SpamTest.remove(word)
lengthst = lengthst - 1
continue
i = i + 1
if(stopword == True):
removeStopWords()
# collections.Counter counts the number of occurence of memebers in list
bagOfWords = ham + spam
dictBagOfWords = collections.Counter(bagOfWords)
listBagOfWords = list(dictBagOfWords.keys())
TargetList = list() # final value of ham or spam, ham = 1 & spam = 0
totalFiles = countTrainHam + countTrainSpam
# correct it to testham/spam
testBagOfWords = hamTest + SpamTest
testDictBagOfWords = collections.Counter(testBagOfWords)
testListBagOfWords = list(testDictBagOfWords.keys())
testTargetList = list() # final value of ham or spam, ham = 1 & spam = 0
totalTestFiles = countTestHam + countTestSpam
# initialize matrix to zero and use list comprehension to create this matrix
def initiliazeMatrix(row, column):
featureMatrix = [0] * row
for i in range(row):
featureMatrix[i] = [0] * column
return featureMatrix
trainFeatureMatrix = initiliazeMatrix(totalFiles, len(listBagOfWords))
testFeatureMatrix = initiliazeMatrix(totalTestFiles, len(testListBagOfWords))
rowMatrix = 0
testRowMatrix = 0
sigMoidList = list() # for each row
for i in range(totalFiles):
sigMoidList.append(-1)
TargetList.append(-1)
for i in range(totalTestFiles):
testTargetList.append(-1)
weightOfFeature = list()
for feature in range(len(listBagOfWords)):
weightOfFeature.append(0)
def makeMatrix(featureMatrix, path, listBagOfWords, rowMatrix, classifier, TargetList):
for fileName in os.listdir(path):
words = ReadFile(fileName, path)
temp = dict(collections.Counter(words))
for key in temp:
if key in listBagOfWords:
column = listBagOfWords.index(key)
featureMatrix[rowMatrix][column] = temp[key]
if (classifier == "ham"):
TargetList[rowMatrix] = 0
elif (classifier == "spam"):
TargetList[rowMatrix] = 1
rowMatrix += 1
return featureMatrix, rowMatrix, TargetList
#train matrix including ham and spam
trainFeatureMatrix, rowMatrix, TargetList = makeMatrix(trainFeatureMatrix, directoryHam, listBagOfWords, rowMatrix,
"ham", TargetList)
trainFeatureMatrix, rowMatrix, TargetList = makeMatrix(trainFeatureMatrix, directorySpam, listBagOfWords, rowMatrix,
"spam", TargetList)
testFeatureMatrix, testRowMatrix, testTargetList = makeMatrix(testFeatureMatrix, testHam, testListBagOfWords,
testRowMatrix, "ham", testTargetList)
testFeatureMatrix, testRowMatrix, testTargetList = makeMatrix(testFeatureMatrix, testSpam, testListBagOfWords,
testRowMatrix, "spam", testTargetList)
# for each column
def sigmoid(x):
den = (1 + numpy.exp(-x))
sigma = 1 / den
return sigma
# Calculate for each file
def sigmoidFunction(totalFiles, totalFeatures, featureMatrix):
global sigMoidList
for files in range(totalFiles):
summation = 1.0
for features in range(totalFeatures):
summation += featureMatrix[files][features] * weightOfFeature[features]
sigMoidList[files] = sigmoid(summation)
def calculateWeightUpdate(totalFiles, numberOfFeature, featureMatrix, TargetList):
global sigMoidList
for feature in range(numberOfFeature):
weight = bias
for files in range(totalFiles):
frequency = featureMatrix[files][feature]
y = TargetList[files]
sigmoidValue = sigMoidList[files]
weight += frequency * (y - sigmoidValue)
oldW = weightOfFeature[feature]
weightOfFeature[feature] += ((weight * learningRate) - (learningRate * regularization * oldW))
return weightOfFeature
def trainingFunction(totalFiles, numbeOffeatures, trainFeatureMatrix, TargetList):
sigmoidFunction(totalFiles, numbeOffeatures, trainFeatureMatrix)
calculateWeightUpdate(totalFiles, numbeOffeatures, trainFeatureMatrix, TargetList)
def classifyData():
correctHam = 0
incorrectHam = 0
correctSpam = 0
incorrectSpam = 0
idx=0
print("Classifyig the test files, this may take a while \n")
for file in range(totalTestFiles):
summation = 1.0
print(file)
for i in range(len(testListBagOfWords)):
word = testListBagOfWords[i]
if word in listBagOfWords:
index = listBagOfWords.index(word)
weight = weightOfFeature[index]
wordcount = testFeatureMatrix[file][i]
summation += weight * wordcount
sigSum = sigmoid(summation)
if (testTargetList[file] == 0):
if sigSum < 0.5:
correctHam += 1.0
else:
incorrectHam += 1.0
else:
if sigSum >= 0.5:
correctSpam += 1.0
else:
incorrectSpam += 1.0
idx += 1
print("Classifyig the test files, this may take a while \n")
print("Stop Words: " + str(stopword))
print("\nRegularization Parameter is: " + str(regularization))
print("\nLearning Rate is: " + str(learningRate))
print("Accuracy on Ham:" + str((correctHam / (correctHam + incorrectHam)) * 100))
print("Accuracy on Spam:" + str((correctSpam / (correctSpam + incorrectSpam)) * 100))
print("Overall Accuracy :" + str(((correctHam+correctSpam) / (correctHam + incorrectHam+correctSpam + incorrectSpam)) * 100))
for i in range(Iteration):
print("Iteration of training: " + str(i + 1))
trainingFunction(totalFiles, len(listBagOfWords), trainFeatureMatrix, TargetList)
classifyData()