forked from epierson9/pain-disparities
-
Notifications
You must be signed in to change notification settings - Fork 0
/
analysis.py
3558 lines (3109 loc) · 193 KB
/
analysis.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from constants_and_util import *
from scipy.stats import norm, pearsonr, spearmanr
import pandas as pd
import copy
import numpy as np
import random
import matplotlib.pyplot as plt
import statsmodels.api as sm
from sklearn.linear_model import Lasso
from sklearn.ensemble import RandomForestRegressor
from scipy.stats import ttest_ind, rankdata
import non_image_data_processing
import patsy
import os
import math
import sklearn
import json
import seaborn as sns
from scipy.stats import scoreatpercentile
import statsmodels
from sklearn.kernel_ridge import KernelRidge
import scipy
from scipy.stats import scoreatpercentile, linregress, ttest_rel
from statsmodels.iolib.summary2 import summary_col
"""
Code to perform analyses on the fitted models. We note two potentially confusing naming conventions in the analysis code.
First, much of the code was written during preliminary analyses looking just at SES; later, we broadened the analysis to look at pain gaps by sex, race, etc.
Hence, many of the variable names/comments contain "ses", but in general, these refer to all three binary variables we consider in the final paper (capturing education and race, not just income).
Second, while the paper refers to "training", "development", and "validation" sets, those correspond in the code to the "train", "val", and "test" sets, respectively.
"""
def make_simple_histogram_of_pain(y, binary_vector_to_use, positive_class_label, negative_class_label, plot_filename):
"""
Make a simple histogram of pain versus binary class (eg, pain for black vs non-black patients).
Checked.
"""
sns.set_style()
bins = np.arange(0, 101, 10)
plt.figure(figsize=[4, 4])
hist_weights = np.ones((binary_vector_to_use == False).sum())/float((binary_vector_to_use == False).sum()) # https://stackoverflow.com/a/16399202/9477154
plt.hist(y[binary_vector_to_use == False], weights=hist_weights, alpha=1, bins=bins, label=negative_class_label, orientation='horizontal')
hist_weights = np.ones((binary_vector_to_use == True).sum())/float((binary_vector_to_use == True).sum())
plt.hist(y[binary_vector_to_use == True], weights=hist_weights, alpha=.7, bins=bins, label=positive_class_label, orientation='horizontal')
plt.ylim([0, 100])
plt.yticks([0, 20, 40, 60, 80, 100], fontsize=12)
plt.xlabel("")
plt.legend(loc=4, fontsize=12)
plt.xticks([])
plt.savefig(plot_filename)
def compare_to_mri_features(datasets, y, yhat, all_ses_vars, ids, df_for_filtering_out_special_values, also_include_xray_features, use_random_forest, mri_features):
"""
Show that yhat still outperforms a predictor which uses MRI features.
df_for_filtering_out_special_values: this is a dataframe for MRI features only which only has rows if there are no 0.5/-0.5 values.
Just a sanity check (those values are rare) because I'm not sure whether binarizing really makes sense for those values.
"""
datasets = copy.deepcopy(datasets)
idxs_with_mris = {}
dfs_to_use_in_regression = {}
for dataset in ['train', 'val', 'test']:
idxs_with_mris[dataset] = np.isnan(datasets[dataset].non_image_data[mri_features].values).sum(axis=1) == 0
if df_for_filtering_out_special_values is not None:
dfs_to_use_in_regression[dataset] = pd.merge(datasets[dataset].non_image_data,
df_for_filtering_out_special_values,
how='left',
on=['id', 'side', 'visit'],
validate='one_to_one')
no_special_values = ~pd.isnull(dfs_to_use_in_regression[dataset]['no_special_values']).values
idxs_with_mris[dataset] = (idxs_with_mris[dataset]) & (no_special_values)
else:
dfs_to_use_in_regression[dataset] = datasets[dataset].non_image_data.copy()
if also_include_xray_features:
mri_features_to_use = ['C(%s)' % a for a in mri_features + CLINICAL_CONTROL_COLUMNS]
else:
mri_features_to_use = ['C(%s)' % a for a in mri_features]
print("\n\n\n\n********Predicting pain from MRI features; including Xray clinical features=%s; using random forest %s; filtering out special values %s" %
(also_include_xray_features, use_random_forest, df_for_filtering_out_special_values is not None))
yhat_from_mri = compare_to_clinical_performance(
train_df=dfs_to_use_in_regression['train'].loc[idxs_with_mris['train']],
val_df=dfs_to_use_in_regression['val'].loc[idxs_with_mris['val']],
test_df=dfs_to_use_in_regression['test'].loc[idxs_with_mris['test']],
y_col='koos_pain_subscore',
features_to_use=mri_features_to_use,
binary_prediction=False,
use_nonlinear_model=use_random_forest,
do_ols_sanity_check=True)
print("Compare to yhat performance")
yhat_performance = assess_performance(y=y[idxs_with_mris['test']],
yhat=yhat[idxs_with_mris['test']],
binary_prediction=False)
for k in yhat_performance:
print('%s: %2.3f' % (k, yhat_performance[k]))
mri_ses_vars = {}
for k in all_ses_vars:
mri_ses_vars[k] = all_ses_vars[k][idxs_with_mris['test']]
print(quantify_pain_gap_reduction_vs_rival(yhat=yhat[idxs_with_mris['test']],
y=y[idxs_with_mris['test']],
rival_severity_measure=yhat_from_mri,
all_ses_vars=mri_ses_vars,
ids=ids[idxs_with_mris['test']]))
def sig_star(p):
assert p >= 0 and p <= 1
if p < .001:
return '***'
elif p < .01:
return '**'
elif p < .05:
return '*'
return ''
def get_pvalue_on_binary_vector_mean_diff(yhat_vector, klg_vector, ids):
"""
Assess whether yhat_vector and KLG_vector are assigning different fractions of people to surgery.
Basically does a paired t-test on the binary vector accounting for clustering.
Used for surgery analysis.
"""
assert len(yhat_vector) == len(klg_vector) == len(ids)
check_is_array(yhat_vector)
check_is_array(klg_vector)
diff_df = pd.DataFrame({'diff':1.*yhat_vector - 1.*klg_vector, 'id':ids})
clustered_diff_model = sm.OLS.from_formula('diff ~ 1', data=diff_df).fit(cov_type='cluster', cov_kwds={'groups':diff_df['id']})
assert np.allclose(clustered_diff_model.params['Intercept'], yhat_vector.mean() - klg_vector.mean())
return clustered_diff_model.pvalues['Intercept']
def get_ci_on_binary_vector(vector, ids):
"""
Compute standard error on a binary vector's mean, accounting for clustering.
Used for surgery analysis.
"""
assert len(vector) == len(ids)
check_is_array(vector)
check_is_array(ids)
df = pd.DataFrame({'val':1.*vector, 'id':ids})
cluster_model = sm.OLS.from_formula('val ~ 1', data=df).fit(cov_type='cluster', cov_kwds={'groups':df['id']})
assert np.allclose(cluster_model.params['Intercept'], vector.mean())
return '(%2.5f, %2.5f)' % (cluster_model.conf_int().loc['Intercept', 0], cluster_model.conf_int().loc['Intercept', 1])
def do_surgery_analysis_ziad_style(yhat, y, klg, all_ses_vars, baseline_idxs, have_actually_had_surgery, df_to_use, ids):
"""
Hopefully the final surgery analysis. Does a couple things:
1. Uses a criterion for allocating surgery based on the prior literature: KLG >= 3 and high pain, as defined using pain threshold from prior literature.
- to compare to yhat we do it two ways: discretize yhat, use discretized_yhat >= 3
- and, to make sure we allocate the same number of surgeries, take all high pain people and just count down by yhat until we have the same number that KLG allocates.
2. Then examines:
- What fraction of people are eligible for surgery both overall and in our racial/SES groups?
- What fraction of people are in a lot of pain but aren't eligible for surgery both overall and in our racial/SES groups?
- Is painkiller use correlated with yhat among those who don't receive surgery?
As a robustness check, all these analyses are repeated on both baseline + overall dataset, both excluding and including those who have already had surgery.
"""
check_is_array(yhat)
check_is_array(y)
check_is_array(klg)
check_is_array(ids)
check_is_array(baseline_idxs)
check_is_array(have_actually_had_surgery)
pd.set_option('precision', 6)
pd.set_option('display.width', 1000)
df_to_use = df_to_use.copy()
in_high_pain = binarize_koos(y) == True
discretized_yhat = discretize_yhat_like_kl_grade(yhat_arr=yhat, kl_grade_arr=klg, y_col='koos_pain_subscore')
klg_cutoff = 3
fit_surgery_criteria_under_klg = (in_high_pain == True) & (klg >= klg_cutoff)
fit_surgery_criteria_under_discretized_yhat = (in_high_pain == True) & (discretized_yhat >= klg_cutoff)
for just_use_baseline in [True, False]:
for exclude_those_who_have_surgery in [True, False]:
idxs_to_use = np.ones(baseline_idxs.shape) == 1
if just_use_baseline:
idxs_to_use = idxs_to_use & (baseline_idxs == 1)
if exclude_those_who_have_surgery:
idxs_to_use = idxs_to_use & (have_actually_had_surgery == 0)
print("\n\n\n\n****Just use baseline: %s; exclude those who have had surgery: %s; analyzing %i knees" %
(just_use_baseline, exclude_those_who_have_surgery, idxs_to_use.sum()))
n_surgeries_under_klg = int(fit_surgery_criteria_under_klg[idxs_to_use].sum())
# Alternate yhat criterion: assign exactly same number of people surgery under yhat as under KLG.
# Do this by taking people with the lowest yhat values subject to being in high pain.
# Compute this independently for each group specified by idxs_to_use.
lowest_yhat_idxs = np.argsort(yhat)
yhat_match_n_surgeries = np.array([False for a in range(len(fit_surgery_criteria_under_discretized_yhat))])
for idx in lowest_yhat_idxs:
if yhat_match_n_surgeries.sum() < n_surgeries_under_klg:
if (in_high_pain[idx] == 1) & (idxs_to_use[idx] == 1):
yhat_match_n_surgeries[idx] = True
assert yhat[yhat_match_n_surgeries == True].mean() < yhat[yhat_match_n_surgeries == False].mean()
assert np.allclose(yhat_match_n_surgeries[idxs_to_use].mean(), fit_surgery_criteria_under_klg[idxs_to_use].mean())
fracs_eligible_for_surgery = []
fracs_eligible_for_surgery.append({'group':'Overall',
'klg':fit_surgery_criteria_under_klg[idxs_to_use].mean(),
'klg_ci':get_ci_on_binary_vector(fit_surgery_criteria_under_klg[idxs_to_use], ids[idxs_to_use]),
'yhat':fit_surgery_criteria_under_discretized_yhat[idxs_to_use].mean(),
'yhat_ci':get_ci_on_binary_vector(fit_surgery_criteria_under_discretized_yhat[idxs_to_use], ids[idxs_to_use]),
'yhat_match_surgeries':yhat_match_n_surgeries[idxs_to_use].mean(),
'yhat_klg_p':get_pvalue_on_binary_vector_mean_diff(yhat_vector=fit_surgery_criteria_under_discretized_yhat[idxs_to_use],
klg_vector=fit_surgery_criteria_under_klg[idxs_to_use],
ids=ids[idxs_to_use])})
for ses_var in all_ses_vars:
fracs_eligible_for_surgery.append({'group':ses_var,
'yhat':fit_surgery_criteria_under_discretized_yhat[(all_ses_vars[ses_var] == True) & idxs_to_use].mean(),
'yhat_ci':get_ci_on_binary_vector(fit_surgery_criteria_under_discretized_yhat[(all_ses_vars[ses_var] == True) & idxs_to_use],
ids[(all_ses_vars[ses_var] == True) & idxs_to_use]),
'klg':fit_surgery_criteria_under_klg[(all_ses_vars[ses_var] == True) & idxs_to_use].mean(),
'klg_ci':get_ci_on_binary_vector(fit_surgery_criteria_under_klg[(all_ses_vars[ses_var] == True) & idxs_to_use],
ids[(all_ses_vars[ses_var] == True) & idxs_to_use]),
'yhat_match_surgeries':yhat_match_n_surgeries[(all_ses_vars[ses_var] == True) & idxs_to_use].mean(),
'yhat_klg_p':get_pvalue_on_binary_vector_mean_diff(yhat_vector=fit_surgery_criteria_under_discretized_yhat[(all_ses_vars[ses_var] == True) & idxs_to_use], klg_vector=fit_surgery_criteria_under_klg[(all_ses_vars[ses_var] == True) & idxs_to_use],
ids=ids[(all_ses_vars[ses_var] == True) & idxs_to_use])})
fracs_eligible_for_surgery = pd.DataFrame(fracs_eligible_for_surgery)
fracs_eligible_for_surgery['yhat/klg'] = fracs_eligible_for_surgery['yhat'] / fracs_eligible_for_surgery['klg']
fracs_eligible_for_surgery['yhat_match_surgeries/klg'] = fracs_eligible_for_surgery['yhat_match_surgeries'] / fracs_eligible_for_surgery['klg']
print("Fraction eligible for surgery")
print(fracs_eligible_for_surgery[['group', 'klg', 'klg_ci', 'yhat', 'yhat_ci', 'yhat/klg', 'yhat_klg_p']])
assert (fracs_eligible_for_surgery['yhat/klg'] > 1).all()
assert (fracs_eligible_for_surgery['yhat_match_surgeries/klg'] >= 1).all()
for check in ['klg', 'yhat']:
# check CIs.
assert np.allclose(
fracs_eligible_for_surgery[check].values - fracs_eligible_for_surgery['%s_ci' % check].map(lambda x:float(x.split()[0].replace(',', '').replace('(', ''))),
fracs_eligible_for_surgery['%s_ci' % check].map(lambda x:float(x.split()[1].replace(',', '').replace(')', ''))) - fracs_eligible_for_surgery[check].values,
atol=1e-5)
# for each population we calculate both under the current regime and under our counterfactual surgery assignment: the rate of people who do not receive surgery and are in pain.
do_not_receive_surgery_and_are_in_pain = []
print("Do not receive surgery and are in pain")
do_not_receive_surgery_and_are_in_pain.append({'group':'Overall',
'klg':((fit_surgery_criteria_under_klg == 0) & in_high_pain)[idxs_to_use].mean(),
'klg_ci':get_ci_on_binary_vector(((fit_surgery_criteria_under_klg == 0) & in_high_pain)[idxs_to_use], ids[idxs_to_use]),
'yhat':((fit_surgery_criteria_under_discretized_yhat == 0) & in_high_pain)[idxs_to_use].mean(),
'yhat_ci':get_ci_on_binary_vector(((fit_surgery_criteria_under_discretized_yhat == 0) & in_high_pain)[idxs_to_use], ids[idxs_to_use]),
'yhat_match_surgeries':((yhat_match_n_surgeries == 0) & in_high_pain)[idxs_to_use].mean(),
'yhat_klg_p':get_pvalue_on_binary_vector_mean_diff(yhat_vector=((fit_surgery_criteria_under_discretized_yhat == 0) & in_high_pain)[idxs_to_use],
klg_vector=((fit_surgery_criteria_under_klg == 0) & in_high_pain)[idxs_to_use],
ids=ids[idxs_to_use])})
for ses_var in all_ses_vars:
do_not_receive_surgery_and_are_in_pain.append({'group':ses_var,
'klg':((fit_surgery_criteria_under_klg == 0) & in_high_pain)[(all_ses_vars[ses_var] == True) & idxs_to_use].mean(),
'klg_ci':get_ci_on_binary_vector(((fit_surgery_criteria_under_klg == 0) & in_high_pain)[idxs_to_use & (all_ses_vars[ses_var] == True)], ids[idxs_to_use & (all_ses_vars[ses_var] == True)]),
'yhat':((fit_surgery_criteria_under_discretized_yhat == 0) & in_high_pain)[(all_ses_vars[ses_var] == True) & idxs_to_use].mean(),
'yhat_ci':get_ci_on_binary_vector(((fit_surgery_criteria_under_discretized_yhat == 0) & in_high_pain)[idxs_to_use & (all_ses_vars[ses_var] == True)], ids[idxs_to_use & (all_ses_vars[ses_var] == True)]),
'yhat_match_surgeries':((yhat_match_n_surgeries == 0) & in_high_pain)[(all_ses_vars[ses_var] == True) & idxs_to_use].mean(),
'yhat_klg_p':get_pvalue_on_binary_vector_mean_diff(yhat_vector=((fit_surgery_criteria_under_discretized_yhat == 0) & in_high_pain)[(all_ses_vars[ses_var] == True) & idxs_to_use],
klg_vector=((fit_surgery_criteria_under_klg == 0) & in_high_pain)[(all_ses_vars[ses_var] == True) & idxs_to_use],
ids=ids[(all_ses_vars[ses_var] == True) & idxs_to_use])})
do_not_receive_surgery_and_are_in_pain = pd.DataFrame(do_not_receive_surgery_and_are_in_pain)
do_not_receive_surgery_and_are_in_pain['yhat/klg'] = do_not_receive_surgery_and_are_in_pain['yhat'] / do_not_receive_surgery_and_are_in_pain['klg']
do_not_receive_surgery_and_are_in_pain['yhat_match_surgeries/klg'] = do_not_receive_surgery_and_are_in_pain['yhat_match_surgeries'] / do_not_receive_surgery_and_are_in_pain['klg']
print(do_not_receive_surgery_and_are_in_pain[['group', 'klg', 'klg_ci', 'yhat', 'yhat_ci', 'yhat/klg', 'yhat_klg_p']])
assert (do_not_receive_surgery_and_are_in_pain['yhat/klg'] < 1).all()
assert (do_not_receive_surgery_and_are_in_pain['yhat_match_surgeries/klg'] <= 1).all()
for check in ['klg', 'yhat']:
# check CIs.
assert np.allclose(
do_not_receive_surgery_and_are_in_pain[check].values - do_not_receive_surgery_and_are_in_pain['%s_ci' % check].map(lambda x:float(x.split()[0].replace(',', '').replace('(', ''))),
do_not_receive_surgery_and_are_in_pain['%s_ci' % check].map(lambda x:float(x.split()[1].replace(',', '').replace(')', ''))) - do_not_receive_surgery_and_are_in_pain[check].values,
atol=1e-5)
# show in the non-surgical population the corrrelation between opioid use and y-hat
predict_medication_results = []
medications = ['rxactm', 'rxanalg', 'rxasprn', 'rxnarc', 'rxnsaid', 'rxothan']
for surgery_criterion in ['yhat', 'yhat_match_surgeries', 'klg']:
if surgery_criterion == 'yhat':
non_surgical_population = (fit_surgery_criteria_under_discretized_yhat == False) & idxs_to_use
elif surgery_criterion == 'klg':
non_surgical_population = (fit_surgery_criteria_under_klg == False) & idxs_to_use
elif surgery_criterion == 'yhat_match_surgeries':
non_surgical_population = (yhat_match_n_surgeries == False) & idxs_to_use
for m in medications:
df_for_regression = pd.DataFrame({'medication':df_to_use.loc[non_surgical_population, m].values,
'yhat':yhat[non_surgical_population],
'id':df_to_use.loc[non_surgical_population, 'id'].values})
df_for_regression = df_for_regression.dropna()
predict_on_medication_in_nonsurgical_population = sm.Logit.from_formula('medication ~ yhat', data=df_for_regression).fit(cov_type='cluster', cov_kwds={'groups':df_for_regression['id']})
predict_medication_results.append({'medication':MEDICATION_CODES[('v00' + m).upper()],
'beta_yhat':predict_on_medication_in_nonsurgical_population.params['yhat'],
'DV mean':df_for_regression['medication'].mean(),
'p_yhat':predict_on_medication_in_nonsurgical_population.pvalues['yhat'],
'surgery_criterion':surgery_criterion,
'n':predict_on_medication_in_nonsurgical_population.nobs})
predict_medication_results = pd.DataFrame(predict_medication_results)[['surgery_criterion', 'medication', 'beta_yhat', 'p_yhat', 'DV mean', 'n']]
predict_medication_results['sig'] = predict_medication_results['p_yhat'].map(sig_star)
assert (predict_medication_results['sig'].map(lambda x:'*' in x) & (predict_medication_results['beta_yhat'] > 0)).sum() == 0 # make sure no significant associations in the wrong direction.
print(predict_medication_results.sort_values(by='medication'))
def extract_all_ses_vars(df):
"""
Small helper method: return a dictionary of variables coded in the proper direction.
"""
for k in ['binarized_income_at_least_50k', 'binarized_education_graduated_college', 'race_black']:
assert df[k].map(lambda x:x in [0, 1]).all()
assert df[k].map(lambda x:x in [True, False]).all()
income_at_least_50k = df['binarized_income_at_least_50k'].values == 1
graduated_college = df['binarized_education_graduated_college'].values == 1
race_black = df['race_black'].values == 1
all_ses_vars = {'did_not_graduate_college':~(graduated_college == 1),
'income_less_than_50k':~(income_at_least_50k == 1),
'race_black':race_black == 1}
return all_ses_vars, income_at_least_50k, graduated_college, race_black
def assess_treatment_gaps_controlling_for_klg(klg, all_ses_vars, baseline_idxs, df_to_use):
"""
Regression:
treatment ~ SES + controls, where controls \in [KLG, none].
"""
check_is_array(klg)
check_is_array(baseline_idxs)
pd.set_option('max_rows', 500)
get_OR_and_CI = lambda m:'%2.2f (%2.2f, %2.2f)' % (np.exp(m.params['ses']), np.exp(m.conf_int().loc['ses', 0]), np.exp(m.conf_int().loc['ses', 1]))
treatment_gaps_regression_results = []
for treatment in ['knee_surgery', 'rxnarc', 'rxactm', 'rxanalg', 'rxasprn', 'rxnsaid', 'rxothan']:
for just_use_baseline in [True, False]:
idxs_to_use = np.ones(baseline_idxs.shape) == 1
if just_use_baseline:
idxs_to_use = idxs_to_use & (baseline_idxs == 1)
for control_for_klg in [True, False]:
for ses_var_name in all_ses_vars:
regression_df = pd.DataFrame({'ses':all_ses_vars[ses_var_name][idxs_to_use] * 1.,
'klg':klg[idxs_to_use],
'treatment':df_to_use.loc[idxs_to_use, treatment].values,
'id':df_to_use.loc[idxs_to_use, 'id'].values,
'visit':df_to_use.loc[idxs_to_use, 'visit'].values}).dropna()
if control_for_klg:
formula = 'treatment ~ ses + C(klg)'
else:
formula = 'treatment ~ ses'
regression_model = sm.Logit.from_formula(formula, data=regression_df).fit(cov_type='cluster', cov_kwds={'groups':regression_df['id'].values})
treatment_gaps_regression_results.append({'n_obs':regression_model.nobs,
'just_baseline':just_use_baseline,
'klg_control':control_for_klg,
'treatment':MEDICATION_CODES[('v00' + treatment).upper()] if treatment != 'knee_surgery' else 'knee_surgery',
'ses_var':ses_var_name,
'ses_OR':get_OR_and_CI(regression_model),
'DV mean':'%2.3f' % regression_df['treatment'].mean() ,
'sig':sig_star(regression_model.pvalues['ses'])})
treatment_gaps_regression_results = pd.DataFrame(treatment_gaps_regression_results)[['just_baseline',
'klg_control',
'treatment',
'ses_var',
'ses_OR',
'sig',
'DV mean',
'n_obs']]
print(treatment_gaps_regression_results)
def study_effect_of_surgery(df_to_use, surgery_col_to_analyze):
"""
The goal here was to show that people are in less pain after surgery, which is true for arthroplasty (not arthroscopy).
"""
pd.set_option('display.width', 500)
df_to_use = df_to_use.copy()
df_to_use['high_pain'] = binarize_koos(df_to_use['koos_pain_subscore'])
print("Prior to dropping people with missing %s data, %i rows" % (surgery_col_to_analyze, len(df_to_use)))
df_to_use = df_to_use.dropna(subset=[surgery_col_to_analyze])
print("After dropping people with missing %s data, %i rows" % (surgery_col_to_analyze, len(df_to_use)))
df_to_use['id_plus_side'] = df_to_use['id'].astype(str) + '*' + df_to_use['side'].astype(str)
medications = ['rxactm', 'rxanalg', 'rxasprn', 'rxnarc', 'rxnsaid', 'rxothan']
outcomes = ['koos_pain_subscore', 'high_pain'] + medications + ['all_pain_medications_combined']
df_to_use['all_pain_medications_combined'] = False
for k in medications:
df_to_use['all_pain_medications_combined'] = (df_to_use['all_pain_medications_combined'] | (df_to_use[k] == 1))
grouped_d = df_to_use.groupby('id_plus_side')
outcomes_to_changes = {}
for outcome in outcomes:
outcomes_to_changes[outcome] = []
outcomes_to_changes['pre_surgery_klg'] = []
outcomes_to_changes['pre_surgery_discretized_yhat'] = []
for group_id, small_d in grouped_d:
small_d = small_d.copy().sort_values(by='visit')
if small_d[surgery_col_to_analyze].sum() == 0:
continue
if small_d[surgery_col_to_analyze].iloc[0] == 1:
continue
small_d.index = range(len(small_d))
before_surgery = small_d[surgery_col_to_analyze] == 0
after_surgery = small_d[surgery_col_to_analyze] == 1
assert before_surgery.sum() > 0
assert after_surgery.sum() > 0
outcomes_to_changes['pre_surgery_klg'].append(small_d.loc[before_surgery, 'xrkl'].dropna().mean())
if 'discretized_yhat' in small_d.columns:
outcomes_to_changes['pre_surgery_discretized_yhat'].append(small_d.loc[before_surgery, 'discretized_yhat'].dropna().mean())
else:
outcomes_to_changes['pre_surgery_discretized_yhat'].append(np.nan)
for outcome in outcomes:
if pd.isnull(small_d[outcome]).mean() > 0:
continue
before_surgery_mean = small_d.loc[before_surgery, outcome].mean()
after_surgery_mean = small_d.loc[after_surgery, outcome].mean()
outcomes_to_changes[outcome].append({'before_surgery':before_surgery_mean, 'after_surgery':after_surgery_mean})
assert sorted(small_d[surgery_col_to_analyze].values) == list(small_d[surgery_col_to_analyze].values)
outcomes_to_changes['pre_surgery_klg'] = np.array(outcomes_to_changes['pre_surgery_klg'])
outcomes_to_changes['pre_surgery_discretized_yhat'] = np.array(outcomes_to_changes['pre_surgery_discretized_yhat'])
if np.isnan(outcomes_to_changes['pre_surgery_discretized_yhat']).mean() < 1:
assert (np.isnan(outcomes_to_changes['pre_surgery_klg']) == np.isnan(outcomes_to_changes['pre_surgery_discretized_yhat'])).all()
for k in ['pre_surgery_klg', 'pre_surgery_discretized_yhat']:
not_nan = ~np.isnan(outcomes_to_changes[k])
print('Mean of %s prior to surgery in people who had surgery: %2.5f; median %2.5f' % (k,
outcomes_to_changes[k][not_nan].mean(),
np.median(outcomes_to_changes[k][not_nan])))
results_df = []
for outcome in outcomes:
pre_surgery_values = np.array([a['before_surgery'] for a in outcomes_to_changes[outcome]])
post_surgery_values = np.array([a['after_surgery'] for a in outcomes_to_changes[outcome]])
t, p = ttest_rel(pre_surgery_values, post_surgery_values)
pretty_outcome_name = MEDICATION_CODES['V00' + outcome.upper()] if 'V00' + outcome.upper() in MEDICATION_CODES else outcome
results_df.append({'outcome':pretty_outcome_name,
'n':len(post_surgery_values),
'pre_surgery_larger':(pre_surgery_values > post_surgery_values).sum(),
'post_surgery_larger':(pre_surgery_values < post_surgery_values).sum(),
'no_change':(pre_surgery_values == post_surgery_values).sum(),
'pre_surgery_mean':pre_surgery_values.mean(),
'post_surgery_mean':post_surgery_values.mean(),
'p':p})
if np.isnan(outcomes_to_changes['pre_surgery_discretized_yhat']).mean() < 1:
# check whether yhat predicts surgical outcomes -- but this turns out to be pretty impossible due to small size o fhte test set.
for outcome in outcomes:
print(outcome)
pre_surgery_values = np.array([a['before_surgery'] for a in outcomes_to_changes[outcome]])
post_surgery_values = np.array([a['after_surgery'] for a in outcomes_to_changes[outcome]])
for k in ['pre_surgery_klg', 'pre_surgery_discretized_yhat']:
not_nan = ~np.isnan(outcomes_to_changes[k])
r, p = pearsonr(outcomes_to_changes[k][not_nan], post_surgery_values[not_nan] - pre_surgery_values[not_nan])
print("Correlation between %s and post-surgery change: %2.3f, p=%2.3e; n=%i" % (k, r, p, not_nan.sum()))
return pd.DataFrame(results_df)[['outcome', 'n', 'pre_surgery_larger', 'no_change', 'post_surgery_larger', 'pre_surgery_mean', 'post_surgery_mean', 'p']]
def analyze_performance_on_held_out_sites(all_site_generalization_results, yhat, y, yhat_from_klg, site_vector, all_ses_vars, ids, recalibrate_to_new_set):
"""
Check how we do on held out data (ie, train just on 4 sites, validate+test on the fifth).
all_site_generalization_results is a dataframe with performance results.
If recalibrate_to_new_set is True, fits a model ax + b on the held out site (improves RMSE but leaves r^2 unchanged).
This seems like something you probably want to avoid doing.
"""
pd.set_option("display.width", 500)
# Just a little bit of paranoia here to avoid accidental modification due to pass-by-reference.
yhat = yhat.copy()
y = y.copy()
yhat_from_klg = yhat_from_klg.copy()
site_vector = site_vector.copy()
all_ses_vars = copy.deepcopy(all_ses_vars)
ids = ids.copy()
# one way to combine performance across all 5 settings: stich together yhat/KLG for each held out site. But this is kind of weird.
stitched_together_held_out_yhat = np.nan * np.ones(yhat.shape)
stitched_together_klg = np.nan * np.ones(yhat.shape)
results_to_plot = []
all_site_names = sorted(list(set(all_site_generalization_results['site_to_remove'])))
concatenated_pain_gap_reductions = []
for site in all_site_names:
model_idxs = all_site_generalization_results['site_to_remove'] == site
site_idxs = site_vector == site
site_ensemble_results, ensemble_site_yhat = try_ensembling(all_site_generalization_results.loc[model_idxs],
5,
binary_prediction=False)
yhat_from_klg_to_use = yhat_from_klg.copy()
ensemble_site_yhat[~site_idxs] = np.nan
if recalibrate_to_new_set:
# recalibrate yhat
df_for_recalibration = pd.DataFrame({'yhat':ensemble_site_yhat[site_idxs], 'y':y[site_idxs]})
recalibration_model = sm.OLS.from_formula('y ~ yhat', data=df_for_recalibration).fit()
ensemble_site_yhat[site_idxs] = recalibration_model.predict(df_for_recalibration)
# recalibrate KLG
df_for_recalibration = pd.DataFrame({'yhat':yhat_from_klg_to_use[site_idxs], 'y':y[site_idxs]})
recalibration_model = sm.OLS.from_formula('y ~ yhat', data=df_for_recalibration).fit()
yhat_from_klg_to_use[site_idxs] = recalibration_model.predict(df_for_recalibration)
stitched_together_held_out_yhat[site_idxs] = ensemble_site_yhat[site_idxs]
stitched_together_klg[site_idxs] = yhat_from_klg_to_use[site_idxs]
# KLG
klg_results_for_site = assess_performance(
yhat=yhat_from_klg_to_use[site_idxs],
y=y[site_idxs],
binary_prediction=False)
klg_results_for_site['predictor'] = 'klg'
# held out yhat
held_out_yhat_results_for_site = assess_performance(
yhat=ensemble_site_yhat[site_idxs],
y=y[site_idxs],
binary_prediction=False)
held_out_yhat_results_for_site['predictor'] = 'held_out_yhat'
# original performance results, restricted to site.
yhat_results_for_site = assess_performance(
yhat=yhat[site_idxs],
y=y[site_idxs],
binary_prediction=False)
yhat_results_for_site['predictor'] = 'yhat'
results_for_site_compared = pd.DataFrame([yhat_results_for_site, held_out_yhat_results_for_site, klg_results_for_site])
results_for_site_compared['n'] = site_idxs.sum()
results_for_site_compared['n_models'] = model_idxs.sum()
results_for_site_compared['site'] = site
results_to_plot.append(results_for_site_compared)
print(results_for_site_compared[['predictor', 'r^2', 'negative_rmse', 'spearman_r^2', 'n', 'n_models']])
ses_vars_to_use = copy.deepcopy(all_ses_vars)
for var_name in ses_vars_to_use:
ses_vars_to_use[var_name] = all_ses_vars[var_name][site_idxs]
print("Pain gap analysis (important point is that Rival red. vs nothing < red. vs nothing)")
pain_gap_reduction = quantify_pain_gap_reduction_vs_rival(yhat=ensemble_site_yhat[site_idxs],
y=y[site_idxs],
rival_severity_measure=yhat_from_klg_to_use[site_idxs],
all_ses_vars=ses_vars_to_use,
ids=ids[site_idxs])
concatenated_pain_gap_reductions.append(pain_gap_reduction)
assert (pain_gap_reduction['No controls gap'] < 0).all()
assert (pain_gap_reduction['Rival red. vs nothing'] < pain_gap_reduction['red. vs nothing']).all()
print(pain_gap_reduction[['SES var',
'Rival red. vs nothing',
'red. vs nothing',
'yhat/rival red. ratio',
'n_people',
'n_obs']])
results_to_plot = pd.concat(results_to_plot)
print("\n\nUnweighted mean predictive performance across all 5 sites")
print(results_to_plot.groupby('predictor').mean())
print("Unweighted mean pain gap reduction performance across all 5 sites")
concatenated_pain_gap_reductions = pd.concat(concatenated_pain_gap_reductions)
print(concatenated_pain_gap_reductions.groupby('SES var').mean()[['Rival red. vs nothing', 'red. vs nothing']])
plt.figure(figsize=[12, 4])
for subplot_idx, col_to_plot in enumerate(['r^2', 'spearman_r^2', 'negative_rmse']):
plt.subplot(1, 3, subplot_idx + 1)
for predictor in ['held_out_yhat', 'klg']:
predictor_idxs = results_to_plot['predictor'] == predictor
plt.scatter(
x=range(predictor_idxs.sum()),
y=results_to_plot.loc[predictor_idxs, col_to_plot].values,
label=predictor)
plt.xticks(range(predictor_idxs.sum()), results_to_plot.loc[predictor_idxs, 'site'].values)
plt.title(col_to_plot)
plt.legend()
plt.show()
print("Stitched together predictor across all sites! Not really using this at present")
print("yhat")
assert np.isnan(stitched_together_held_out_yhat).sum() == 0
print(assess_performance(yhat=yhat,
y=y,
binary_prediction=False))
print("stitched together held out yhat")
print(assess_performance(yhat=stitched_together_held_out_yhat,
y=y,
binary_prediction=False))
print("KLG")
print(assess_performance(yhat=stitched_together_klg,
y=y,
binary_prediction=False))
print(quantify_pain_gap_reduction_vs_rival(yhat=stitched_together_held_out_yhat,
y=y,
rival_severity_measure=stitched_together_klg,
all_ses_vars=all_ses_vars,
ids=ids)[['SES var',
'Rival red. vs nothing',
'red. vs nothing',
'yhat/rival red. ratio',
'n_people',
'n_obs']])
def analyze_effect_of_diversity(all_diversity_results, all_ses_vars, y, yhat_from_klg, ids, n_bootstraps):
"""
Look at the effect of training on all non-minority patients, as opposed to including some minority patients.
Checked.
"""
for ses_group in sorted(list(set(all_diversity_results['ses_col']))):
print('\n\n\n\n%s' % ses_group)
metrics_we_want = []
if ses_group == 'race_black':
minority_idxs = all_ses_vars['race_black']
elif ses_group == 'binarized_education_graduated_college':
minority_idxs = all_ses_vars['did_not_graduate_college']
elif ses_group == 'binarized_income_at_least_50k':
minority_idxs = all_ses_vars['income_less_than_50k']
else:
raise Exception("Invalid variable.")
assert minority_idxs.mean() < .5
vals_to_test_yhat = {}
for val in sorted(list(set(all_diversity_results['majority_group_seed']))):
# Note: all_diversity_results['majority_group_seed'] is None iff we exclude the minority group.
diversity_idxs = ((all_diversity_results['majority_group_seed'] == val) &
(all_diversity_results['ses_col'] == ses_group))
assert diversity_idxs.sum() >= 5
ensemble_diversity_results, ensemble_test_diversity_yhat = try_ensembling(all_diversity_results.loc[diversity_idxs], 5, binary_prediction=False)
vals_to_test_yhat[val] = ensemble_test_diversity_yhat
# Predictive performance on full dataset.
ensemble_diversity_results = ensemble_diversity_results.loc[ensemble_diversity_results['model'] == 'ensemble']
assert len(ensemble_diversity_results) == 1
results_for_seed = {'majority_group_seed':val,
'r^2':ensemble_diversity_results['r^2'].iloc[-1],
'spearman_r^2':ensemble_diversity_results['spearman_r^2'].iloc[-1],
'negative_rmse':ensemble_diversity_results['negative_rmse'].iloc[-1],
'n_models':diversity_idxs.sum()}
# predictive performance just on minority/majority.
just_minority_results = assess_performance(yhat=ensemble_test_diversity_yhat[minority_idxs],
y=y[minority_idxs],
binary_prediction=False)
non_minority_results = assess_performance(yhat=ensemble_test_diversity_yhat[~minority_idxs],
y=y[~minority_idxs],
binary_prediction=False)
for k in ['r^2', 'negative_rmse']:
results_for_seed['Just minority %s' % k] = just_minority_results[k]
for k in ['r^2', 'negative_rmse']:
results_for_seed['Just non-minority %s' % k] = non_minority_results[k]
# pain gap reduction.
diversity_pain_gap_reduction = quantify_pain_gap_reduction_vs_rival(yhat=ensemble_test_diversity_yhat,
y=y,
rival_severity_measure=yhat_from_klg,
all_ses_vars=all_ses_vars,
ids=ids)[['SES var', 'yhat/rival red. ratio']]
for ses_var in all_ses_vars:
results_for_seed['%s_pain gap reduction ratio' % ses_var] = diversity_pain_gap_reduction.loc[
diversity_pain_gap_reduction['SES var'] == ses_var, 'yhat/rival red. ratio'].iloc[0]
metrics_we_want.append(results_for_seed)
metrics_we_want = pd.DataFrame(metrics_we_want)
print(metrics_we_want)
# CIs
for val in ['0.0', '1.0', '2.0', '3.0', '4.0']:
print("Comparing predictive performance for diverse dataset with seed %s to non-diverse dataset (note that 'KLG' here is the non-diverse dataset)" % val)
bootstrap_CIs_on_model_performance(y=y,
yhat=vals_to_test_yhat[val],
yhat_from_klg=vals_to_test_yhat['nan'],
yhat_from_clinical_image_features=None,
ids=ids,
n_bootstraps=n_bootstraps)
for val in ['0.0', '1.0', '2.0', '3.0', '4.0']:
print("Comparing pain gap reduction for diverse dataset with seed %s to non-diverse dataset (note that 'KLG' here is the non-diverse dataset)" % val)
bootstrap_CIs_on_pain_gap_reduction(y=y,
yhat=vals_to_test_yhat[val],
yhat_from_klg=vals_to_test_yhat['nan'],
ids=ids,
all_ses_vars=all_ses_vars,
n_bootstraps=n_bootstraps,
quantities_of_interest=['yhat/rival red. ratio'])
main_titles = {'race_black':'Race\ndiversity',
'binarized_education_graduated_college':'Education\ndiversity',
'binarized_income_at_least_50k':'Income\ndiversity'}
plot_diversity_results(metrics_we_want,
main_title=main_titles[ses_group],
minority_idxs=minority_idxs,
y=y,
yhat_from_klg=yhat_from_klg)
def plot_diversity_results(metrics_we_want, main_title, minority_idxs, y, yhat_from_klg):
"""
Plot blue dots for KLG baseline, red dots for no-diversity condition, black dots for diversity condition.
metrics_we_want is a dataframe with performance under different majority_group_seed conditions.
Checked.
"""
check_is_array(minority_idxs)
check_is_array(y)
check_is_array(yhat_from_klg)
cols_to_plot = [#'negative_rmse',
'r^2',
#'spearman_r^2',
'did_not_graduate_college_pain gap reduction ratio',
'income_less_than_50k_pain gap reduction ratio',
'race_black_pain gap reduction ratio',
#'Just minority r^2',
#'Just non-minority r^2',
#'Just minority negative_rmse',
#'Just non-minority negative_rmse']
]
col_pretty_names = {'r^2':'$r^2$',
'did_not_graduate_college_pain gap reduction ratio':'Reduction in education pain disparity\n(relative to KLG)',
'income_less_than_50k_pain gap reduction ratio':'Reduction in income pain disparity\n(relative to KLG)',
'race_black_pain gap reduction ratio':'Reduction in race pain disparity\n(relative to KLG)'}
fontsize = 16
plt.figure(figsize=[6 * len(cols_to_plot), 3])
#plt.suptitle(main_title)
for subplot_idx, col in enumerate(cols_to_plot):
xlimits = None
plt.subplot(1, len(cols_to_plot), subplot_idx + 1)
assert sorted(list(set(metrics_we_want['majority_group_seed']))) == sorted(['0.0', '1.0', '2.0', '3.0', '4.0', 'nan'])
assert len(metrics_we_want) == 6
if 'pain gap reduction ratio' in col:
plt.scatter([1], [1], color='blue', label='KLG')
if col == 'did_not_graduate_college_pain gap reduction ratio':
xlimits = [.9, 5.1]
plt.xticks([1, 2, 3, 4, 5], ['1x', '2x', '3x', '4x', '5x'], fontsize=fontsize)
elif col == 'income_less_than_50k_pain gap reduction ratio':
xlimits = [.9, 3.1]
plt.xticks([1, 2, 3], ['1x', '2x', '3x'], fontsize=fontsize)
elif col == 'race_black_pain gap reduction ratio':
xlimits = [.9, 6.1]
plt.xticks([1, 2, 3, 4, 5, 6], ['1x', '2x', '3x', '4x', '5x', '6x'], fontsize=fontsize)
else:
raise Exception("Invalid column")
elif 'Just minority' in col:
klg_counterpart = assess_performance(y=y[minority_idxs],
yhat=yhat_from_klg[minority_idxs],
binary_prediction=False)[col.split()[-1]]
plt.scatter([klg_counterpart], [1], color='blue', label='KLG')
elif 'Just non-minority' in col:
klg_counterpart = assess_performance(y=y[~minority_idxs],
yhat=yhat_from_klg[~minority_idxs],
binary_prediction=False)[col.split()[-1]]
plt.scatter([klg_counterpart], [1], color='blue', label='KLG')
else:
if col == 'r^2':
xlimits = [.09, .18]
plt.xticks([.1, .12, .14, .16], fontsize=fontsize)
klg_counterpart = assess_performance(y=y, yhat=yhat_from_klg, binary_prediction=False)[col]
plt.scatter([klg_counterpart], [1], color='blue', label='KLG')
plt.scatter([], [], label='') # this is just to make the legend spacing good.
# This is the non-diversity condition. One red dot.
plt.scatter(metrics_we_want.loc[metrics_we_want['majority_group_seed'] == 'nan', col].values,
[1],
color='red',
label='Non-diverse\ntrain set')
# This is the diversity condition. 5 black dots.
plt.scatter(metrics_we_want.loc[metrics_we_want['majority_group_seed'] != 'nan', col].values,
[1] * (len(metrics_we_want) - 1),
color='black',
label='Diverse\ntrain set')
if xlimits is not None:
assert (metrics_we_want[col].values > xlimits[0]).all()
assert (metrics_we_want[col].values < xlimits[1]).all()
plt.xlim(xlimits)
plt.yticks([])
plt.xlabel(col_pretty_names[col] if col in col_pretty_names else col, fontsize=fontsize)
if subplot_idx == 0:
plt.ylabel(main_title, fontsize=fontsize)
if 'race' in main_title.lower():
plt.legend(ncol=3, fontsize=fontsize, labelspacing=0.2, columnspacing=.2, handletextpad=.1, loc=(.08, .6))
plt.subplots_adjust(left=.05, right=.95, bottom=.3, wspace=.05)
plt.savefig('diversity_%s.png' % main_title.replace(' ', '_').replace('\n', '_'), dpi=300)
plt.show()
def print_out_paired_images(df, dataset, pair_idxs, title_fxn, directory_to_save):
"""
Saves images in pairs so we can look for differences.
pair_idxs should be a list of image pairs (list of lists). Title_fxn takes in df and an index i and returns a title.
"""
for i in range(len(pair_idxs)):
img_1 = dataset[pair_idxs[i][0]]['image'][0, :, :]
img_1 = (img_1 - img_1.mean()) / img_1.std()
img_2 = dataset[pair_idxs[i][1]]['image'][0, :, :]
img_2 = (img_2 - img_2.mean()) / img_2.std()
plt.figure()
plt.subplot(121)
plt.imshow(img_1, clim=[-3, 3], cmap='bone')
plt.title(title_fxn(df, pair_idxs[i][0]))
plt.xticks([])
plt.yticks([])
plt.subplot(122)
plt.imshow(img_2, clim=[-3, 3], cmap='bone')
plt.title(title_fxn(df, pair_idxs[i][1]))
plt.xticks([])
plt.yticks([])
plt.savefig(os.path.join(directory_to_save, 'pair_%i.png' % i), dpi=300)
plt.show()
def generate_paired_images_to_inspect_three_different_ways(dataset_to_use, yhat):
"""
Try pairing images by KLG; by all image features (basically we take the max over feature categories); and by invididual and side. In all cases, the
"high pain" image is on the right, although the way we define "high pain" changes.
"""
# 1. Pair images by KLG. Just use KLG 2.
df = dataset_to_use.non_image_data.copy()
df['yhat'] = yhat
klg_idxs = (df['xrkl'] == 2)
bad_y_cutoff = scoreatpercentile(df.loc[klg_idxs, 'koos_pain_subscore'], 10)
bad_yhat_cutoff = scoreatpercentile(df.loc[klg_idxs, 'yhat'], 10)
print("Bad Y cutoff is %2.3f; yhat cutoff is %2.3f" % (bad_y_cutoff, bad_yhat_cutoff))
good_y_cutoff = scoreatpercentile(df.loc[klg_idxs, 'koos_pain_subscore'], 90)
good_yhat_cutoff = scoreatpercentile(df.loc[klg_idxs, 'yhat'], 90)
print("Good Y cutoff is %2.3f; yhat cutoff is %2.3f" % (good_y_cutoff, good_yhat_cutoff))
low_pain_candidates = np.array(range(len(df)))[klg_idxs &
(df['yhat'] >= good_yhat_cutoff) &
(df['koos_pain_subscore'] >= good_y_cutoff)]
random.shuffle(low_pain_candidates)
high_pain_candidates = np.array(range(len(df)))[klg_idxs &
(df['yhat'] <= bad_yhat_cutoff) &
(df['koos_pain_subscore'] <= bad_y_cutoff)]
random.shuffle(high_pain_candidates)
print("%i low pain candidates; %i high pain candidates" % (len(low_pain_candidates),
len(high_pain_candidates)))
n_images = min(len(high_pain_candidates), len(low_pain_candidates))
paired_image_idxs = list(zip(low_pain_candidates[:n_images], high_pain_candidates[:n_images]))
def title_fxn(df, idx):
return 'KLG %i; yhat %2.1f; y %2.1f' % (df.iloc[idx]['xrkl'],
df.iloc[idx]['yhat'],
df.iloc[idx]['koos_pain_subscore'])
print_out_paired_images(df=df,
dataset=dataset_to_use,
pair_idxs=paired_image_idxs,
title_fxn=title_fxn,
directory_to_save='paired_images/paired_by_KLG/')
# pair images by image features.
# Set looser percentile cutoffs than in KLG pairing, to ensure we actually have pairs.
df = dataset_to_use.non_image_data.copy()
df['yhat'] = yhat
feature_groups_to_match_on = ['att', 'ch', 'cy', 'js', 'os', 'kl', 'sc']
def title_fxn(df, idx):
return '%s\nyhat %2.1f; y %2.1f' % (' '.join(['%s%1.0f' % (a, df.iloc[idx]['max_%s' % a]) for a in feature_groups_to_match_on]),
df.iloc[idx]['yhat'],
df.iloc[idx]['koos_pain_subscore'])
all_cols_used = []
for feature_group in feature_groups_to_match_on:
cols_to_use = sorted([a for a in CLINICAL_CONTROL_COLUMNS if feature_group in a])
print("taking max of features", cols_to_use, 'for %s' % feature_group)
df['max_%s' % feature_group] = df[cols_to_use].values.max(axis=1)
assert pd.isnull(df['max_%s' % feature_group]).sum() == 0
all_cols_used += cols_to_use
assert sorted(all_cols_used) == sorted(CLINICAL_CONTROL_COLUMNS) # make sure we have a disjoint partition of the original column set.
grouped_d = df.groupby(['max_%s' % a for a in feature_groups_to_match_on])
bad_y_cutoff = scoreatpercentile(df['koos_pain_subscore'], 40)
bad_yhat_cutoff = scoreatpercentile(df['yhat'], 40)
print("Y cutoff is %2.3f; yhat cutoff is %2.3f" % (bad_y_cutoff, bad_yhat_cutoff))
good_y_cutoff = scoreatpercentile(df['koos_pain_subscore'], 60)
good_yhat_cutoff = scoreatpercentile(df['yhat'], 60)
print("Y cutoff is %2.3f; yhat cutoff is %2.3f" % (good_y_cutoff, good_yhat_cutoff))
pair_idxs = []
for feature_vals, small_d in grouped_d:
if len(small_d) > 1:
bad_idxs = ((small_d['koos_pain_subscore'] <= bad_y_cutoff) &
(small_d['yhat'] <= bad_yhat_cutoff))
good_idxs = ((small_d['koos_pain_subscore'] >= good_y_cutoff) &
(small_d['yhat'] >= good_yhat_cutoff))
if bad_idxs.sum() > 0 and good_idxs.sum() > 0:
bad_small_d = small_d.loc[bad_idxs]
good_small_d = small_d.loc[good_idxs]
bad_idx = random.choice(bad_small_d.index)
good_idx = random.choice(good_small_d.index)
pair_idxs.append([good_idx, bad_idx])
print_out_paired_images(df=df,
dataset=dataset_to_use,
pair_idxs=pair_idxs,
title_fxn=title_fxn,
directory_to_save='paired_images/paired_by_image_features/')
# pair by person, side, and KLG. (So variation is just over time). Set a threshold on change in pain/yhat.
df = dataset_to_use.non_image_data.copy()
df['yhat'] = yhat
def title_fxn(df, idx):
return '%s, %s side\nKLG %i\nyhat %2.1f; y %2.1f' % (
df.iloc[idx]['visit'],
df.iloc[idx]['side'],
df.iloc[idx]['xrkl'],
df.iloc[idx]['yhat'],
df.iloc[idx]['koos_pain_subscore'])
grouped_d = df.groupby(['id', 'side', 'xrkl'])
pair_idxs = []
for feature_vals, small_d in grouped_d:
if len(small_d) > 1:
small_d = small_d.copy().sort_values(by='koos_pain_subscore')[::-1]
koos_change = small_d.iloc[0]['koos_pain_subscore'] - small_d.iloc[-1]['koos_pain_subscore']
yhat_change = small_d.iloc[0]['yhat'] - small_d.iloc[-1]['yhat']
if koos_change > 5 and yhat_change > 5:
pair_idxs.append([small_d.index[0], small_d.index[-1]])
print_out_paired_images(df=df,
dataset=dataset_to_use,
pair_idxs=pair_idxs,
title_fxn=title_fxn,
directory_to_save='paired_images/paired_by_person_and_side/')
def stratify_performances(df, yhat, y, yhat_from_klg):
"""
How do we do across subsets of the dataset relative to KLG?
"""
stratified_performances = []
pd.set_option('max_rows', 500)
for thing_to_stratify_by in ['v00site',
'side',
'visit',
'p02sex',
'age_at_visit',
'current_bmi',
'binarized_income_at_least_50k',
'binarized_education_graduated_college',
'race_black']:
for k in sorted(list(set(df[thing_to_stratify_by].dropna()))):
substratification_idxs = df[thing_to_stratify_by].values == k
if substratification_idxs.sum() < 100:
# don't plot super-noisy groups.
continue
yhat_performance = assess_performance(yhat=yhat[substratification_idxs],
y=y[substratification_idxs],
binary_prediction=False)
klg_performance = assess_performance(yhat=yhat_from_klg[substratification_idxs],
y=y[substratification_idxs],
binary_prediction=False)
stratified_performances.append(yhat_performance)
stratified_performances[-1]['predictor'] = 'yhat'
stratified_performances[-1]['substratification'] = thing_to_stratify_by + ' ' + str(k)
stratified_performances[-1]['n'] = substratification_idxs.sum()
stratified_performances.append(klg_performance)
stratified_performances[-1]['predictor'] = 'klg'
stratified_performances[-1]['substratification'] = thing_to_stratify_by + ' ' + str(k)
stratified_performances[-1]['n'] = substratification_idxs.sum()
for metric in ['r^2', 'negative_rmse']:
if yhat_performance[metric] < klg_performance[metric]:
print('Warning: yhat %s (%2.3f) is less than KLGs (%2.3f) for %s' %
(metric,
yhat_performance[metric],
klg_performance[metric],
k))
print("All other metrics passed. If a few fail, and not by too much, probably noise.")
stratified_performances = pd.DataFrame(stratified_performances)
# plot performance across subsets.
sns.set_style('whitegrid')
plt.figure(figsize=[15, 5])
plt.subplot(121)
labels = stratified_performances.loc[stratified_performances['predictor'] == 'klg', 'substratification'].values
plt.scatter(range(len(labels)), stratified_performances.loc[stratified_performances['predictor'] == 'klg', 'r^2'].values, label='klg')
plt.scatter(range(len(labels)), stratified_performances.loc[stratified_performances['predictor'] == 'yhat', 'r^2'].values, label='yhat')
plt.xticks(range(len(labels)), labels, rotation=90)
plt.ylabel("r^2")
plt.legend()
plt.subplot(122)
plt.scatter(range(len(labels)), stratified_performances.loc[stratified_performances['predictor'] == 'klg', 'negative_rmse'].values, label='KLG')