-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChurn_Prediction.py
More file actions
204 lines (130 loc) · 4.76 KB
/
Churn_Prediction.py
File metadata and controls
204 lines (130 loc) · 4.76 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
# Importing the libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn import svm
# Importing the dataset, renaming the column names and dataset backup
ds = pd.read_csv('Churn_Modelling.csv')
ds.columns = ds.columns.str.replace('\s+', '_')
df = ds.copy()
# Remove unnecessary columns either by selecting or deleting
col_del = ['RowNumber', 'CustomerId', 'Surname']
df = df.drop(col_del, axis = 1).copy()
#col_sel = ['RowNumber', 'CustomerId', 'Surname']
#df = df[col_sel].copy()
# Encode categorical variables
df = pd.get_dummies(df, drop_first = True)
#Moving the dependant variable to the last
cols = df.columns.tolist()
n = int(cols.index('Exited'))
cols = cols[:n] + cols[n+1:] + [cols[n]]
df = df[cols]
# IVs and DVs for model execution
X = df.iloc[:, :-1]
y = df.iloc[:, df.shape[1]-1]
# Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
# Construct Pipeline for each Model
pipe_lr = Pipeline([('scl', StandardScaler()),
('clf', LogisticRegression(random_state=0))])
pipe_lr_pca = Pipeline([('scl', StandardScaler()),
('pca', PCA(n_components=2)),
('clf', LogisticRegression(random_state=0))])
pipe_rf = Pipeline([('scl', StandardScaler()),
('clf', RandomForestClassifier(random_state=0))])
pipe_rf_pca = Pipeline([('scl', StandardScaler()),
('pca', PCA(n_components=2)),
('clf', RandomForestClassifier(random_state=0))])
pipe_svm = Pipeline([('scl', StandardScaler()),
('clf', svm.SVC(random_state=0))])
pipe_svm_pca = Pipeline([('scl', StandardScaler()),
('pca', PCA(n_components=2)),
('clf', svm.SVC(random_state=0))])
# Set grid search params for all models
param_range = [1, 2, 3, 4, 5]
param_range_fl = [1.0, 0.5, 0.1]
grid_params_lr = [{'clf__penalty': ['l1', 'l2'],
'clf__C': param_range_fl,
'clf__solver': ['liblinear']}]
grid_params_rf = [{'clf__criterion': ['gini', 'entropy'],
'clf__min_samples_leaf': param_range,
'clf__max_depth': param_range,
'clf__min_samples_split': param_range[1:]}]
grid_params_svm = [{'clf__kernel': ['linear', 'rbf'],
'clf__C': param_range}]
# Construct grid searches
jobs = -1
gs_lr = GridSearchCV(estimator=pipe_lr,
param_grid=grid_params_lr,
scoring='accuracy',
cv=4)
gs_lr_pca = GridSearchCV(estimator=pipe_lr_pca,
param_grid=grid_params_lr,
scoring='accuracy',
cv=4)
gs_rf = GridSearchCV(estimator=pipe_rf,
param_grid=grid_params_rf,
scoring='accuracy',
cv=4,
n_jobs=jobs)
gs_rf_pca = GridSearchCV(estimator=pipe_rf_pca,
param_grid=grid_params_rf,
scoring='accuracy',
cv=4,
n_jobs=jobs)
gs_svm = GridSearchCV(estimator=pipe_svm,
param_grid=grid_params_svm,
scoring='accuracy',
cv=4,
n_jobs=jobs)
gs_svm_pca = GridSearchCV(estimator=pipe_svm_pca,
param_grid=grid_params_svm,
scoring='accuracy',
cv=4,
n_jobs=jobs)
# List of pipelines for ease of iteration
grids = [gs_lr, gs_lr_pca, gs_rf, gs_rf_pca, gs_svm, gs_svm_pca]
# Dictionary of pipelines and classifier types for ease of reference
grid_dict = {0: 'Logistic Regression', 1: 'Logistic Regression w/PCA',
2: 'Random Forest', 3: 'Random Forest w/PCA',
4: 'Support Vector Machine', 5: 'Support Vector Machine w/PCA'}
# Fit the grid search objects
print('Performing model optimizations...')
best_acc = 0.0
best_clf = 0
best_gs = ''
for idx, gs in enumerate(grids):
print('\nEstimator: %s' % grid_dict[idx])
# Fit grid search
gs.fit(X_train, y_train)
# Best params
print('Best params: %s' % gs.best_params_)
# Best training data accuracy
print('Best training accuracy: %.3f' % gs.best_score_)
# Predict on test data with best params
y_pred = gs.predict(X_test)
# Test data accuracy of model with best params
print('Test set accuracy score for best params: %.3f ' % accuracy_score(y_test, y_pred))
# Track best (highest test accuracy) model
if accuracy_score(y_test, y_pred) > best_acc:
best_acc = accuracy_score(y_test, y_pred)
best_gs = gs
best_clf = idx
y_pred_best = y_pred
print('\nClassifier with best test set accuracy: %s' % grid_dict[best_clf])
# Making the Confusion Matrix
cm = confusion_matrix(y_test, y_pred_best)
# Export the dataframe to csv
#X_train.to_csv('X_train.csv')
#X_test.to_csv('X_test.csv')
#y_train.to_csv('y_train.csv')
#y_test.to_csv('y_test.csv')
#apd = pd.DataFrame(y_pred_best)
#apd.to_csv('y_pred.csv')