-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.py
328 lines (287 loc) · 11.3 KB
/
utils.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import numpy as np
import os
import time
from sklearn.model_selection import train_test_split
class load_data:
def __init__(self, dataset, eliminated=False):
self.dataset = dataset
self.eliminated = eliminated
self.path_original = __file__.replace("utils.py","datasets/original_datasets/"+dataset)
if dataset == 'hdfs':
self.path_original_label = __file__.replace("utils.py","datasets/original_datasets/anomaly_label.csv")
if self.eliminated:
self.path = __file__.replace("utils.py","datasets/splited_datasets/"+dataset+"_eli")
else:
self.path = __file__.replace("utils.py","datasets/splited_datasets/"+dataset)
print(self.path)
def reload_data(self):
dirs = os.listdir(self.path)
x_train = []
x_test = []
y_train = []
y_test = []
print(dirs)
for dir in dirs:
data = np.load(os.path.join(self.path,dir), allow_pickle=True)
x_train.append(data["x_train"])
x_test.append(data["x_test"])
y_train.append(data["y_train"])
y_test.append(data["y_test"])
return x_train, x_test, y_train, y_test
def eliminate(self, data_eliminated, data_formed, total_label):
matrix = []
new_data = []
label = []
for idx_r, x_r in enumerate(data_formed):
temp_vector = [0]*len(data_eliminated)
for idx, x in enumerate(x_r):
vec_idx = data_eliminated.index(x)
tf = x_r.count(x)
temp_vector[vec_idx] = tf
if temp_vector not in matrix:
matrix.append(temp_vector)
new_data.append(x_r)
label.append(total_label[idx_r])
return new_data, label
def naive_agg(self, data_eliminated, data_total):
vec_data = []
for data in data_total:
temp_vector = [0]*len(data_eliminated)
for d in data:
vec_idx = data_eliminated.index(d)
temp_vector[vec_idx] += 1
vec_data.append(temp_vector)
return vec_data
def load_and_split_hdfs(self, train_ratio=0.8, times=1):
f_label = open(self.path_original_label,'rb')
lines = f_label.readlines()
label_dict = {}
count_label = 0
for line in lines:
if count_label == 0:
count_label += 1
continue
line = line.decode('utf-8')[:-2].split(',')
count_label += 1
if line[1] == 'Normal':
current_label = "-"
else:
current_label = "+"
label_dict[line[0]] = current_label
count_label += 1
total_time = 0
f = open(self.path_original,'rb')
total_data = {}
data_eliminated = []
total_label = []
lines = f.readlines()
count = 0
debug_content = []
for line in lines:
#print(line.decode('utf-8'))
line = line.decode('utf-8')[:-2].split(' ')
start_time = time.time()
content = line[5:]
new_content = []
for c in content:
flag = True
if c.startswith('blk_') and flag:
flag = False
current_blk = c.strip('.')
if current_blk not in total_data.keys():
total_data[current_blk] = []
#print(count,current_blk)
for element in c:
if element.isdigit(): #whether token contains digits
flag = False
break
if flag:
new_content.append(c)
if new_content not in debug_content:
#print(new_content)
debug_content.append(new_content)
total_data[current_blk].append(new_content)
if new_content not in data_eliminated:
data_eliminated.append(new_content)
end_time = time.time()
total_time += (end_time-start_time)
count += 1
if count % 500000 == 0:
print("Data pre_loading:",count,"/",len(lines), "Current event types:",len(data_eliminated))
total_data_temp = []
start_time = time.time()
for key in total_data.keys():
total_label.append(label_dict[key])
total_data_temp.append(total_data[key])
end_time = time.time()
total_time += (end_time-start_time)
# whether eliminate (deduplicate)
if self.eliminated:
total_data_temp, total_label = self.eliminate(data_eliminated, total_data_temp, total_label)
start_time = time.time()
total_data_temp = self.naive_agg(data_eliminated, total_data_temp)
end_time = time.time()
total_time+=(end_time-start_time)
for t in range(times):
#pdb.set_trace()
x_train_temp, x_test_temp, y_train, y_test = train_test_split(total_data_temp, total_label, test_size=1-train_ratio)
start_time = time.time()
x_train, x_test = x_train_temp, x_test_temp
end_time = time.time()
total_time += (end_time-start_time)
print("Total preprocessing time is:",total_time)
print(t, len(x_train))
if not os.path.exists(self.path):
os.mkdir(self.path)
np.savez(os.path.join(self.path,"shuffle_"+str(t)+".npz"), x_train=x_train, x_test=x_test, y_train=y_train, y_test=y_test)
def load_and_split(self, preprocess=True, data_range=[0,10000000], train_ratio=0.8, window_size=1, step_size=1):
f = open(self.path_original,'rb')
total_data = []
total_data_window = []
total_label = []
total_label_window = []
count = 0
first_occurences = []
error_count = 0
error_types = []
total_time = 0
lines = line = f.readlines()
for idx, line in enumerate(lines):
try:
if count < data_range[0]:
count += 1
continue
line = line.decode('utf-8')[:-1]
line = line.split(' ')
start_time = time.time()
if self.dataset in ['spirit','tbird','bgl']:
content = line[8:]
elif self.dataset == 'liberty':
content = line[7:]
label = line[0]
if preprocess:
new_content = []
for c in content:
flag = True
char = False
for element in c:
if element.isdigit():
flag = False
break
if element.isalpha():
char = True
if flag and char:
new_content.append(c)
total_data.append(new_content)
else:
total_data.append(content)
if label == '-':
total_label.append(label)
else:
total_label.append('+')
if label != '-':
if label not in error_types:
error_types.append(label)
first_occurences.append(count)
error_count += 1
if count >= window_size+data_range[0]-1 and (count-data_range[0]-window_size+1)%step_size==0:
temp_data = total_data[count-data_range[0]-window_size+1:count-data_range[0]+1]
total_data_window.append(temp_data[0])
if '+' in total_label[count-data_range[0]-window_size+1:count-data_range[0]+1]:
total_label_window.append("+")
else:
total_label_window.append("-")
end_time = time.time()
total_time += (end_time-start_time)
count += 1
if count % 500000 == 0:
print("Data pre_loading:",count-data_range[0],"/",data_range[1]-data_range[0])
if count == data_range[1] or idx == len(lines)-1:
print("Number of error types in current data:", error_count)
print("Error types in current data:", error_types)
print("Their first occurences are:", first_occurences)
break
except Exception as e:
print('decode error!!!')
print(len(total_data_window))
print("Preprocessing time (w./o vectorization):",total_time)
# No shuffle
train_size = int(train_ratio*len(total_data_window))
x_train, x_test, y_train, y_test = total_data_window[:train_size], total_data_window[train_size:],\
total_label_window[:train_size], total_label_window[train_size:]
if not os.path.exists(self.path):
os.mkdir(self.path)
np.savez(os.path.join(self.path,"unshuffle.npz"),x_train=x_train, x_test=x_test, y_train=y_train, y_test=y_test)
class evaluation:
def __init__(self, labels, labels_pre):
self.labels = labels
self.labels_pre = labels_pre
def calc_metrics(self):
tp = 0
tn = 0
fp = 0
fn = 0
for idx, l in enumerate(self.labels_pre):
if l=="-" and self.labels[idx]=="-":
tn += 1
elif l == "-" and self.labels[idx] != "-":
fn += 1
elif l != "-" and self.labels[idx] == "-":
fp += 1
else:
tp += 1
#print(tp,fp,tn,fn)
if (tp+fp)==0:
prec = 0
else:
prec = tp/(tp+fp)
if (tp+fn)==0:
rec = 0
else:
rec = tp/(tp+fn)
if (prec+rec)==0:
f=0
else:
f = 2*prec*rec/(prec+rec)
if (fp + tn) == 0:
spec = 0
else:
spec = tn / (fp + tn)
bal = (spec + rec) / 2
return prec, rec, f, spec, bal
def calc_with_windows(self,window=20,step=1):
tp = 0
tn = 0
fp = 0
fn = 0
idx = 0
while True:
if (idx+window) >= len(self.labels_pre):
break
flag_pre = "-"
for l_pre in self.labels_pre[idx:idx+window]:
if l_pre != "-":
flag_pre = "+"
flag_true = "-"
for l_true in self.labels[idx:idx+window]:
if l_true != "-":
flag_true = "+"
if flag_pre=="-" and flag_true=="-":
tn += 1
elif flag_pre == "-" and flag_true != "-":
fn += 1
elif flag_pre != "-" and flag_true == "-":
fp += 1
else:
tp += 1
idx += step
prec = tp/(tp+fp)
rec = tp/(tp+fn)
f = 2*prec*rec/(prec+rec)
# spec = tn / (fp + tn)
if (fp + tn) == 0:
spec = 0
else:
spec = tn / (fp + tn)
bal = (spec + rec) / 2
return prec, rec, f, spec, bal