-
Notifications
You must be signed in to change notification settings - Fork 2
/
cpt_logit_quintiles.py
352 lines (279 loc) · 15.3 KB
/
cpt_logit_quintiles.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
import numpy as np
import pandas as pd
import os
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from support.acc_funs import auc_decomp
from sklearn.model_selection import GridSearchCV
# DESCRIPTION: THIS SCRIPT GENERATES AUC SCORES AND COEFFCIENT VALUES FOR THE AGGREGATE AND SUB MODELS.
# THE SUBMODELS ARE DEFINED BY THEIR RISK QUINTILE, NOT INDIVIDUAL CPT CODE
# SAVES TO OUTPUT:
# --- logit_agg_quin_cpt.csv
# --- logit_agg_quin_bin.csv
# --- logit_agg_quin_coef.csv
# --- logit_sub_quin_cpt.csv
# --- logit_sub_quin_bin.csv
# --- logit_sub_quin_coef_bin.csv
# --- logit_sub_quin_coef_cpt.csv
###############################
# ---- STEP 1: LOAD DATA ---- #
dir_base = os.getcwd()
dir_output = os.path.join(dir_base, '..', 'output')
dir_figures = os.path.join(dir_base, '..', 'figures')
fn_X = 'X_imputed.csv'
fn_Y = 'y_agg.csv'
dat_X = pd.read_csv(os.path.join(dir_output, fn_X))
dat_Y = pd.read_csv(os.path.join(dir_output, fn_Y))
# CREATE DUMMY VARIABLES FOR NON NUMERIC
dat_X = pd.get_dummies(dat_X)
# !! ENCODE CPT AS CATEGORICAL !! #
dat_X['cpt'] = 'c' + dat_X.cpt.astype(str)
# GET COLUMNS
cn_X = list(dat_X.columns[2:])
cn_Y = list(dat_Y.columns[25:37])
# DELETE NON AGG LABELS
dat_Y.drop(dat_Y.columns[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]],
axis=1, inplace=True)
# JOIN DAT_X AND DAT_Y
dat = pd.merge(dat_Y, dat_X, on='caseid')
####################################################
# ---- STEP 2: LEAVE-ONE-YEAR - AGGREGATE MODEL AUC FOR QUINTILE BINS AND CPT---- #
# LIST FOR BIN AUC AND CPT (WITHIN BIN) AUC FOR AGGREGATE MODEL
outcome_coef = []
outcome_bin = []
outcome_cpt = []
for ii, vv in enumerate(cn_Y):
print('##### ------- Outcome %s (%i of %i) -------- #####' % (vv, ii + 1, len(cn_Y)))
# GROUP BY CPT GET MEAN OF OUTCOME (RISK)
cpt_groups = pd.DataFrame(dat.groupby('cpt')[vv].apply(np.mean).reset_index().rename(columns={vv: 'outcome_mean'}))
# REMOVE CPTS THAT HAVE NO RISK (ALL ZERO) FOR OUTCOME VV
cpt_groups = cpt_groups[cpt_groups['outcome_mean'] > 0].reset_index(drop=False)
# GET QUINTILES
cpt_groups['bin'] = pd.qcut(cpt_groups['outcome_mean'], 5, labels=False)
# GET CPT LIST
sub_cpts = cpt_groups.cpt.unique()
# SUBSET DATA BY CPTS
sub_dat = dat[dat['cpt'].isin(sub_cpts)].reset_index(drop=False)
# GET TRAIN YEARS
tmp_ii = pd.concat([sub_dat.operyr, dat[vv] == -1], axis=1)
tmp_ii = tmp_ii.groupby('operyr')[vv].apply(np.sum).reset_index().rename(columns={vv: 'n'})
tmp_years = tmp_ii[tmp_ii.n == 0].operyr.values
tmp_years = tmp_years.astype(int)
tmp_train_years = tmp_years[tmp_years > (tmp_years.min())]
year_coef = []
year_bin = []
year_cpt = []
for yy in tmp_train_years:
print('Train Year %i' % (yy))
idx_train = sub_dat.operyr.isin(tmp_years) & (sub_dat.operyr < yy)
idx_test = sub_dat.operyr.isin(tmp_years) & (sub_dat.operyr == yy)
# GET TRAIN AND TEST DATA
Xtrain, Xtest = sub_dat.loc[idx_train, cn_X].reset_index(drop=True), \
sub_dat.loc[idx_test, cn_X].reset_index(drop=True)
ytrain, ytest = sub_dat.loc[idx_train, [vv]].reset_index(drop=True), \
sub_dat.loc[idx_test, [vv]].reset_index(drop=True)
# STORE CPT CODES
tmp_cpt = Xtest.cpt
# REMOVE CPT FROM DATA
del Xtrain['cpt']
del Xtest['cpt']
# grid search
param_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000]}
clf = GridSearchCV(LogisticRegression(penalty='l2', solver='liblinear', max_iter=200), param_grid, n_jobs=6, cv=2)
logisiticreg = clf.fit(Xtrain, ytrain.values.ravel())
logit_preds = logisiticreg.predict_proba(Xtest)[:, 1]
# GET COEFFCIENTS FROM MODEL AND STORE THEM
tmp_coef = []
coef = logit_fit.coef_
tmp_coef.append(pd.DataFrame({'coef': list(coef)}, index=[0]))
# GET BIN NAMES FOR LOOP
cpt_bin = cpt_groups.bin.sort_values().unique()
# STORE RESULTS FROM AGGREGATE MODEL
tmp_holder = pd.DataFrame({'y_preds': list(logit_preds), 'y_values': list(ytest.values), 'cpt': list(tmp_cpt)})
# LOOP THROUGH BINS
bin_holder = []
cpt_bin_holder = []
for bb in cpt_bin:
# GET CPTS FROM BIN
tmp_cpts = np.array(cpt_groups.cpt[cpt_groups['bin'] == bb])
# SUBSET MODEL RESULT BY CPTS
bin_tmp_holder = tmp_holder[tmp_holder['cpt'].isin(tmp_cpts)].reset_index(drop=False)
# GET UNIQUE CPTS FOR FOR LOOP
cpt_codes = bin_tmp_holder.cpt.sort_values().unique()
cpt_holder = []
for cc in cpt_codes:
# SUBSET BY CPT
cpt_tmp_holder =bin_tmp_holder[bin_tmp_holder['cpt']==cc]
# FILL RESULTS WITH NA IF TRAIN OR TEST OUTCOMES ARE ALL ONE VALUE
if all(cpt_tmp_holder.y_values.values == 0) or all(cpt_tmp_holder.y_values.values == 1) or len(cpt_tmp_holder.y_values) <= 1:
cpt_holder.append(pd.DataFrame({'auc': 'NA',
'cpt': cc,
'num_obs': cpt_tmp_holder.y_values.size}, index=[0]))
else:
cpt_holder.append(pd.DataFrame({'auc': metrics.roc_auc_score(list(cpt_tmp_holder.y_values.values),
list(cpt_tmp_holder.y_preds.values)),
'cpt': cc,
'num_obs': cpt_tmp_holder.y_values.size}, index=[0]))
cpt_bin_holder.append(pd.concat(cpt_holder).assign(bin=bb))
# FILL RESULTS WITH NA IF TRAIN OR TEST OUTCOMES ARE ALL ONE VALUE
if all(bin_tmp_holder.y_values.values == 0):
bin_holder.append(pd.DataFrame({'auc': 'NA',
'bin': bb,
'num_obs': bin_tmp_holder.y_values.size}, index=[0]))
else:
bin_holder.append(pd.DataFrame({'auc': metrics.roc_auc_score(list(bin_tmp_holder.y_values.values),
list(bin_tmp_holder.y_preds.values)),
'bin': bb,
'num_obs': bin_tmp_holder.y_values.size}, index=[0]))
year_coef.append(pd.concat(tmp_coef).assign(test_year=yy))
year_cpt.append(pd.concat(cpt_bin_holder).assign(test_year=yy))
year_bin.append(pd.concat(bin_holder).assign(test_year=yy))
outcome_coef.append(pd.concat(year_coef).assign(outcome=vv))
outcome_cpt.append(pd.concat(year_cpt).assign(outcome=vv))
outcome_bin.append(pd.concat(year_bin).assign(outcome=vv))
# SAVE CPT AUC FOR AGGREGATE MODEL
agg_auc_cpt = pd.concat(outcome_cpt).reset_index(drop=True)
agg_auc_cpt.to_csv(os.path.join(dir_output, 'logit_agg_quin_cpt.csv'), index=False)
# SAVE QUINTILE AUC FOR AGGREGATE MODEL
agg_auc_bin = pd.concat(outcome_bin).reset_index(drop=True)
agg_auc_bin.to_csv(os.path.join(dir_output, 'logit_agg_quin_bin.csv'), index=False)
# SAVE coefficients for agg model
agg_coef = pd.concat(outcome_coef).reset_index(drop=True)
agg_coef.to_csv(os.path.join(dir_output, 'logit_agg_quin_coef.csv'), index=False)
####################################################
# ---- STEP 3: LEAVE-ONE-YEAR - SUB MODEL AUC FOR QUINTILE BINS AND CPT---- #
outcome_bin_coef = []
outcome_cpt_coef = []
outcome_bin = []
outcome_cpt = []
for ii, vv in enumerate(cn_Y):
print('##### ------- Outcome %s (%i of %i) -------- #####' % (vv, ii + 1, len(cn_Y)))
# GROUP BY CPT GET MEAN OF OUTCOME (RISK)
cpt_groups = pd.DataFrame(dat.groupby('cpt')[vv].apply(np.mean).reset_index().rename(columns={vv: 'outcome_mean'}))
# REMOVE CPTS THAT HAVE NO RISK (ALL ZERO) FOR OUTCOME VV
cpt_groups = cpt_groups[cpt_groups['outcome_mean'] > 0].reset_index(drop=False)
# GET BINS
cpt_groups['bin'] = pd.qcut(cpt_groups['outcome_mean'], 5, labels=False)
# GET LIST OF CPTS
sub_cpts = cpt_groups.cpt.unique()
# SUBSET DATA BY CPTS
sub_dat = dat[dat['cpt'].isin(sub_cpts)].reset_index(drop=False)
# GET TRAIN YEARS
tmp_ii = pd.concat([dat.operyr, dat[vv] == -1], axis=1)
tmp_ii = tmp_ii.groupby('operyr')[vv].apply(np.sum).reset_index().rename(columns={vv: 'n'})
tmp_years = tmp_ii[tmp_ii.n == 0].operyr.values
tmp_years = tmp_years.astype(int)
tmp_train_years = tmp_years[tmp_years > (tmp_years.min())]
year_cpt_coef = []
year_bin_coef = []
year_bin = []
year_cpt = []
for yy in tmp_train_years:
print('Train Year %i' % (yy))
idx_train = sub_dat.operyr.isin(tmp_years) & (sub_dat.operyr < yy)
idx_test = sub_dat.operyr.isin(tmp_years) & (sub_dat.operyr == yy)
# TRAIN AND TEST DATA
Xtrain, Xtest = sub_dat.loc[idx_train, cn_X].reset_index(drop=True), \
sub_dat.loc[idx_test, cn_X].reset_index(drop=True)
ytrain, ytest = sub_dat.loc[idx_train, [vv]].reset_index(drop=True), \
sub_dat.loc[idx_test, [vv]].reset_index(drop=True)
# GET UNIQUE BINS FOR LOOP
cpt_bin = cpt_groups.bin.sort_values().unique()
bin_holder = []
bin_coef_holder =[]
cpt_bin_holder = []
cpt_bin_coef_holder = []
for bb in cpt_bin:
# SUBSET BY BIN
tmp_bins = cpt_groups[cpt_groups['bin']==bb]
# SUBSET XTRAIN AND XTEST BY CPTS
bin_xtrain = Xtrain[Xtrain['cpt'].isin(tmp_bins.cpt)]
bin_xtest = Xtest[Xtest['cpt'].isin(tmp_bins.cpt)]
# SUBSET YTRAIN AND YTEST BY THE CORRESPONDING INDICES IN SUBSETTED XDATA
bin_ytrain = ytrain[ytrain.index.isin(bin_xtrain.index)]
bin_ytest = ytest[ytest.index.isin(bin_xtest.index)]
# GET CPT CODES
cpt_codes = tmp_bins.cpt.sort_values().unique()
cpt_holder = []
cpt_coef_holder = []
for cc in cpt_codes:
# GET CPTS CODES FROM CURRENT BIN
tmp_cpts = tmp_bins[tmp_bins['cpt'] == cc]
# SUBSET XTRAIN AND XTEST BY CPTS
cpt_xtrain = bin_xtrain[bin_xtrain['cpt'].isin(tmp_cpts.cpt)]
cpt_xtest = bin_xtest[bin_xtest['cpt'].isin(tmp_cpts.cpt)]
# SUBSET YTRAIN AND YTEST BY THE CORRESPONDING INDICES IN SUBSETTED XDATA
cpt_ytrain = bin_ytrain[bin_ytrain.index.isin(cpt_xtrain.index)]
cpt_ytest = bin_ytest[bin_ytest.index.isin(cpt_xtest.index)]
# REMOVE CPT
del cpt_xtrain['cpt']
del cpt_xtest['cpt']
# FILL RESULTS WITH NA IF TRAIN OR TEST OUTCOMES ARE ALL ONE VALUE
if np.unique(cpt_ytrain.values).size <= 1 or np.unique(cpt_ytest.values).size <= 1:
cpt_holder.append(pd.DataFrame({'auc': 'NA',
'cpt': cc,
'num_obs': cpt_ytest.values.size}, index=[0]))
cpt_coef_holder.append(pd.DataFrame({'coef':'NA',
'cpt': cc,
'num_obs': cpt_ytest.values.size}, index=[0]))
else:
# grid search
param_grid = {'C': [0.001, 0.01, 0.1, 1, 10, 100, 1000]}
clf = GridSearchCV(LogisticRegression(penalty='l2', solver='liblinear', max_iter=200), param_grid,
n_jobs=6,cv=2)
logisiticreg = clf.fit(sub_xtrain, sub_ytrain.values.ravel())
logit_preds = logisiticreg.predict_proba(sub_xtest)[:, 1]
# GET COEFFICIENTS FROM MODEL AND STORE
coef_cpt = logit_fit.coef_
cpt_holder.append(
pd.DataFrame({'auc': metrics.roc_auc_score(cpt_ytest.values, logit_preds),
'cpt': cc,
'num_obs': cpt_ytest.values.size}, index=[0]))
cpt_coef_holder.append(pd.DataFrame({'coef':list(coef_cpt),
'cpt': cc,
'num_obs':cpt_ytest.values.size}, index=[0]))
cpt_bin_holder.append(pd.concat(cpt_holder).assign(bin=bb))
cpt_bin_coef_holder.append(pd.concat(cpt_coef_holder).assign(bin=bb))
# IF OUTCOME HAS ONE LEVEL, STORE NAs
if all(np.unique(bin_ytrain.values) == 0) or all(np.unique(bin_ytest.values) == 0):
bin_holder.append(pd.DataFrame({'auc': 'NA',
'bin': bb,
'num_obs': bin_ytest.values.size}, index=[0]))
bin_coef_holder.append(pd.DataFrame({'coef': 'NA',
'bin': bb,
'num_obs': bin_ytest.values.size}, index=[0]))
else:
# REMOVE CPT COLUMN
del bin_xtrain['cpt']
del bin_xtest['cpt']
# TRAIN MODEL
logisticreg = LogisticRegression(solver='liblinear', max_iter=200)
logit_fit = logisticreg.fit(bin_xtrain, bin_ytrain.values.ravel())
# TEST MODEL
logit_preds = logit_fit.predict_proba(bin_xtest)[:, 1]
# GET COEFFICIENTS AND STORE THE
coef_bin = logit_fit.coef_
bin_holder.append(pd.DataFrame({'auc': metrics.roc_auc_score(bin_ytest.values, logit_preds),
'bin': bb,
'num_obs': bin_ytest.values.size}, index=[0]))
bin_coef_holder.append(pd.DataFrame({'coef': list(coef_bin),
'bin': bb,
'num_obs': bin_ytest.values.size}, index=[0]))
year_cpt_coef.append(pd.concat(cpt_bin_coef_holder).assign(test_year=yy))
year_bin_coef.append(pd.concat(bin_coef_holder).assign(test_year=yy))
year_cpt.append(pd.concat(cpt_bin_holder).assign(test_year=yy))
year_bin.append(pd.concat(bin_holder).assign(test_year=yy))
outcome_cpt_coef.append(pd.concat(year_cpt_coef).assign(outcome=vv))
outcome_bin_coef.append(pd.concat(year_bin_coef).assign(outcome=vv))
outcome_cpt.append(pd.concat(year_cpt).assign(outcome=vv))
outcome_bin.append(pd.concat(year_bin).assign(outcome=vv))
# SAVE AUC FOR CPTS ON SUB MODELS
agg_auc_cpt = pd.concat(outcome_cpt).reset_index(drop=True)
agg_auc_cpt.to_csv(os.path.join(dir_output, 'logit_sub_quin_cpt.csv'), index=False)
agg_coef_cpt = pd.concat(outcome_cpt_coef).reset_index(drop=True)
agg_coef_cpt.to_csv(os.path.join(dir_output, 'logit_sub_quin_coef_cpt.csv'), index=False)
# SAVE AUC FOR QUNITILE BINS FOR SUB MODELS
agg_auc_bin = pd.concat(outcome_bin).reset_index(drop=True)
agg_auc_bin.to_csv(os.path.join(dir_output, 'logit_sub_quin_bin.csv'), index=False)
agg_coef_bin = pd.concat(outcome_bin_coef).reset_index(drop=True)
agg_coef_bin.to_csv(os.path.join(dir_output, 'logit_sub_quin_coef_bin.csv'), index=False)