-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathModel_CatBoost.py
More file actions
204 lines (177 loc) · 10.5 KB
/
Copy pathModel_CatBoost.py
File metadata and controls
204 lines (177 loc) · 10.5 KB
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
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import train_test_split,cross_val_score
from sklearn.metrics import accuracy_score,confusion_matrix,roc_auc_score,mean_squared_error,roc_curve
import warnings
import lightgbm as lgb
import pickle
from sklearn.model_selection import KFold
from xgboost import XGBClassifier
warnings.simplefilter(action='ignore', category=FutureWarning)
dtypes = {
'MachineIdentifier': 'category',
'ProductName': 'category',
'EngineVersion': 'category',
'AppVersion': 'category',
'AvSigVersion': 'category',
'IsBeta': 'int8',
'RtpStateBitfield': 'float16',
'IsSxsPassiveMode': 'int8',
'DefaultBrowsersIdentifier': 'float16',
'AVProductStatesIdentifier': 'float32',
'AVProductsInstalled': 'float16',
'AVProductsEnabled': 'float16',
'HasTpm': 'int8',
'CountryIdentifier': 'int16',
'CityIdentifier': 'float32',
'OrganizationIdentifier': 'float16',
'GeoNameIdentifier': 'float16',
'LocaleEnglishNameIdentifier': 'int8',
'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': 'float16',
'Census_OEMModelIdentifier': 'float32',
'Census_ProcessorCoreCount': 'float16',
'Census_ProcessorManufacturerIdentifier': 'float16',
'Census_ProcessorModelIdentifier': 'float16',
'Census_ProcessorClass': 'category',
'Census_PrimaryDiskTotalCapacity': 'float32',
'Census_PrimaryDiskTypeName': 'category',
'Census_SystemVolumeTotalCapacity': 'float32',
'Census_HasOpticalDiskDrive': 'int8',
'Census_TotalPhysicalRAM': 'float32',
'Census_ChassisTypeName': 'category',
'Census_InternalPrimaryDiagonalDisplaySizeInInches': 'float16',
'Census_InternalPrimaryDisplayResolutionHorizontal': 'float16',
'Census_InternalPrimaryDisplayResolutionVertical': 'float16',
'Census_PowerPlatformRoleName': 'category',
'Census_InternalBatteryType': 'category',
'Census_InternalBatteryNumberOfCharges': 'float32',
'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'
}
# start = time.time()
# train_df = pd.read_csv('train.csv', dtype=dtypes)
# print('Train data loaded in '+str(round(time.time()-start,2))+' seconds.\n')
# column_names=list(train_df.columns.values)
# print('Columns originally in Train: '+str(len(column_names))+'\n')
# RemoveColumns = ['PuaMode', 'Census_ProcessorClass', 'DefaultBrowsersIdentifier', 'Census_IsFlightingInternal', 'Census_InternalBatteryType', 'Census_ThresholdOptIn','Census_IsWIMBootEnabled', 'SmartScreen', 'OrganizationIdentifier', 'SMode']
# #SMode due to it being removed in Test data
# train_df.drop(RemoveColumns, axis=1, inplace=True)
# train_column_names=list(train_df.columns.values)
# print('Columns after removing in Train: '+str(len(train_column_names))+'\n')
# print('Columns removed: ',RemoveColumns,'\n')
# def fill_with_max(df):
# x = df.value_counts().argmax()
# df.fillna(x,inplace = True)
# column_names=list(train_df.columns.values)
# for column in column_names:
# fill_with_max(train_df[column])
# train_df_category = train_df.select_dtypes(include='category')
# #start = time.time()
# for i in range(len(train_df_category.columns)):
# labelencoder_X_i = LabelEncoder()
# train_df[train_df_category.columns[i]] = labelencoder_X_i.fit_transform(train_df[train_df_category.columns[i]])
#print(train_df.columns[i])
#print(time.time()-start)
# for i in range(len(train_df_category.columns)):
# train_df[train_df_category.columns[i]] = train_df[train_df_category.columns[i]].astype(np.int8)
#print(train_df.info())
#print(train_df.columns)
#print(len(train_df.columns))
# start = time.time()
# onehotencoder = OneHotEncoder(categorical_features=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14],sparse = False)
# train_df_final_coded = onehotencoder.fit_transform(train_df_final)
# print(time.time()-start)
#train_df.to_csv('ModelTrain.csv', index=False)
start = time.time()
train = pd.read_csv('ModelTrain.csv')
#,dtype=dtypes
print('Train data loaded in '+str(round(time.time()-start,2))+' seconds.\n')
#train['MachineIdentifier'] = train.index.astype('uint32')
#gc.collect()
X = train.drop('HasDetections',axis=1)
X = X.iloc[:].values
Y = train['HasDetections'].values
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.5, random_state = 0)
def plotRoc(testLabels, y_pred_probabilities, label):
oneHotEncoding = np.zeros([testLabels.shape[0], 10])
y_pred_probabilities = y_pred_probabilities.T
for i in range(testLabels.shape[0]):
oneHotEncoding[i][testLabels[i]] = 1
plt.figure()
oneHotEncoding = oneHotEncoding.T
ClassSize = 0
for i in range (1):
auc_score = roc_auc_score(oneHotEncoding[i], y_pred_probabilities[i])
fpr, tpr, thresholds = roc_curve(oneHotEncoding[i], y_pred_probabilities[i])
ClassSize+=1
plt.plot(fpr, tpr, label="Class: " + str(i) + ": " + str(auc_score)[0:5], linewidth=0.5)
print(ClassSize)
plt.legend(loc="lower right")
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.plot([0, 1], [0, 1], 'k--', linewidth=2)
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curves for ' + label)
plt.savefig(label+'.png')
m = CatBoostRegressor(iterations=100,learning_rate=0.02,depth=12,eval_metric='RMSE',random_seed = 23,bagging_temperature = 0.2,od_type='Iter',metric_period = 75,od_wait=100)
m.fit(X_train, Y_train,eval_set=(X_test,Y_test),cat_features=categorical_features_pos,use_best_model=True,verbose=True)
m = lgb.train(params,d_train,100)
dict1={}
modelname="CatBoost_Model.pkl"
dict1['model']=m
joblib.dump(dict1,open(modelname,'wb'))
#m.fit(X_train[:100], Y_train[:100])
YProb = m.predict_proba(X_test)
YPred = m.predict(X_test)
print(confusion_matrix(Y_test, YPred))
print(np.mean(Y_test==YPred)*100)
plotRoc(Y_test,YProb,'ROC_Curve')