-
Notifications
You must be signed in to change notification settings - Fork 2
/
testingHandlerMultithreaded.py
284 lines (218 loc) · 8.69 KB
/
testingHandlerMultithreaded.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
276
277
278
279
280
281
282
283
from databaseObject import *
from nntrainer import *
from nnbuilder import *
import os
import xml.etree.ElementTree
import time
import Queue
import multiprocessing
import numpy as np
import sys
THREADS = 5
NEWONLY = 0
class testingHandler:
def __init__(self, fileName):
self.openSchema(fileName)
def openSchema(self, fileName):
# Setup dictionaries for XML
self.networkDescDict = {}
self.netDict = {}
self.thresholdDict = {}
# Parse xml file
xmlHead = xml.etree.ElementTree.parse("XMLSchema/" + fileName + ".xml").getroot()
topLayer = xmlHead.get('name')
self.head = topLayer
self.netDict[ topLayer ] = self.fetchNet( topLayer )
self.thresholdDict[ topLayer ] = xmlHead.get('threshold')
# add details to dicts
self.addAllDict(self.networkDescDict, self.thresholdDict, self.netDict, xmlHead.get('name'), xmlHead)
def addAllDict(self, networkDescDict, thresholdDict, netDict, lastName, lastNet):
# Add each node info into dict
for xmlNode in lastNet.findall('network'):
netName = xmlNode.get('name')
# Go to next node within
self.addAllDict(networkDescDict, thresholdDict, netDict, netName, xmlNode)
# Add to dict
networkDescDict.setdefault(lastName, [])
thresholdDict[netName] = xmlNode.get('threshold')
networkDescDict[lastName].append( netName )
netDict[netName] = self.fetchNet( netName )
def fetchNet(self, name):
fileName = "NetBinarySaves/" + name
netExists = os.path.isfile(fileName)
if (netExists and NEWONLY != 1):
# See if net was already created
print("Using existing net for " + name)
importFile = open(fileName,'r')
builder = pickle.load(importFile)
else:
# Create net if it doesnt already exist
print("Creating net for " + name)
builder = NNBuilder(name)
builder.BuildNN()
net = builder.nn
netTrainer = NNTrainer()
# Create the dataset
print("Creating dataset for " + name)
testDataset = netTrainer.createDataset(builder.input, builder.success, builder.typeRuns, builder.normRuns)
# Train the network
print("Training " + name)
netTrainer.trainNetwork(net, testDataset)
# Save the built net
print("Saving net")
exportFile = open(fileName, 'w')
pickle.dump(builder, exportFile)
return builder
def fetchData(self, fields, successField, ids):
db = Database();
fields.append(successField)
fields.append("id")
newArr = db.getFields(fields, "test", ids, None)
returnArr = []
# Get each row from DB
for row in newArr:
arr = []
# Append each field to dataset
for field in fields:
if (field != successField and field != "id"):
arr.append(row[field]);
# Add sample to set
returnArr.append([arr, row[successField], row["id"]])
# Remve the success field
fields.pop()
fields.pop()
return returnArr;
def testWholeNetwork(self):
self.testEach(self.head, None)
def testEach(self, name, arr):
netBuilt = self.netDict[name]
threshold = self.thresholdDict[name]
print("\nTesting " + name + " with a success at " + netBuilt.success)
arr = self.testNet(netBuilt.nn, threshold, netBuilt.input, netBuilt.success, arr)
if name in self.networkDescDict.keys():
netNames = self.networkDescDict[name]
for netName in netNames:
self.testEach(netName, arr)
def testNetInner(self, x, return_dict, net, threshold, fields, successField, ids):
correct = 0
total = 0
correctOfType = 0
totalOfType = 0
falsePositives = 0
normalAsThreat = 0
sendLower = []
# Fetch data from DB
checkData = self.fetchData(fields, successField, ids)
# Test each record
for row in checkData:
result = net.activate(row[0])[0]
expected = row[1]
totalOfType += expected
# Guess is whether not it is believed to be malicious
if result >= threshold:
guess = 1
else:
guess = 0
# Flip normals
if successField == "normal":
if guess == 0:
sendGuess = 1
elif guess == 1:
sendGuess = 0
else:
sendGuess = guess
# Net believes malicious
if sendGuess == 1:
sendLower.append(row[2])
# net believes malicious and is
if guess == 1 and expected == 1:
correct += 1.0
correctOfType += 1.0
# net believes not malicious and isnt
if guess == 0 and expected == 0:
correct += 1.0
# net belivies malicious but is not
if guess == 1 and expected == 0:
normalAsThreat += 1.0
# net believes not malicious but is
if guess == 0 and expected == 1:
falsePositives += 1.0
total += 1.0 # To prevent integer division
# Normal has reversed stats
if successField == "normal":
tempNormal = normalAsThreat
normalAsThreat = falsePositives
falsePositives = tempNormal
returnData = [correct, total, correctOfType, totalOfType, falsePositives, sendLower, normalAsThreat]
return_dict[x] = returnData
def testNet(self, net, threshold, fields, successField, ids):
correct = 0
total = 0
correctOfType = 0
totalOfType = 0
falsePositives = 0
normalAsThreat = 0
sendLower = []
x = 0
threshold = float(threshold)
db = Database();
# Fetch ids for splitting
if (ids == None):
ids = db.getAllIds()
idsSet = np.array_split(ids, THREADS)
start = time.time()
# Setup return data from threads
manager = multiprocessing.Manager()
return_dict = manager.dict()
processes = []
# Create thread for each set of work
for idsInnerSet in idsSet:
x += 1
# Delegate work to new process
thread = multiprocessing.Process(target = self.testNetInner , args = (x, return_dict, net, threshold, fields, successField, idsInnerSet))
thread.start()
processes.append(thread)
# Wait for processes to finish
for i in range(THREADS):
processes[i].join()
# Add back all the return data
for threadReturnData in return_dict.values():
correct += threadReturnData[0]
total += threadReturnData[1]
correctOfType += threadReturnData[2]
totalOfType += threadReturnData[3]
falsePositives += threadReturnData[4]
sendLower += threadReturnData[5]
normalAsThreat += threadReturnData[6]
end = time.time()
# Calculate percent correctly determined
if (total > 0):
percent = correct/total
else:
percent = 1
percent *= 100.0
# Total of type
percentOfTotal = 0
if (totalOfType != 0):
percentOfTotal = correctOfType/totalOfType*100
else:
percentOfTotal = 100
quality = (percent + percentOfTotal) / 2
# Print results
print("Threshold: " + str(threshold));
print("Correct: " + str(correct) + ", incorrect: " + str(total-correct) + ", of a total of: " + str(total))
print("Correctly determined " + str(percent) + "% of connections")
print("With " + str(totalOfType) + " of type " + successField + ", found " + str(correctOfType) + " of the " + str(totalOfType) + " which is " + str(percentOfTotal) + "%")
print("Number of threats classified as normal: " + str(falsePositives))
print("Number of normals classified as threats: " + str(normalAsThreat))
print("Possible threats found: " + str( len(sendLower) ))
print("Took " + str(end - start) + " seconds")
print("Quality of net " + str(int(quality)) + "%")
# Returns percent correctly determined
return sendLower;
if __name__ == "__main__":
if len(sys.argv) < 2:
print "Usage: python testingHandlerMultithreaded.py [schema file]"
sys.exit()
testHandler = testingHandler(sys.argv[1])
testHandler.testWholeNetwork()