-
Notifications
You must be signed in to change notification settings - Fork 6
/
Risk-calculation-using-backward-elimination-algorithm-in-Life-Insurance.py
367 lines (282 loc) · 13 KB
/
Risk-calculation-using-backward-elimination-algorithm-in-Life-Insurance.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
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import timeit
# Importing the dataset
dataset = pd.read_csv('train.csv')
#dataset = dataset[0:5000]
X = dataset.iloc[:, 1:127].values
data = dataset.iloc[:, 1:].values
dataframe = pd.DataFrame(data, columns = dataset.columns[1:])
y = dataset.iloc[:, -1].values
# Taking care of missing data
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
imputer.fit(X[:, (11,14,16,28,33,34,35,36,37,46,51,60,68)])
X[:, (11,14,16,28,33,34,35,36,37,46,51,60,68)] = imputer.transform(X[:, (11,14,16,28,33,34,35,36,37,46,51,60,68)])
# Encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_X_1 = LabelEncoder()
produxtInfo2 = labelencoder_X_1.fit_transform(X[:, 1])
X[:, 1] = produxtInfo2
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:]
X_column_label = ['A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'B1', 'B2', 'C1',
'C2', 'C3', 'C4', 'D1', 'D2', 'D3', 'D4', 'E1']
for i in range(len(dataframe.columns)-1):
if(i == 1):
continue
else:
X_column_label.append(dataframe.columns[i])
X_dataframe = pd.DataFrame(X, columns = X_column_label)
data = X_dataframe
X = data.iloc[:, :-1].values
#Feature Scaling
#from sklearn.preprocessing import StandardScaler
#sc = StandardScaler()
#X = sc.fit_transform(X)
for i in range(len(y)):
y[i] = y[i]-1
########################################################################################
########################################################################################
########################################################################################
######################################################################################
######################################################################################
######################################################################################
###################################################################################
#######################################################################
#Building optimal model using Backward Elimination
import statsmodels.formula.api as sm
X = np.append(arr = np.ones(shape = (len(X), 1)).astype(int), values = X, axis = 1)
b = []
for i in range(len(X[1])):
b.append(i)
display_p = []
display_length = []
display_index = []
display_number = []
display_r2 = []
display_adj_r2 = []
accuracy_percent = []
training_time = []
testing_time = []
########################################## p = 0.05 #########################################################
List_of_column_no_removed = []
maxx = 1.0
while( maxx > 0.05):
#ij = 0
#while(ij < 0.01):
X_opt = X[: , b]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
summary = regressor_OLS.summary()
summary_csv = summary.as_csv()
summary_rsq_text = summary_csv[106:116]
summary_rsq_value = summary_csv[129:134]
summary_adj_rsq_text = summary_csv[175:190]
summary_adj_rsq_value = summary_csv[198:203]
summary_csv =summary_csv[690: -224]
print()
print(summary_rsq_text + ' :' + " " + summary_rsq_value)
print(summary_adj_rsq_text + ' :' + " " + summary_adj_rsq_value)
text_file = open("Output.csv", "w")
text_file.write(summary_csv)
text_file.close()
df = dataset = pd.read_csv('Output.csv')
p = df.iloc[:, 4].values
index = df.iloc[:, 0].values
dframe = pd.DataFrame(index = index)
dframe['p'] = p
dframe['p'] = p
maxx = dframe['p'].max()
imax = 0
for i in range(len(df)):
if(dframe.iloc[i]['p'] == maxx):
imax = i
print('p: ', maxx, 'length: ', len(b)-1, '\nRemovable index: ', imax)
if(maxx > 0.05):
print('Removing Number: ', b[imax])
print('#################################################\n')
display_p.append(maxx)
display_length.append(len(b)-1)
display_index.append(imax)
display_r2.append(summary_rsq_value)
display_adj_r2.append(summary_adj_rsq_value)
List_of_column_no_removed.append(b[imax])
b.remove(b[imax])
d = pd.DataFrame()
d['length'] = display_length
d['index'] = display_index
d['number'] = List_of_column_no_removed
d['p value'] = display_p
d[summary_adj_rsq_text] = display_adj_r2
d[summary_rsq_text] = display_r2
# d["training time"] = training_time
# d["testing time"] = testing_time
# d["accuracy"] = accuracy_percent
save = d.to_csv(sep=',')
text_file = open("train_file.csv", "w")
text_file.write(save)
text_file.close()
df = pd.read_csv('train_file.csv')
s=[]
number = []
b = []
for i in range(len(X[1])):
number.append(i)
b.append(i)
num = list(df['number'])
for i in range(len(df)):
# if (m == df[summary_adj_rsq_text][i]):
# s.append(i)
if(num[i] in number):
b.remove(num[i])
#########################################################################################################################
#########################################################################################################################
#########################################################################################################################
########################################## 0.01 ###############################################################
#########################################################################################################################
#########################################################################################################################
#########################################################################################################################
#########################################################################################################################
########################################## p = 0.01 #########################################################
while( maxx > 0.01):
#ij = 0
#while(ij < 0.01):
X_opt = X[: , b]
regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit()
summary = regressor_OLS.summary()
summary_csv = summary.as_csv()
summary_rsq_text = summary_csv[106:116]
summary_rsq_value = summary_csv[129:134]
summary_adj_rsq_text = summary_csv[175:190]
summary_adj_rsq_value = summary_csv[198:203]
summary_csv =summary_csv[690: -224]
print()
print(summary_rsq_text + ' :' + " " + summary_rsq_value)
print(summary_adj_rsq_text + ' :' + " " + summary_adj_rsq_value)
text_file = open("Output.csv", "w")
text_file.write(summary_csv)
text_file.close()
df = dataset = pd.read_csv('Output.csv')
p = df.iloc[:, 4].values
index = df.iloc[:, 0].values
dframe = pd.DataFrame(index = index)
dframe['p'] = p
dframe['p'] = p
maxx = dframe['p'].max()
imax = 0
for i in range(len(df)):
if(dframe.iloc[i]['p'] == maxx):
imax = i
print('p: ', maxx, 'length: ', len(b)-1, '\nRemovable index: ', imax)
if(maxx > 0.01):
print('Removing Number: ', b[imax])
print('#################################################\n')
display_p.append(maxx)
display_length.append(len(b)-1)
display_index.append(imax)
display_r2.append(summary_rsq_value)
display_adj_r2.append(summary_adj_rsq_value)
List_of_column_no_removed.append(b[imax])
b.remove(b[imax])
d = pd.DataFrame()
d['length'] = display_length
d['index'] = display_index
d['number'] = List_of_column_no_removed
d['p value'] = display_p
d[summary_adj_rsq_text] = display_adj_r2
d[summary_rsq_text] = display_r2
# d["training time"] = training_time
# d["testing time"] = testing_time
# d["accuracy"] = accuracy_percent
save = d.to_csv(sep=',')
text_file = open("train_file.csv", "w")
text_file.write(save)
text_file.close()
df = pd.read_csv('train_file.csv')
s=[]
number = []
b = []
for i in range(len(X[1])):
number.append(i)
b.append(i)
num = list(df['number'])
for i in range(len(df)):
# if (m == df[summary_adj_rsq_text][i]):
# s.append(i)
if(num[i] in number):
b.remove(num[i])
#########################################################################################################################
#########################################################################################################################
#########################################################################################################################
#########################################################################################################################
#########################################################################################################################
#Building optimal model using Backward Elimination
X = X[:, b]
X = X[:, 1:]
#########################################################################################################################
#########################################################################################################################
#########################################################################################################################
#########################################################################################################################
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
#####################################################################################
# After selection of important features
#######################################################################################
# Fitting Random Forest Classification to the Training set
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier( n_estimators = 10, criterion = 'entropy', random_state = 0, n_jobs = -1)
temp = []
for i in range(10):
start = timeit.default_timer()
classifier.fit(X_train, y_train)
stop = timeit.default_timer()
After_time_001 = stop - start
temp.append(After_time_001)
After_time_001 = sum(temp)/10
temp = []
# Predicting the Test set results
for i in range(10):
start = timeit.default_timer()
y_pred = classifier.predict(X_test)
stop = timeit.default_timer()
After_time_y_pred_001 = stop - start
temp.append(After_time_y_pred_001)
After_time_y_pred_001 = sum(temp)/10
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
accuracy=0
for i in range(len(cm)):
for j in range(len(cm[i])):
if(i==j):
accuracy += cm[i][j]
accuracy = (accuracy/len(X_test)) * 100
After_accuracy_001 = accuracy
#Applying kfold cross validation
from sklearn.model_selection import cross_val_score
accuracies = cross_val_score(estimator = classifier, X = X_train, y = y_train, cv=10, n_jobs = -1)
#accuracy_by_10fold_cv = (sum(accuracies) / 10)
accuracy_by_10fold_cv = accuracies.mean() * 100
std = accuracies.std() * 100
accuracy = accuracy_by_10fold_cv
After_accuracy_001 = accuracy
print('\n\t'+'Train\t' + str(After_time_001) + '\t' + str(After_accuracy_001) + ' Accuracy')
print('\n\t'+'Test\t' + str(After_time_y_pred_001) + '\t' + str(After_accuracy_001) + ' Accuracy')
print('\n\t'+ 'b = ', len(b))
training_time.append(After_time_001)
testing_time.append(After_time_y_pred_001)
accuracy_percent.append(After_accuracy_001)
d = pd.DataFrame()
d["training time"] = training_time
d["testing time"] = testing_time
d["accuracy"] = accuracy_percent
save = d.to_csv(sep=',')
text_file = open("train_file.csv", "w")
text_file.write(save)
text_file.close()
###################################################################################################################