-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmalware anlaysis hackathon (1).py
2090 lines (1230 loc) · 46.1 KB
/
malware anlaysis hackathon (1).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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# Put this when it's called
from sklearn.model_selection import train_test_split
from sklearn.model_selection import learning_curve
from sklearn.model_selection import validation_curve
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
# In[3]:
def draw_missing_data_table(df):
total = df.isnull().sum().sort_values(ascending=False)
percent = (df.isnull().sum()/df.isnull().count()).sort_values(ascending=False)
missing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])
return missing_data
# In[4]:
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
plt.figure()
plt.title(title)
if ylim is not None:
plt.ylim(*ylim)
plt.xlabel("Training examples")
plt.ylabel("Score")
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
plt.grid()
plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1,
color="r")
plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Validation score")
plt.legend(loc="best")
return plt
# In[5]:
def plot_validation_curve(estimator, title, X, y, param_name, param_range, ylim=None, cv=None,
n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
train_scores, test_scores = validation_curve(estimator, X, y, param_name, param_range, cv)
train_mean = np.mean(train_scores, axis=1)
train_std = np.std(train_scores, axis=1)
test_mean = np.mean(test_scores, axis=1)
test_std = np.std(test_scores, axis=1)
plt.plot(param_range, train_mean, color='r', marker='o', markersize=5, label='Training score')
plt.fill_between(param_range, train_mean + train_std, train_mean - train_std, alpha=0.15, color='r')
plt.plot(param_range, test_mean, color='g', linestyle='--', marker='s', markersize=5, label='Validation score')
plt.fill_between(param_range, test_mean + test_std, test_mean - test_std, alpha=0.15, color='g')
plt.grid()
plt.xscale('log')
plt.legend(loc='best')
plt.xlabel('Parameter')
plt.ylabel('Score')
plt.ylim(ylim)
# In[6]:
df = pd.read_csv(r'C:\Users\Anustup\Desktop\dataset_malwares.csv')
df_raw = df.copy()
# In[7]:
df.head()
# In[8]:
df.describe()
# In[9]:
draw_missing_data_table(df)
# In[10]:
df.drop('e_magic', axis=1, inplace=True)
df.head()
# In[11]:
value = 1000
df['e_cp'].fillna(1000, inplace=True)
df['e_cp'].max()
# In[12]:
df.drop(df[pd.isnull(df['e_cblp'])].index, inplace=True)
df[pd.isnull(df['e_cblp'])]
# In[13]:
df.drop('e_cblp', axis=1, inplace=True)
df.head()
# In[14]:
df['e_cp'] = pd.Categorical(df['e_cp'])
df['e_crlc'] = pd.Categorical(df['e_crlc'])
# In[15]:
df.drop('e_cp',axis=1,inplace=True)
df.drop('e_crlc',axis=1,inplace=True)
df.head()
# In[16]:
# Drop Name and Ticket
df.drop('e_cparhdr', axis=1, inplace=True)
df.drop('e_minalloc', axis=1, inplace=True)
df.head()
# In[17]:
df = pd.get_dummies(df, drop_first=True)
df.head()
# In[18]:
# Create data set to train data imputation methods
X = df[df.loc[:, df.columns != 'e_maxalloc'].columns]
y = df['e_maxalloc']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=1)
# In[19]:
print('Inputs: \n', X_train.head())
print('Outputs: \n', y_train.head())
# In[20]:
# Fit logistic regression
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
# In[21]:
scores = cross_val_score(logreg, X_train, y_train, cv=10)
print('CV accuracy: %.3f +/- %.3f' % (np.mean(scores), np.std(scores)))
# In[22]:
# Plot learning curves
title = "Learning Curves (Logistic Regression)"
cv = 10
plot_learning_curve(logreg, title, X_train, y_train, ylim=(0.7, 1.01), cv=cv, n_jobs=1);
# In[23]:
# Plot validation curve
title = 'Validation Curve (Logistic Regression)'
param_name = 'C'
param_range = [0.001, 0.01, 0.1, 1.0, 10.0, 100.0]
cv = 10
plot_validation_curve(estimator=logreg, title=title, X=X_train, y=y_train, param_name=param_name,
ylim=(0.5, 1.01), param_range=param_range);
# In[24]:
# Restart data set
df = df_raw.copy()
df.head()
# In[25]:
df.drop('e_magic',axis=1,inplace=True)
df.drop('e_cblp',axis=1,inplace=True)
df.head()
# In[26]:
# Drop irrelevant features
df.drop(['e_cp','e_crlc','e_minalloc'], axis=1, inplace=True)
df.head()
# In[27]:
df_raw['Name'].unique()[:10]
# In[28]:
for i in df:
df['Title']=df_raw['Name'].str.extract('([A-Za-z]+)\.', expand=False) # Use REGEX to define a search pattern
df.head()
# In[29]:
df_raw['Name'].unique()[:10]
# In[30]:
# Plot bar plot (titles, age and sex)
plt.figure(figsize=(15,5))
sns.barplot(x=df['Title'], y=df_raw['e_cparhdr']);
# In[31]:
# Means per title
df_raw['Title'] = df['Title'] # To simplify data handling
means = df_raw.groupby('Title')['e_cparhdr'].mean()
means.head()
# In[32]:
# Transform means into a dictionary for future mapping
map_means = means.to_dict()
map_means
# In[33]:
# Impute ages based on titles
idx_nan_age = df.loc[np.isnan(df['e_cparhdr'])].index
df.loc[idx_nan_age,'e_cparhdr'].loc[idx_nan_age] = df['Title'].loc[idx_nan_age].map(map_means)
df.head()
# In[34]:
# Identify imputed data
df['Imputed'] = 0
df.at[idx_nan_age.values, 'Imputed'] = 1
df.head()
# In[35]:
# Plot
sns.barplot(df['e_cparhdr'],df['e_maxalloc']);
# In[36]:
# Count how many people have each of the titles
df.groupby(['e_ss'])['e_sp'].count()
# In[37]:
titles_dict = {'Anuradha': 'Other',
'Keran': 'Other',
'Keya': 'Other',
'Koyeli': 'Other',
'Adrija': 'Other',
'FATIMA': 'Other',
'Mohit dhiman': 'Other',
'Mohit Sharma': 'Other',
'Ayush': 'Other',
'Deepanjali': 'Mrs',
'Shekhar': 'Miss',
'Sanand': 'Miss',
'Vaibhav': 'Mr',
'Lavisha': 'Mrs',
'Vikas': 'Miss',
'Akhil': 'Master',
'RS BAWA': 'Other'}
# In[38]:
# Group titles
df['Title'] = df['Title'].map(titles_dict)
df['Title'].head()
# In[39]:
# Transform into categorical
df['Title'] = pd.Categorical(df['Title'])
df.dtypes
# In[42]:
# Plot
sns.barplot(x='Title', y='e_ss', data=df);
# In[44]:
# Transform into categorical
df['e_sp'] = pd.Categorical(df['e_sp'])
# In[45]:
# Plot
sns.barplot(df['e_sp'],df['e_ss']);
# In[46]:
# Plot
plt.figure(figsize=(25,10))
sns.barplot(df['e_ss'],df['e_sp'], ci=None)
plt.xticks(rotation=90);
# In[47]:
# Plot
'''
Probably, there is an easier way to do this plot. I had a problem using
plt.axvspan because the xmin and xmax values weren't
being plotted correctly. For example, I would define xmax = 12 and only
the area between 0 and 7 would be filled. This was happening because my
X-axis don't follow a regular (0, 1, ..., n) sequence. After some trial
and error, I noticed that xmin and xmax refer to the number of elements in
the X-axis coordinate that should be filled. Accordingly, I defined two
variables, x_limit_1 and x_limit_2, that count the number of elements that
should be filled in each interval. Sounds confusing? To me too.
'''
limit_1 = 12
limit_2 = 50
x_limit_1 = np.size(df[df['e_ss'] < limit_1]['e_ss'].unique())
x_limit_2 = np.size(df[df['e_ss'] < limit_2]['e_ss'].unique())
plt.figure(figsize=(25,10))
sns.barplot(df['e_ss'],df['e_sp'], ci=None)
plt.axvspan(-1, x_limit_1, alpha=0.25, color='green')
plt.axvspan(x_limit_1, x_limit_2, alpha=0.25, color='red')
plt.axvspan(x_limit_2, 100, alpha=0.25, color='yellow')
plt.xticks(rotation=90);
# In[48]:
# Bin data
df['e_ss'] = pd.cut(df['e_ss'], bins=[0, 12, 50, 200], labels=['Ayush','Keran','Deepanjali'])
df['e_ss'].head()
# In[49]:
# Plot
sns.barplot(df['e_ss'], df['e_sp']);
# In[51]:
# Plot
sns.barplot(df['e_csum'], df['e_ip']);
# In[52]:
# Plot
plt.figure(figsize=(7.5,5))
sns.boxplot(df['e_ss'], df['e_sp']);
# In[53]:
# Plot
sns.barplot(df['e_ss'], df['e_sp'], df['e_csum']);
# In[54]:
# Plot
sns.barplot(df['e_ss'], df['e_sp']);
# In[55]:
# Compare with other variables
df.groupby(['e_ss']).mean()
# In[56]:
# Relationship with age
df.groupby(['e_ss','e_sp'])['e_csum'].count()
# In[57]:
# Relationship with sex
df.groupby(['e_ss','e_sp'])['e_cs'].count()
# In[58]:
# Overview
df.head()
# In[59]:
# Drop feature
df.drop('e_cparhdr', axis=1, inplace=True)
# In[60]:
# Check features type
df.dtypes
# In[61]:
# Transform object into categorical
df['e_ss'] = pd.Categorical(df['e_sp'])
df['e_csum'] = pd.Categorical(df['e_ip'])
df.dtypes
# In[62]:
# Transform categorical features into dummy variables
df = pd.get_dummies(df, drop_first=1)
df.head()
# In[63]:
from sklearn.model_selection import train_test_split
X = df[df.loc[:, df.columns != 'e_cs'].columns]
y = df['e_cs']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.2, random_state=0)
# In[82]:
from scipy.stats import boxcox
X_train_transformed = X_train.copy()
X_train_transformed['e_ip'] = boxcox(X_train_transformed['e_ip'] + 1)[0]
X_test_transformed = X_test.copy()
X_test_transformed['e_ip'] = boxcox(X_test_transformed['e_ip'] + 1)[0]
# In[83]:
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train_transformed_scaled = scaler.fit_transform(X_train_transformed)
X_test_transformed_scaled = scaler.transform(X_test_transformed)
# In[84]:
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(degree=2).fit(X_train_transformed)
X_train_poly = poly.transform(X_train_transformed_scaled)
X_test_poly = poly.transform(X_test_transformed_scaled)
# In[68]:
# Debug
print(poly.get_feature_names())
# In[77]:
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
## Get score using original model
logreg = LogisticRegression(C=1)
logreg.fit(X_train, y_train)
scores = cross_val_score(logreg, X_train, y_train, cv=10)
print('CV accuracy (original): %.3f +/- %.3f' % (np.mean(scores), np.std(scores)))
highest_score = np.mean(scores)
## Get score using models with feature selection
for i in range(1, X_train_poly.shape[1]+1, 1):
# Select i features
select = SelectKBest(score_func=chi2, k=i)
select.fit(X_train_poly, y_train)
X_train_poly_selected = select.transform(X_train_poly)
# Model with i features selected
logreg.fit(X_train_poly_selected, y_train)
scores = cross_val_score(logreg, X_train_poly_selected, y_train, cv=10)
print('CV accuracy (number of features = %i): %.3f +/- %.3f' % (i,
np.mean(scores),
np.std(scores)))
# Save results if best score
if np.mean(scores) > highest_score:
highest_score = np.mean(scores)
std = np.std(scores)
k_features_highest_score = i
elif np.mean(scores) == highest_score:
if np.std(scores) < std:
highest_score = np.mean(scores)
std = np.std(scores)
k_features_highest_score = i
# Print the number of features
print('Number of features when highest score: %i' % k_features_highest_score)
# In[89]:
# Select features
select = SelectKBest(score_func=chi2, k=k_features_highest_score)
select.fit(X_train_poly, y_train)
X_train_poly_selected = select.transform(X_train_poly)
# In[91]:
filepath=r"C:\Users\Anustup\Desktop\dataset_malwares.csv"
# In[92]:
malwares = pd.read_csv(filepath, dtype=str)
# In[93]:
print('Found (' + str(len(malwares.index)) + ') malwares in csv file.')
# In[103]:
malwares.shape
# In[105]:
malwares.isnull().sum()
# In[107]:
malwares.columns
# In[108]:
data1=malwares.dropna(how="any",axis=0)
data1.head()
# In[110]:
data1["e_magic"].value_counts()
# In[115]:
data1.head()
# In[116]:
data1.tail()
# In[119]:
sns.countplot(data1["e_cblp"])
plt.show()
# In[120]:
data1["e_cblp"].value_counts().plot(kind="pie",autopct="%1.1f%%")
plt.axis("equal")
plt.show()
# In[126]:
x=data1.drop(["e_cblp","e_magic"],axis=1)
x.head()
# In[128]:
y=data1["e_magic"]
y
# In[137]:
data=pd.read_csv(r"C:\Users\Anustup\Downloads\Malware dataset.csv (3).zip")
# In[138]:
data.head()
# In[140]:
data.shape
# In[141]:
data.isnull().sum()
# In[142]:
data.columns
# In[143]:
data1=data.dropna(how="any",axis=0)
data1.head()
# In[144]:
data1["classification"].value_counts()
# In[145]:
data1['classification'] = data1.classification.map({'benign':0, 'malware':1})
# In[146]:
data.head()
# In[147]:
data.tail()
# In[148]:
sns.countplot(data1["classification"])
plt.show()
# In[149]:
data1["classification"].value_counts().plot(kind="pie",autopct="%1.1f%%")
plt.axis("equal")
plt.show()
# In[150]:
benign1=data.loc[data['classification']=='benign']
benign1["classification"].head()
# In[151]:
malware1=data.loc[data['classification']=='malware']
malware1["classification"].head()
# In[152]:
corr=data1.corr()
corr.nlargest(35,'classification')["classification"]
# In[153]:
x=data1.drop(["hash","classification",'vm_truncate_count','shared_vm','exec_vm','nvcsw','maj_flt','utime'],axis=1)
x.head()
# In[154]:
y=data1["classification"]
y
# In[155]:
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
# In[156]:
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=1)
# In[157]:
from sklearn.naive_bayes import GaussianNB
model=GaussianNB()
model.fit(x_train,y_train)
# In[158]:
pred=model.predict(x_test)
pred
# In[159]:
model.score(x_test,y_test)
# In[160]:
result=pd.DataFrame({
"Actual_Value":y_test,
"Predict_Value":pred
})
# In[161]:
result
# In[12]:
import numpy as np
import pandas as pd
import seaborn as sns
import pickle as pck
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
get_ipython().run_line_magic('matplotlib', 'inline')
# In[14]:
data = pd.read_csv(r'C:\Users\Anustup\Desktop\Malware Analysis\dataset_malwares.csv', sep=',')
#The target is Malware Column {0=Benign, 1=Malware}
X = data.drop(['Name','Malware'], axis=1)
y = data['Malware']
X_train, X_test, y_train, y_test= train_test_split(X,y, test_size=0.2, random_state=101)
X_train.head()
# In[15]:
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_train)
# In[17]:
X_new = pd.DataFrame(X_scaled, columns=X.columns)
X_new.head()
# In[18]:
skpca = PCA(n_components=55)
X_pca = skpca.fit_transform(X_new)
print('Variance sum : ', skpca.explained_variance_ratio_.cumsum()[-1])
# In[19]:
from sklearn.ensemble import RandomForestClassifier as RFC
from sklearn.metrics import classification_report, confusion_matrix
# In[20]:
model = RFC(n_estimators=100, random_state=0,
oob_score = True,
max_depth = 16,
max_features = 'sqrt')
model.fit(X_pca, y_train)
X_test_scaled = scaler.transform(X_test)
X_test_new = pd.DataFrame(X_test_scaled, columns=X.columns)
X_test_pca = skpca.transform(X_test_new)
y_pred = model.predict(X_test_pca)
print(classification_report(y_pred, y_test))
# In[21]:
sns.heatmap(confusion_matrix(y_pred, y_test), annot=True, fmt="d", cmap=plt.cm.Blues, cbar=False)
# In[22]:
from sklearn.externals import joblib
from sklearn.pipeline import Pipeline
pipe = Pipeline([('scale', scaler),('pca', skpca), ('clf', model)])
# jbolib.dumps(pipe, 'my_model')
# In[27]:
test = pd.read_csv(r'C:\Users\Anustup\Desktop\Malware Analysis\dataset_malwares.csv', sep=',')
X_to_push = test
X_testing = test.drop(['Name'], axis=1)
clf = pipe
X_testing_scaled = clf.named_steps['scale'].transform(X_testing)
X_testing_pca = clf.named_steps['pca'].transform(X_testing_scaled)
y_testing_pred = clf.named_steps['clf'].predict_proba(X_testing_pca)
pd.concat([X_to_push['Name'], pd.DataFrame(y_testing_pred) ], axis=1)
# In[28]:
from datetime import datetime
print("last update: {}".format(datetime.now()))
# In[29]:
from sklearn.naive_bayes import GaussianNB, BernoulliNB
from sklearn.metrics import accuracy_score, classification_report
from sklearn.ensemble import BaggingClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import cohen_kappa_score