-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtransformers_deep_learning.py
244 lines (176 loc) · 8.09 KB
/
transformers_deep_learning.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
from bigdl.util.common import *
from pyspark import keyword_only
from pyspark.ml import Transformer
from pyspark.sql.types import IntegerType, ArrayType, FloatType
from pyspark.sql import functions as F
import numpy as np
from pyspark.sql import Row
# Transforms the dataframe to the required format to train the model
def transform_sample(row):
values = np.array(row['features'])
sample = Sample.from_ndarray(values, values)
return sample
# Calculates the percentile of the MSE to consider anomalies
def percentile_threshold(ardd, percentile):
assert 100 >= percentile > 0, "percentile should be larger then 0 and smaller or equal to 100"
return ardd.sortBy(lambda x: x).zipWithIndex().map(lambda x: (x[1], x[0])) \
.lookup(np.ceil(ardd.count() / 100 * percentile - 1))[0]
# Obtains the mean and std values to normalize the variables described in feat_to_norm
feat_to_norm = ["tdur_log", "ipkt_log", "ibyt_log"]
def get_stats(df):
# Obtain the mean and std values from the train database and use them to normalize train and test
normalization_values = {}
for feat in feat_to_norm:
normalization_values[feat] = {}
mean = df.select(F.avg(feat)).collect()[0][0]
std = df.select(F.stddev(feat)).collect()[0][0]
normalization_values[feat]['mean'] = mean
normalization_values[feat]['std'] = std
return normalization_values
# Applies a logarithm transform to the variables tdur, ipkt and ibyt
class ToLog(Transformer):
@keyword_only
def __init__(self):
super(ToLog, self).__init__()
def _transform(self, df):
df = df.withColumn('tdur_log', F.log(df.tdur + 1)).withColumn('ipkt_log', F.log(df.ipkt + 1)).withColumn(
'ibyt_log',F.log(df.ibyt))
return df
# Transforms the protocol string into one-hot encoding using a dictionary
class ProtocolOneHot(Transformer):
@keyword_only
def __init__(self):
super(ProtocolOneHot, self).__init__()
def _transform(self, df):
def transform_protocol(proto):
list_prots = ['UDP', 'TCP', 'ICMP', 'IGMP']
output_list = [0, 0, 0, 0, 0]
found_prot = False
for i in range(len(list_prots)):
if list_prots[i] in proto:
output_list[i] += 1
found_prot = True
break
if found_prot == False:
output_list[len(list_prots)] += 1
return output_list
proto_transform = F.udf(lambda z: transform_protocol(z), ArrayType(IntegerType()))
df = df.withColumn('proto_onehot', proto_transform(df.proto))
return df
# Transforms the flag string into one-hot encoding using a dictionary
class FlagOneHot(Transformer):
@keyword_only
def __init__(self):
super(FlagOneHot, self).__init__()
def _transform(self, df):
def process_flag(flag):
list_flags = ['A', 'S', 'F', 'R', 'P', 'U', 'X']
flag_array = [0, 0, 0, 0, 0, 0]
contains_x = False
for i in range(len(list_flags)):
for letter in flag:
if letter == list_flags[i]:
flag_array[i] += 1
if letter == 'X':
contains_x = True
if contains_x:
return [1, 1, 1, 1, 1, 1]
else:
return flag_array
flag_transform = F.udf(lambda z: process_flag(z), ArrayType(IntegerType()))
df = df.withColumn('flag_onehot', flag_transform(df.flag))
return df
# Trasforms ports into one-hot encoding (0 < port < 1024), other rules can be defined if need be
class PortProcessing(Transformer):
@keyword_only
def __init__(self, source = False):
super(PortProcessing, self).__init__()
self.source = source
def _transform(self, df):
def process_port(port):
if port > 1024:
return 1
else:
return 0
port_transform = F.udf(lambda z: process_port(z), IntegerType())
if self.source:
df = df.withColumn('sport_transform', port_transform(df.sport))
else:
df = df.withColumn('dport_transform', port_transform(df.dport))
return df
# Scales the variables using the mean and std values provided by a dictionary
class StandardScaler(Transformer):
@keyword_only
def __init__(self, data_dict):
super(StandardScaler, self).__init__()
self.tdur_mean = data_dict['tdur_log']['mean']
self.tdur_std = data_dict['tdur_log']['std']
self.ipkt_mean = data_dict['ipkt_log']['mean']
self.ipkt_std = data_dict['ipkt_log']['std']
self.ibyt_mean = data_dict['ibyt_log']['mean']
self.ibyt_std = data_dict['ibyt_log']['std']
def _transform(self, df):
df = df.withColumn('tdur_log_standarized', (df.tdur_log - self.tdur_mean)/self.tdur_std)\
.withColumn('ipkt_log_standarized', (df.ipkt_log - self.ipkt_mean)/self.ipkt_std)\
.withColumn('ibyt_log_standarized', (df.ipkt_log - self.ibyt_mean)/self.ibyt_std)\
return df
# Joins all the features into a single variable in the dataframe, required to make work bigdl
class CreateFeatures(Transformer):
@keyword_only
def __init__(self):
super(CreateFeatures, self).__init__()
def _transform(self, df):
def process(proto_onehot, flag_onehot, tdur, ipkt, ibyt, sport, dport):
features = proto_onehot + flag_onehot
features.append(tdur)
features.append(ipkt)
features.append(ibyt)
features.append(sport)
features.append(dport)
features = [float(i) for i in features]
return features
transformer = F.udf(process, ArrayType(FloatType()))
df = df.withColumn('features', transformer(df.proto_onehot, df.flag_onehot, df.tdur_log_standarized, df.ipkt_log_standarized, df.ibyt_log_standarized, df.sport_transform, df.dport_transform))
return df
def helper(item):
row = item[0]
temp = row.asDict()
temp['predictions'] = item[1].tolist()
features = np.array(temp['features'])
predictions = np.array(temp['predictions'])
mse = np.linalg.norm(features - predictions)
temp['score'] = float(mse)
return Row(**temp)
# ---------------------ROIG-------------------------#
def wannacryLabels(df):
if not 'label' in df.columns:
df = df.withColumn('label', F.when((df.sip == "192.168.116.138") |
(df.sip == "192.168.116.143") |
(df.dip == "192.168.116.149") |
(df.dip == "192.168.116.150") |
(df.dip == "192.168.116.172") |
(df.dip == "192.168.116.254") |
(df.dip == "192.168.116.255") |
(df.sip == "192.168.116.138") |
(df.sip == "192.168.116.143") |
(df.sip == "192.168.116.149") |
(df.sip == "192.168.116.150") |
(df.sip == "192.168.116.172") |
(df.sip == "192.168.116.254") |
(df.sip == "192.168.116.255"),
"WANNACRY").otherwise("BENIGN"))
directori = "hdfs:///user/spotuser/article/test.csv"
print(df.show(5))
df = df.select(df.tdur,
df.sport,
df.dport,
df.proto,
df.sip,
df.dip,
df.ipkt.cast(IntegerType()),
df.ibyt.cast(IntegerType()),
df.opkt.cast(IntegerType()),
df.obyt.cast(IntegerType()),
df.score,
df.label)
df.write.csv(directori, mode="append")