forked from RachanaJayaram/MalwarePrediction
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LSTM_CNN.py
175 lines (151 loc) · 10.1 KB
/
LSTM_CNN.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
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from sklearn.preprocessing import LabelEncoder
import math
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from sklearn.model_selection import train_test_split
from keras.callbacks import LearningRateScheduler
from keras.optimizers import Adam
from keras import callbacks
from sklearn.metrics import roc_auc_score
from encoding import *
from keras.layers.convolutional import Conv1D
from keras.layers.convolutional import MaxPooling1D
dtypes = {
'MachineIdentifier': 'category',
'ProductName': 'category',
'EngineVersion': 'category',
'AppVersion': 'category',
'AvSigVersion': 'category',
'IsBeta': 'int8',
'RtpStateBitfield': 'float16',
'IsSxsPassiveMode': 'int8',
'DefaultBrowsersIdentifier': 'float32',
'AVProductStatesIdentifier': 'float32',
'AVProductsInstalled': 'float16',
'AVProductsEnabled': 'float16',
'HasTpm': 'int8',
'CountryIdentifier': 'int16',
'CityIdentifier': 'float32',
'OrganizationIdentifier': 'float16',
'GeoNameIdentifier': 'float16',
'LocaleEnglishNameIdentifier': 'int16',
'Platform': 'category',
'Processor': 'category',
'OsVer': 'category',
'OsBuild': 'int16',
'OsSuite': 'int16',
'OsPlatformSubRelease': 'category',
'OsBuildLab': 'category',
'SkuEdition': 'category',
'IsProtected': 'float16',
'AutoSampleOptIn': 'int8',
'PuaMode': 'category',
'SMode': 'float16',
'IeVerIdentifier': 'float16',
'SmartScreen': 'category',
'Firewall': 'float16',
'UacLuaenable': 'float32',
'Census_MDC2FormFactor': 'category',
'Census_DeviceFamily': 'category',
'Census_OEMNameIdentifier': 'float32',
'Census_OEMModelIdentifier': 'float32',
'Census_ProcessorCoreCount': 'float16',
'Census_ProcessorManufacturerIdentifier': 'float16',
'Census_ProcessorModelIdentifier': 'float32',
'Census_ProcessorClass': 'category',
'Census_PrimaryDiskTotalCapacity': 'float64',
'Census_PrimaryDiskTypeName': 'category',
'Census_SystemVolumeTotalCapacity': 'float64',
'Census_HasOpticalDiskDrive': 'int8',
'Census_TotalPhysicalRAM': 'float32',
'Census_ChassisTypeName': 'category',
'Census_InternalPrimaryDiagonalDisplaySizeInInches': 'float32',
'Census_InternalPrimaryDisplayResolutionHorizontal': 'float32',
'Census_InternalPrimaryDisplayResolutionVertical': 'float32',
'Census_PowerPlatformRoleName': 'category',
'Census_InternalBatteryType': 'category',
'Census_InternalBatteryNumberOfCharges': 'float64',
'Census_OSVersion': 'category',
'Census_OSArchitecture': 'category',
'Census_OSBranch': 'category',
'Census_OSBuildNumber': 'int16',
'Census_OSBuildRevision': 'int32',
'Census_OSEdition': 'category',
'Census_OSSkuName': 'category',
'Census_OSInstallTypeName': 'category',
'Census_OSInstallLanguageIdentifier': 'float16',
'Census_OSUILocaleIdentifier': 'int16',
'Census_OSWUAutoUpdateOptionsName': 'category',
'Census_IsPortableOperatingSystem': 'int8',
'Census_GenuineStateName': 'category',
'Census_ActivationChannel': 'category',
'Census_IsFlightingInternal': 'float16',
'Census_IsFlightsDisabled': 'float16',
'Census_FlightRing': 'category',
'Census_ThresholdOptIn': 'float16',
'Census_FirmwareManufacturerIdentifier': 'float16',
'Census_FirmwareVersionIdentifier': 'float32',
'Census_IsSecureBootEnabled': 'int8',
'Census_IsWIMBootEnabled': 'float16',
'Census_IsVirtualDevice': 'float16',
'Census_IsTouchEnabled': 'int8',
'Census_IsPenCapable': 'int8',
'Census_IsAlwaysOnAlwaysConnectedCapable': 'float16',
'Wdft_IsGamer': 'float16',
'Wdft_RegionIdentifier': 'float16',
'HasDetections': 'int8'
}
train=pd.read_csv("../data/train.csv",dtype=dtypes)
train.drop(['MachineIdentifier', 'LocaleEnglishNameIdentifier','Census_InternalBatteryType','Census_InternalBatteryNumberOfCharges','Census_OSInstallLanguageIdentifier','Census_InternalPrimaryDiagonalDisplaySizeInInches','Census_InternalPrimaryDisplayResolutionHorizontal','Census_InternalPrimaryDisplayResolutionVertical','Census_OSUILocaleIdentifier','Census_IsTouchEnabled','Census_IsPenCapable','Census_IsAlwaysOnAlwaysConnectedCapable','Wdft_RegionIdentifier'], axis = 1,inplace=True) #d
train.drop(['PuaMode', 'Census_ProcessorClass','DefaultBrowsersIdentifier','Census_IsFlightingInternal'], axis = 1,inplace=True) # droping features with more than 80% empty values
train.drop(['Census_IsWIMBootEnabled', 'IsBeta','Census_IsFlightsDisabled','AutoSampleOptIn','Census_ThresholdOptIn','SMode','Census_IsPortableOperatingSystem','Census_DeviceFamily','UacLuaenable','Census_IsVirtualDevice'], axis = 1,inplace=True) # droping features unbalancedness >= 99
trans_dict = {
'off': 'Off', '': '2', '': '1', 'on': 'On', 'requireadmin': 'RequireAdmin', 'OFF': 'Off',
'Promt': 'Prompt', 'requireAdmin': 'RequireAdmin', 'prompt': 'Prompt', 'warn': 'Warn',
'00000000': '0', '': '3', np.nan: 'RequireAdmin'
}
train.replace({'SmartScreen': trans_dict}, inplace=True)
train.replace({'OrganizationIdentifier': {np.nan: 0}}, inplace=True)
train['SmartScreen'] = train.SmartScreen.astype('category')
category_cols = train.select_dtypes(include='category').columns.tolist()
train=train.dropna()
FE = ['AppVersion','AvSigVersion','Census_OSVersion']
OHE = [ 'IsSxsPassiveMode',
'AVProductStatesIdentifier','AVProductsInstalled', 'AVProductsEnabled',
'CountryIdentifier', 'CityIdentifier',
'GeoNameIdentifier', 'OsBuild', 'OsSuite',
'SmartScreen','Census_MDC2FormFactor',
'Census_OEMNameIdentifier',
'Census_ProcessorCoreCount',
'Census_ProcessorModelIdentifier',
'Census_PrimaryDiskTotalCapacity', 'Census_PrimaryDiskTypeName',
'Census_HasOpticalDiskDrive',
'Census_TotalPhysicalRAM', 'Census_ChassisTypeName',
'Census_PowerPlatformRoleName',
'Census_OSEdition',
'Census_GenuineStateName','Census_ActivationChannel',
'Census_FirmwareManufacturerIdentifier', 'Wdft_IsGamer',]
cols = []; dd = []
for x in FE:
cols += encode_FE(train,x)
for x in OHE:
tmp = encode_OHE(train,x,0.005,5)
cols += tmp[0]; dd.append(tmp[1])
print('Encoded',len(cols),'new variables')
for x in FE+OHE:
del train[x]
print('Removed original',len(FE+OHE),'variables')
train.drop(['EngineVersion', 'RtpStateBitfield','IeVerIdentifier','Platform','SkuEdition','Census_OSSkuName','Census_OSBuildNumber','Processor'], axis = 1,inplace=True) # droping features with more correlation coefficient > 0.90
X_train, X_val, Y_train, Y_val = train_test_split(train[cols],train['HasDetections'] ,test_size = 0.5)
model = Sequential()
model.add(Conv1D(filters=32, kernel_size=3, padding='same', activation='relu'))
model.add(MaxPooling1D(pool_size=1))
model.add(LSTM(256))
model.add(Dense(1,activation='sigmoid'))
model.compile(optimizer=Adam(lr=0.01), loss="binary_crossentropy", metrics=["accuracy"])
annealer = LearningRateScheduler(lambda x: 1e-2 * 0.95 ** x)
model.fit(X_train,Y_train, batch_size=1024, epochs = 20, callbacks=[annealer,
printAUC(X_train, Y_train)], validation_data = (X_val,Y_val), verbose=1)