-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModel_Building.py
More file actions
292 lines (217 loc) · 10.4 KB
/
Copy pathModel_Building.py
File metadata and controls
292 lines (217 loc) · 10.4 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
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
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 27 13:20:30 2021
@author: he
"""
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import StratifiedKFold
from sklearn import metrics
import matplotlib.pyplot as plt
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from xgboost import XGBClassifier
train = pd.read_csv('Data/train_new.csv')
test = pd.read_csv('Data/test_new.csv')
test_og = pd.read_csv('Data/test.csv')
# =============================================================================
# #Removing the Loan_ID since it has no effect.
# =============================================================================
train = train.drop('Loan_ID', axis=1)
test = test.drop('Loan_ID', axis=1)
X = train.drop('Loan_Status', 1)
y = train.Loan_Status
X = pd.get_dummies(X)
train = pd.get_dummies(train)
test = pd.get_dummies(test)
x_train, x_cv, y_train, y_cv = train_test_split(X,y, test_size=0.3)
# =============================================================================
# LOGISTIC REGRESSION.
# =============================================================================
model = LogisticRegression()
model.fit(x_train, y_train)
#preddicting the Loan_status.
pred_cv = model.predict(x_cv)
#now let's calculate the accuracy of the model.
log_reg = accuracy_score(y_cv, pred_cv)
# let's make the predection for the test dataset
pred_test = model.predict(test)
print('The Accuracy of Logistic Regression Model:',log_reg*100)
# =============================================================================
# The Accuracy of Logistic Regression is 79.45945945945945
# =============================================================================
submission = pd.read_csv('Data/submission.csv')
submission.Loan_Status = pred_test
submission.Loan_Status.replace(1, 'Y', inplace=True)
submission.Loan_Status.replace(0, 'N', inplace=True)
pd.DataFrame(submission, columns=['Loan_ID', 'Loan_Status']).to_csv('submission.csv', index=False)
# =============================================================================
# Cross Validation metrics Using Stratified-K-Folds
# =============================================================================
'''
Now Let's make a cross validation logistic model with stratified 5 folds
And make prediction on the test dataset.
'''
print('\n Logistic Regression using stratified k-folds')
i = 1
KF = StratifiedKFold(n_splits = 5, random_state=1,shuffle=True)
for train_index, test_index in KF.split(X,y):
print('\n{} of Kfold {} '.format(i,KF.n_splits))
xtrain = X.iloc[train_index]
ytrain = y.iloc[train_index]
xvalidation = X.iloc[test_index]
yvalidation = y.iloc[test_index]
model = LogisticRegression(random_state=1)
model.fit(xtrain,ytrain)
pred_test = model.predict(xvalidation)
score = accuracy_score(yvalidation, pred_test)
print('accuracy_score', score)
i+=1
pred_test = model.predict(test)
pred = model.predict_proba(xvalidation)[:,1]
False_Positive_Rate, True_Positive_Rate, _ = metrics.roc_curve(yvalidation, pred, pos_label='Y')
AUC = metrics.roc_auc_score(yvalidation, pred)
plt.figure(figsize=(12,8))
plt.plot(False_Positive_Rate, True_Positive_Rate, label='validation, AUC='+str(AUC))
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend(loc=4)#Location of the legend on the position on the screen represented by numbers from 1 to 4.
plt.show()
# =============================================================================
# Feature Engineering
# =============================================================================
train.columns
train['Total_Amount'] = train.ApplicantIncome + train.CoapplicantIncome
test['Total_Amount'] = test.ApplicantIncome + test.CoapplicantIncome
train['Total_Amount_log'] = np.log(train.Total_Amount)
test['Total_Amount_log'] = np.log(test.Total_Amount)
sns.distplot(train.Total_Amount_log)
train['EMI'] = train.LoanAmount / train.Loan_Amount_Term
test['EMI'] = test.LoanAmount / train.Loan_Amount_Term
sns.distplot(train.EMI)
train['Balance_Income'] = train['Total_Amount'] -(train['EMI']*1000)
test['Balance_Income'] = test['Total_Amount'] -(test['EMI']*1000)
sns.displot(train.Balance_Income)
train = train.drop(['ApplicantIncome', 'CoapplicantIncome', 'Loan_Amount_Term', 'LoanAmount'], axis=1)
test = test.drop(['ApplicantIncome', 'CoapplicantIncome', 'Loan_Amount_Term', 'LoanAmount'], axis=1)
# =============================================================================
# Decision Tree.
# =============================================================================
i=1
KF = StratifiedKFold(n_splits=5, random_state=1, shuffle=True)
for train_index, test_index in KF.split(X,y):
print('\n{} of Kfolds {} '.format(i, KF.n_splits))
xtrain = X.iloc[train_index]
ytrain = y.iloc[train_index]
xvalidation = X.iloc[test_index]
yvalidation = y.iloc[test_index]
model = tree.DecisionTreeClassifier(random_state=1)
model.fit(xtrain,ytrain)
pred_test = model.predict(xvalidation)
score = accuracy_score(yvalidation, pred_test)
print('Accuracy Score of Decision Tree is ',score)
i+=1
pred_test = model.predict(test)
submission['Loan_Status'] = pred_test
submission['Loan_ID'] = test_og['Loan_ID']
submission['Loan_Status'].replace(0, 'N', inplace=True)
submission['Loan_Status'].replace(1, 'Y', inplace=True)
pd.DataFrame(submission, columns=['Loan_ID', 'Loan_Status']).to_csv('Decision Tree.csv', index=False)
# =============================================================================
# Random Forest
# =============================================================================
print('\n Random Forest')
i=1
KF = StratifiedKFold(n_splits=5, random_state=1, shuffle=True)
for train_index, test_index in KF.split(X,y):
print('\n{} of Kfolds {} '.format(i, KF.n_splits))
xtrain = X.iloc[train_index]
ytrain = y.iloc[train_index]
xvalidation = X.iloc[test_index]
yvalidation = y.iloc[test_index]
model = RandomForestClassifier(random_state=1, max_depth=10)
model.fit(xtrain,ytrain)
pred_test = model.predict(xvalidation)
score = accuracy_score(yvalidation, pred_test)
print('Accuracy Score of Random Forest is ',score)
i+=1
pred_test = model.predict(test)
# =============================================================================
# GridSearch
# =============================================================================
param_grid = {'max_depth': list(range(1, 20, 2)),
'n_estimators': list(range(1,200, 20))
}
grid_search = GridSearchCV(RandomForestClassifier(random_state=1), param_grid)
grid_search.fit(X,y)
GridSearchCV(cv=None, error_score='raise',
estimator = RandomForestClassifier(bootstrap = True, class_weight = None,
criterion='gini', max_depth= None,
max_features='auto', max_leaf_nodes= None,
min_impurity_decrease = 0.0,
min_impurity_split=None, min_samples_leaf = 1,
min_samples_split = 2, min_weight_fraction_leaf = 0.0,
n_estimators= 10, n_jobs=1, oob_score=False,
random_state =1, verbose =0, warm_start=False),
n_jobs=1,
param_grid = {'max_depth': list(range(1, 20, 2)),
'n_estimators': list(range(1,200, 20))
}, pre_dispatch = '2*n_jobs', refit = True,
scoring = None, verbose=0
)
#Estimating the optimized value
grid_search.best_estimator_
RandomForestClassifier(bootstrap = True, class_weight = None,
criterion='gini', max_depth= None,
max_features='auto', max_leaf_nodes= None,
min_impurity_decrease = 0.0,
min_impurity_split=None, min_samples_leaf = 1,
min_samples_split = 2, min_weight_fraction_leaf = 0.0,
n_estimators= 10, n_jobs=1, oob_score=False,
random_state =1, verbose =0, warm_start=False)
i=1
KF = StratifiedKFold(n_splits=5, random_state=1, shuffle=True)
for train_index, test_index in KF.split(X,y):
print('\n{} of Kfolds {} '.format(i, KF.n_splits))
xtrain = X.iloc[train_index]
ytrain = y.iloc[train_index]
xvalidation = X.iloc[test_index]
yvalidation = y.iloc[test_index]
model = RandomForestClassifier(random_state=1, max_depth=3, n_estimators=41)
model.fit(xtrain,ytrain)
pred_test = model.predict(xvalidation)
score = accuracy_score(yvalidation, pred_test)
print('Accuracy Score of Random Forest is ',score)
i+=1
pred_test = model.predict(test)
submission['Loan_Status'] = pred_test
submission['Loan_ID'] = test_og['Loan_ID']
submission['Loan_Status'].replace(0, 'N', inplace=True)
submission['Loan_Status'].replace(1, 'Y', inplace=True)
pd.DataFrame(submission, columns=['Loan_ID', 'Loan_Status']).to_csv('Random Forest.csv', index=False)
importances = pd.Series(model.feature_importances_, index= X.columns)
importances.plot(kind='barh', figsize=(16,8))
# =============================================================================
# XGBOOST
# =============================================================================
i=1
KF = StratifiedKFold(n_splits=5, random_state=1, shuffle=True)
for train_index, test_index in KF.split(X,y):
print('\n{} of Kfolds {} '.format(i, KF.n_splits))
xtrain = X.iloc[train_index]
ytrain = y.iloc[train_index]
xvalidation = X.iloc[test_index]
yvalidation = y.iloc[test_index]
model = XGBClassifier(max_depth=4, n_estimators=50)
model.fit(xtrain,ytrain)
pred_test = model.predict(xvalidation)
score = accuracy_score(yvalidation, pred_test)
print('Accuracy Score of Random Forest is ',score)
i+=1
pred_test = model.predict(test)
pred3 = model.predict_proba(test)[:,1]