-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCode.py
386 lines (257 loc) · 9.85 KB
/
Code.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# -*- coding: utf-8 -*-
"""Graduation Project.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1nDOStvzX5XY5pxOBZWRj3bLH7W-kBTCj
importing a library that is not in Colaboratory
"""
!python -m pip install sidetable
"""**Upload of dataset**"""
import pandas as pd
url = 'https://raw.githubusercontent.com/sa190rah/AndroidMalwareDetection/main/drebin-215-dataset-5560malware-9476-benign.csv'
dataset = pd.read_csv(url)
dataset.head()
"""**Histogram chart**"""
import matplotlib.pyplot as plt
colunms = (dataset["transact"],dataset["onServiceConnected"],dataset["bindService"],dataset["attachInterface"],dataset["ServiceConnection"],
dataset["android.os.Binder"],dataset["SEND_SMS"], dataset["Ljava.lang.Class.getCanonicalName"],dataset["Ljava.lang.Class.getMethods"],
dataset["Ljava.lang.Class.cast"],dataset["Ljava.net.URLDecoder"],dataset["android.content.pm.Signature"],dataset["android.telephony.SmsManager"]
)
plt.hist(colunms, range = (0,2))
plt.title("Histogram of Dataset", size=16)
"""**Check data balance**"""
import matplotlib.pyplot as plt
import seaborn as sns
plt.figure(figsize = (10, 5))
plot= dataset["class"].value_counts().reset_index()
graph = sns.barplot(x = "class", y = "class", data=plot)
plt.title("Plot of benign and malicious applications ", size = 18)
plt.xticks(size = 15)
plt.yticks(size = 15)
plt.show()
"""**Frequencies and Percentages**"""
import sidetable
dataset.stb.freq(['class'])
"""
**Feature correlation**"""
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(150,150))
dataset_s = dataset.iloc[:,:215]
correlation = dataset_s.corr()
sns.heatmap(correlation, annot= True)
plt.title("Correlation matrix")
plt.xlabel("cell nucleus features")
plt.ylabel("cell nucleus features")
plt.show()
"""**Change last class Bening/malicious to 0/1**
B = bening = 0 /
S = Malicious = 1
"""
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
dataset['class']= le.fit_transform(dataset['class'])
dataset = dataset.apply(pd.to_numeric, errors='coerce', downcast='float')
import numpy as np
dataset.replace([np.inf, -np.inf], np.nan, inplace=True)
dataset.fillna(999, inplace=True)
print("Number of Benign data",len(dataset[dataset["class"]==0]))
print("Number of Malware data",len(dataset[dataset["class"]==1]))
"""**Train test split**
"""
from sklearn.model_selection import train_test_split
X = dataset.iloc[:,0:215].values
y = dataset.iloc[:,215].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=70)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
"""**Handle Missing data and percentage**"""
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
"""check missing data"""
dataset.isnull().sum()
"""percentage of all columns"""
#Percentage for each column
dataset.isna().mean()
#non-missing value for each column
dataset.count()
#check class have no missing values by Return a boolean (false)
dataset['class'].isna()
"""**Resampling Technique**
Random under sampling
"""
import imblearn
from imblearn.under_sampling import RandomUnderSampler
from collections import Counter
rus = RandomUnderSampler(random_state=42, replacement=True)
# fit predictor and target varialbe
x_rus, y_rus = rus.fit_resample(X_train,y_train)
print('original dataset shape:', Counter(y_train))
print('Resample dataset shape', Counter(y_rus))
"""**Algorithms**
Multi-layer Perceptron(MLP)
"""
from sklearn.neural_network import MLPClassifier
MlpClassifier =MLPClassifier()
MlpClassifier.fit(x_rus , y_rus)
name='Multi-layer Perceptron'
"""Support Vector Machine(SVM)"""
from sklearn.svm import SVC
svclassifier = SVC(kernel='linear')
svclassifier.fit(x_rus , y_rus)
name='Support Vector Machine'
"""Stochastic Gradient Descent (SGD)"""
from sklearn.linear_model import SGDClassifier
SGDmodel =SGDClassifier()
SGDmodel.fit(x_rus , y_rus)
nameSGD ='SGDClassifier'
"""GaussianNB"""
from sklearn.naive_bayes import GaussianNB
GnbClassifier =GaussianNB()
GnbClassifier.fit(x_rus , y_rus)
name='GaussianNB'
"""K-Nearest Neighbours (Knn)"""
from sklearn.neighbors import KNeighborsClassifier
Knn = KNeighborsClassifier(n_neighbors=5)
Knn.fit(x_rus , y_rus)
name='K-Nearest Neighbours'
"""Adaptive Boost"""
from sklearn.ensemble import AdaBoostClassifier
AdaBoost= AdaBoostClassifier()
AdaBoost.fit(x_rus , y_rus)
name='AdaBoostClassifier'
"""
**Ensamble method**"""
from sklearn.ensemble import VotingClassifier
VotingClassifierModelone = VotingClassifier(
estimators=[('Support Vector Machine', svclassifier),
('Multi-layer Perceptron', MlpClassifier),
('K-Nearest Neighbours', Knn),
('SGDClassifier', SGDmodel),
('AdaBoostClassifier', AdaBoost),
('GaussianNB', GnbClassifier)],
voting='hard')
VotingClassifierModelone.fit(x_rus,y_rus)
"""**Cross Validation Testing**
> Upload of new dataset
"""
import pandas as pd
url = 'https://raw.githubusercontent.com/nourasd/dataset/main/malgenome215dataset1260malware2539benign.csv'
dataset2 = pd.read_csv(url)
dataset2.head()
"""
> Encoding target colunm on new dataset
"""
def target(tipo):
if tipo == 'B':
return 0
else:
return 1
dataset2['class'] = dataset2['class'].apply(target)
dataset2.head()
"""**Cross validation**"""
from sklearn.model_selection import train_test_split
X = dataset2.iloc[:,0:215].values
y = dataset2.iloc[:,215].values
CVX_train, CVX_test, CVy_train, CVy_test = train_test_split(X, y, test_size=0.4, random_state=70)
print(CVX_train.shape, CVX_test.shape, CVy_train.shape, CVy_test.shape)
from sklearn.model_selection import cross_val_score
print(cross_val_score(svclassifier, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())
print(cross_val_score(MlpClassifier, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())
print(cross_val_score(Knn, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())
print(cross_val_score(SGDmodel, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())
print(cross_val_score(AdaBoost, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())
print(cross_val_score(GnbClassifier, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())
"""**Handling Duplicate**"""
#Identify duplicates records in the data
dupes=dataset.duplicated()
sum(dupes)
#Identify number of row before delete duplicate
length1 = len(dataset)
print(length1)
# Select duplicate rows except last occurrence based on all columns
duplicateRowsDF = dataset[dataset.duplicated(keep='last')]
print("Duplicate Rows except last occurrence based on all columns are :")
print(duplicateRowsDF)
"""**Remove Duplicate**"""
#Remove Duplicate fro the dataset
dataset.drop_duplicates(keep=False,inplace=True)
#Identify duplicates records in the data After delete it
dupes=dataset.duplicated()
sum(dupes)
#Identify number of row after delete duplicate
length1 = len(dataset)
print(length1)
import matplotlib.pyplot as plt
colunms = (dataset["class"])
plt.hist(colunms, range = (0,2))
plt.title("Histogram of Dataset", size=16)
import sidetable
dataset.stb.freq(['class'])
"""**Train test split**"""
from sklearn.model_selection import train_test_split
X = dataset.iloc[:,0:215].values
y = dataset.iloc[:,215].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=70)
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
"""**Random under sampling**"""
import imblearn
from imblearn.under_sampling import RandomUnderSampler
from collections import Counter
rus = RandomUnderSampler(random_state=42, replacement=True)
# fit predictor and target varialbe
x_rus, y_rus = rus.fit_resample(X_train,y_train)
print('original dataset shape:', Counter(y_train))
print('Resample dataset shape', Counter(y_rus))
"""**Algorithms**
Multi-layer Perceptron(MLP)
"""
from sklearn.neural_network import MLPClassifier
MlpClassifier =MLPClassifier()
MlpClassifier.fit(x_rus , y_rus)
name='Multi-layer Perceptron'
"""Support Vector Machine(SVM)"""
from sklearn.svm import SVC
svclassifier = SVC(kernel='linear')
svclassifier.fit(x_rus , y_rus)
name='Support Vector Machine'
"""Stochastic Gradient Descent (SGD)"""
from sklearn.linear_model import SGDClassifier
SGDmodel =SGDClassifier()
SGDmodel.fit(x_rus , y_rus)
nameSGD ='SGDClassifier'
"""GaussianNB
"""
from sklearn.naive_bayes import GaussianNB
GnbClassifier =GaussianNB()
GnbClassifier.fit(x_rus , y_rus)
name='GaussianNB'
"""K-Nearest Neighbours (Knn)"""
from sklearn.neighbors import KNeighborsClassifier
Knn = KNeighborsClassifier(n_neighbors=5)
Knn.fit(x_rus , y_rus)
name='K-Nearest Neighbours'
"""Adaptive Boost"""
from sklearn.ensemble import AdaBoostClassifier
AdaBoost= AdaBoostClassifier()
AdaBoost.fit(x_rus , y_rus)
name='AdaBoostClassifier'
"""**Ensamble method**"""
from sklearn.ensemble import VotingClassifier
VotingClassifierModel = VotingClassifier(
estimators=[('Support Vector Machine', svclassifier),
('Multi-layer Perceptron', MlpClassifier),
('K-Nearest Neighbours', Knn),
('SGDClassifier', SGDmodel),
('AdaBoostClassifier', AdaBoost),
('GaussianNB', GnbClassifier)],
voting='hard')
VotingClassifierModel.fit(x_rus,y_rus)
"""**Cross Validation Testing**
"""
from sklearn.model_selection import cross_val_score
print(cross_val_score(svclassifier, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())
print(cross_val_score(MlpClassifier, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())
print(cross_val_score(Knn, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())
print(cross_val_score(SGDmodel, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())
print(cross_val_score(AdaBoost, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())
print(cross_val_score(GnbClassifier, CVX_test, CVy_test, cv=10, scoring ='accuracy').mean())