forked from klocey/regression-workbench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
4731 lines (3971 loc) · 191 KB
/
app.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 sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.feature_selection import RFECV
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.stats.outliers_influence import summary_table
import statsmodels.stats.diagnostic as sm_diagnostic
import statsmodels.stats.stattools as stattools
import statsmodels.formula.api as smf
import statsmodels.stats.api as sms
import statsmodels.api as sm
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
from dash import dcc, html, dash_table
import dash
import plotly.graph_objects as go
from scipy import stats
import pandas as pd
import numpy as np
import datetime
import warnings
import random
import base64
import json
import sys
import math
import io
#########################################################################################
################################# CONFIG APP ############################################
#########################################################################################
FONT_AWESOME = "https://use.fontawesome.com/releases/v5.10.2/css/all.css"
chriddyp = 'https://codepen.io/chriddyp/pen/bWLwgP.css'
warnings.filterwarnings('ignore')
pd.set_option('display.max_columns', None)
external_stylesheets=[dbc.themes.BOOTSTRAP, FONT_AWESOME, chriddyp]
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config.suppress_callback_exceptions = True
server = app.server
xvars = ['Nothing uploaded']
yvar = 'Nothing uploaded'
#########################################################################################
########################### CUSTOM FUNCTIONS ############################################
#########################################################################################
def obs_pred_rsquare(obs, pred):
'''
Determines the proportion of variability in a data set accounted for by a model
In other words, this determines the proportion of variation explained by the 1:1 line
in an observed-predicted plot.
Used in various peer-reviewed publications:
1. Locey, K.J. and White, E.P., 2013. How species richness and total abundance
constrain the distribution of abundance. Ecology letters, 16(9), pp.1177-1185.
2. Xiao, X., McGlinn, D.J. and White, E.P., 2015. A strong test of the maximum
entropy theory of ecology. The American Naturalist, 185(3), pp.E70-E80.
3. Baldridge, E., Harris, D.J., Xiao, X. and White, E.P., 2016. An extensive
comparison of species-abundance distribution models. PeerJ, 4, p.e2823.
'''
r2 = 1 - sum((obs - pred) ** 2) / sum((obs - np.mean(obs)) ** 2)
return r2
def smart_scale(df, predictors, responses):
'''
Skewness generally comes in two forms:
1. Positive skew: Data with many small values and few large values.
2. Negative skew: Date with many large values and few small values.
Significantly skewed data can invalidate or obsure regression results by causing outliers
(extreme values in reponse variables) and leverage points (extreme values in predictor variables)
to exert a biased influence on the analysis.
The smart_scale function loops through each data feature in the input dataframe 'df' and conducts
a skewness test using scipy's skewtest function:
(https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.skewtest.html#scipy.stats.skewtest
If a feature is significantly skewed, the smart_scale function will loop through various data
transformations and attempt to find the one that brings the skewness closest to zero.
'''
for i in list(df):
stat, pval = float(), float()
try: stat, pval = stats.skewtest(df[i], nan_policy='omit')
except: continue
if pval >= 0.05:
continue
else:
skewness = stats.skew(df[i], nan_policy='omit') # Based on the Fisher-Pearson coefficient
best_skew = float(skewness)
best_lab = str(i)
t_vals = df[i].tolist()
if np.nanmin(df[i]) < 0:
# log-modulo transformation
lmt = np.log10(np.abs(df[i]) + 1).tolist()
for j, val in enumerate(df[i].tolist()):
if val < 0: lmt[j] = lmt[j] * -1
new_skew = stats.skew(lmt, nan_policy='omit')
if np.abs(new_skew) < best_skew:
best_skew = np.abs(new_skew)
best_lab = 'log<sub>mod</sub>(' + i + ')'
t_vals = lmt
# cube root transformation
crt = df[i]**(1/3)
new_skew = stats.skew(crt, nan_policy='omit')
if np.abs(new_skew) < best_skew:
best_skew = np.abs(new_skew)
best_lab = '\u221B(' + i + ')'
t_vals = crt
# cube transformation
ct = df[i]**3
new_skew = stats.skew(ct, nan_policy='omit')
if np.abs(new_skew) < best_skew:
best_skew = np.abs(new_skew)
best_lab = '(' + i + ')\u00B3'
t_vals = ct
elif np.nanmin(df[i]) == 0:
# log-shift transformation
lmt = np.log10(df[i] + 1).tolist()
new_skew = stats.skew(lmt, nan_policy='omit')
if np.abs(new_skew) < best_skew:
best_skew = np.abs(new_skew)
best_lab = 'log-shift(' + i + ')'
t_vals = lmt
# square root transformation
srt = df[i]**(1/2)
new_skew = stats.skew(srt, nan_policy='omit')
if np.abs(new_skew) < best_skew:
best_skew = np.abs(new_skew)
best_lab = '\u221A(' + i + ')'
t_vals = srt
# square transformation
st = df[i]**2
new_skew = stats.skew(st, nan_policy='omit')
if np.abs(new_skew) < best_skew:
best_skew = np.abs(new_skew)
best_lab = '(' + i + ')\u00B2'
t_vals = st
elif np.nanmin(df[i]) > 0:
lt = np.log10(df[i])
new_skew = stats.skew(lt, nan_policy='omit')
if np.abs(new_skew) < best_skew:
best_skew = np.abs(new_skew)
best_lab = 'log(' + i + ')'
t_vals = lt
# square root transformation
srt = df[i]**(1/2)
new_skew = stats.skew(srt, nan_policy='omit')
if np.abs(new_skew) < best_skew:
best_skew = np.abs(new_skew)
best_lab = '\u221A(' + i + ')'
t_vals = srt
# square transformation
st = df[i]**2
new_skew = stats.skew(st, nan_policy='omit')
if np.abs(new_skew) < best_skew:
best_skew = np.abs(new_skew)
best_lab = '(' + i + ')\u00B2'
t_vals = st
df[i] = list(t_vals)
df.rename(columns={i: best_lab}, inplace=True)
if i in predictors:
predictors.remove(i)
predictors.append(best_lab)
if i in responses:
responses.remove(i)
responses.append(best_lab)
df.replace([np.inf, -np.inf], np.nan, inplace=True)
return df, predictors, responses
def dummify(df, cat_vars, dropone=True):
'''
Convert categorical features to binary dummy variables.
df: input dataframe containing all numerical and categorical features
cat_vars: a list of categorical features
dropone: Indicates whether or not to drop one level from each categorical feature, as when
conducting linear or logistic multivariable regression.
Note: In the event that a categorical feature contains more than 10 levels, only the 10
most common levels are retained. If this happens, then the dropone argument can be ignored
as its function (to prevent perfect multicollinearity) will be redundant.
'''
dropped = []
cat_var_ls = []
interxn = list(set(cat_vars) & set(list(df)))
for i in interxn:
labs = list(set(df[i].tolist()))
df[i] = df[i].replace(r"^ +| +$", r"", regex=True)
subsample = 0
one_hot = pd.get_dummies(df[i])
if one_hot.shape[1] > 10:
subsample = 1
one_hot = one_hot[one_hot.sum().sort_values(ascending=False).index[:10]]
one_hot = one_hot.add_prefix(i + ':')
ls2 = list(one_hot)
if dropone == True and subsample == 0:
nmax = 0
lab = 0
for ii in ls2:
x = one_hot[ii].tolist()
n = x.count(1)
if n > nmax:
nmax = int(n)
lab = ii
one_hot.drop(labels=[lab], axis = 1, inplace=True)
dropped.append(lab)
labs = list(one_hot)
cat_var_ls.append(labs)
df = df.join(one_hot)
df.drop(labels=[i], axis = 1, inplace=True)
return df, dropped, cat_var_ls
def dummify_logistic(df, cat_vars, y_prefix, dropone=True):
'''
Convert categorical features to binary dummy variables.
df: input dataframe containing all numerical and categorical features
cat_vars: a list of categorical features
y_prefix: the category of the feature that was chosen as the response variable
dropone: Indicates whether or not to drop one level from each categorical feature, as when
conducting linear or logistic multivariable regression.
Note: In the event that a categorical feature contains more than 10 levels, only the 10
most common levels are retained. If this happens, then the dropone argument can be ignored
as its function (to prevent perfect multicollinearity) will be redundant.
'''
dropped = []
cat_var_ls = []
interxn = list(set(cat_vars) & set(list(df)))
for i in interxn:
labs = list(set(df[i].tolist()))
df[i] = df[i].replace(r"^ +| +$", r"", regex=True)
subsample = 0
one_hot = pd.get_dummies(df[i])
if one_hot.shape[1] > 10:
subsample = 1
one_hot = one_hot[one_hot.sum().sort_values(ascending=False).index[:10]]
one_hot = one_hot.add_prefix(i + ':')
ls2 = list(one_hot)
if dropone == True and subsample == 0 and i != y_prefix:
nmax = 0
lab = 0
for ii in ls2:
x = one_hot[ii].tolist()
n = x.count(1)
if n > nmax:
nmax = int(n)
lab = ii
one_hot.drop(labels=[lab], axis = 1, inplace=True)
dropped.append(lab)
labs = list(one_hot)
cat_var_ls.append(labs)
df = df.join(one_hot)
df.drop(labels=[i], axis = 1, inplace=True)
return df, dropped, cat_var_ls
def run_MLR(df_train, xvars, yvar, cat_vars, rfe_val):
X_train = df_train.copy(deep=True)
X_train, dropped, cat_vars_ls = dummify(X_train, cat_vars)
if X_train.shape[1] < 2:
return [], [], [], [], [], [], []
########## Eliminating features with many 0's ###########
x_vars = list(X_train)
drop = []
for var in x_vars:
vals = X_train[var].tolist()
frac_0 = vals.count(0)/len(vals)
if frac_0 > 0.95:
drop.append(var)
X_train.drop(labels=drop, axis=1, inplace=True)
X_train.dropna(how='any', inplace=True)
y_train = X_train.pop(yvar)
########## RFECV ############
model = LinearRegression()
rfecv = RFECV(model, step=1)
rfecv = rfecv.fit(X_train, y_train)
#support = rfecv.support_
ranks = rfecv.ranking_
xlabs = rfecv.feature_names_in_
supported_features = []
unsupported = []
for i, lab in enumerate(xlabs):
if ranks[i] == 1:
supported_features.append(lab)
else:
unsupported.append(lab)
for ls in cat_vars_ls:
check = list(set(ls) & set(supported_features)) # elements of ls that are in supported_features
if len(check) == 0:
supported_features = list(set(supported_features) - set(ls))
for l in ls:
try:
X_train.drop(l, axis=1, inplace=True)
unsupported.append(l)
except:
pass
elif len(check) > 0:
supported_features.extend(ls)
supported_features = list(set(supported_features))
if len(supported_features) >= 2:
if rfe_val == 'Yes':
X_train = X_train.filter(items = supported_features, axis=1)
X_train_lm = sm.add_constant(X_train, has_constant='add')
results = sm.OLS(y_train, X_train_lm).fit()
y_pred = results.predict(X_train_lm)
pval_df = results.pvalues
R2 = results.rsquared_adj
if R2 < 0: R2 = 0
results_summary = results.summary()
results_as_html1 = results_summary.tables[1].as_html()
df1_summary = pd.read_html(results_as_html1, header=0, index_col=0)[0]
results_as_html2 = results_summary.tables[0].as_html()
df2_summary = pd.read_html(results_as_html2, header=0, index_col=0)[0]
vifs = [variance_inflation_factor(X_train.values, j) for j in range(X_train.shape[1])]
colors = ["#3399ff"]*len(y_train)
cols = ['Parameter', 'coef', 'std err', 't', 'P>|t|', '[0.025]', '[0.975]']
df_table = pd.DataFrame(columns=cols)
df_table['Parameter'] = df1_summary.index.tolist()
df_table['coef'] = df1_summary['coef'].tolist()
df_table['std err'] = df1_summary['std err'].tolist()
df_table['t'] = df1_summary['t'].tolist()
df_table['P>|t|'] = df1_summary['P>|t|'].tolist()
df_table['[0.025]'] = df1_summary['[0.025'].tolist()
df_table['[0.975]'] = df1_summary['0.975]'].tolist()
xlabs = list(X_train)
vifs2 = []
for p in df_table['Parameter'].tolist():
print(p)
if p == 'const':
vifs2.append(np.nan)
else:
i = xlabs.index(p)
vif = vifs[i]
vifs2.append(np.round(vif,3))
df_table['VIF'] = vifs2
df1_summary = df_table
return y_train, y_pred, df1_summary, df2_summary, supported_features, unsupported, colors
def run_logistic_regression(df, xvars, yvar, cat_vars):
coefs = []
r2s = []
pvals = []
aics = []
llf_ls = []
PredY = []
PredProb = []
Ys = []
df.replace([np.inf, -np.inf], np.nan, inplace=True)
df.dropna(how='any', inplace=True)
df = df.loc[:, df.nunique() != 1]
y_o = df[yvar]
x_o = df.drop(labels=[yvar], axis=1, inplace=False)
########## Eliminating features that are perfectly correlated to the response variable ###########
perfect_correlates = []
for xvar in list(x_o):
x = x_o[xvar].tolist()
y = y_o.tolist()
slope, intercept, r, p, se = stats.linregress(x, y)
if r**2 == 1.0:
perfect_correlates.append(xvar)
x_o.drop(labels=perfect_correlates, axis=1, inplace=True)
########## Eliminating features that only have one value ###########
singularities = []
for xvar in list(x_o):
x = len(list(set(x_o[xvar].tolist())))
if x == 1:
singularities.append(xvar)
x_o.drop(labels=singularities, axis=1, inplace=True)
########## Eliminating features with many 0's ###########
x_vars = list(x_o)
drop = []
for var in x_vars:
vals = x_o[var].tolist()
frac_0 = vals.count(0)/len(vals)
if frac_0 > 0.95:
drop.append(var)
x_o.drop(labels=drop, axis=1, inplace=True)
########## Eliminating features using vif ###########
while x_o.shape[1] > 100:
cols = list(x_o)
vifs = [variance_inflation_factor(x_o.values, j) for j in range(x_o.shape[1])]
max_vif = max(vifs)
if max_vif > 10:
i = vifs.index(max(vifs))
col = cols[i]
x_o.drop(labels=[col], axis=1, inplace=True)
else:
break
########## RFECV ############
if x_o.shape[1] > 100:
model = LogisticRegression()
try:
rfecv = RFECV(model, step=1, min_features_to_select=2)
rfecv = rfecv.fit(x_o, y_o)
#support = rfecv.support_
ranks = rfecv.ranking_
xlabs = rfecv.feature_names_in_
supported_features = []
unsupported = []
for i, lab in enumerate(xlabs):
if ranks[i] == 1:
supported_features.append(lab)
else:
unsupported.append(lab)
#if len(supported_features) >= 2:
# if rfe_val == 'Yes':
#X_train = X_train.filter(items = supported_features, axis=1)
x_o = x_o.filter(items = supported_features, axis=1)
except:
pass
model = 0
x_o_lm = sm.add_constant(x_o, has_constant='add')
try:
model = sm.Logit(y_o, x_o_lm).fit(maxiter=30)
except:
return None, None, None, 1, None
results_summary = model.summary()
results_as_html1 = results_summary.tables[1].as_html()
df1_summary = pd.read_html(results_as_html1, header=0, index_col=0)[0]
results_as_html2 = results_summary.tables[0].as_html()
df2_summary = pd.read_html(results_as_html2, header=0, index_col=0)[0]
#results_as_html2 = results_summary.tables[2].as_html()
#df2_summary = pd.read_html(results_as_html2, header=0, index_col=0)[0]
vifs = [variance_inflation_factor(x_o.values, j) for j in range(x_o.shape[1])]
cols = ['Parameter', 'coef', 'std err', 'z', 'P>|z|', '[0.025]', '[0.975]']
df_table = pd.DataFrame(columns=cols)
df_table['Parameter'] = df1_summary.index.tolist()
df_table['coef'] = df1_summary['coef'].tolist()
df_table['std err'] = df1_summary['std err'].tolist()
df_table['z'] = df1_summary['z'].tolist()
df_table['P>|z|'] = df1_summary['P>|z|'].tolist()
df_table['[0.025]'] = df1_summary['[0.025'].tolist()
df_table['[0.975]'] = df1_summary['0.975]'].tolist()
xlabs = list(x_o)
vifs2 = []
for p in df_table['Parameter'].tolist():
if p == 'const':
vifs2.append(np.nan)
else:
i = xlabs.index(p)
vif = vifs[i]
vifs2.append(np.round(vif,3))
df_table['VIF'] = vifs2
df1_summary = df_table
df1_summary.sort_values(by='P>|z|', inplace=True, ascending=True)
#ypred = model.fittedvalues
ypred = model.predict(x_o_lm)
ypred = ypred.tolist()
#df['predicted probability'] = ypred
####### ROC CURVE #######################################
fpr, tpr, thresholds_roc = roc_curve(y_o, ypred, pos_label=1)
auroc = auc(fpr, tpr)
####### PRECISION-RECALL CURVE ##############################################
ppv, recall, thresholds_prc = precision_recall_curve(y_o, ypred, pos_label=1)
auprc = average_precision_score(y_o, ypred, pos_label=1)
#######
dist1 = np.sqrt((fpr - 0)**2 + (tpr - 1)**2)
dist1 = dist1.tolist()
di1 = dist1.index(np.nanmin(dist1))
thresholds_roc = thresholds_roc.tolist()
opt_roc_threshold = thresholds_roc[di1]
dist2 = np.sqrt((ppv - 1)**2 + (recall - 1)**2)
dist2 = dist2.tolist()
di2 = dist2.index(np.nanmin(dist2))
thresholds_prc = thresholds_prc.tolist()
opt_prc_threshold = thresholds_prc[di2]
opt_threshold = (opt_roc_threshold + opt_prc_threshold)/2
dif = np.abs(np.array(thresholds_roc) - opt_threshold).tolist()
di = dif.index(np.nanmin(dif))
opt_tpr = tpr[di]
opt_fpr = fpr[di]
dif = np.abs(np.array(thresholds_prc) - opt_threshold).tolist()
di = dif.index(np.nanmin(dif))
opt_ppv = ppv[di]
df['Predicted probability'] = ypred
ypred2 = []
for i in ypred:
if i < opt_threshold:
ypred2.append(0)
else:
ypred2.append(1)
ypred = list(ypred2)
lab = 'Binary prediction (optimal threshold =' + str(round(opt_threshold, 6)) + ')'
df[lab] = ypred
coefs.append(model.params[0])
pr2 = model.prsquared
if pr2 < 0:
pr2 = 0
aic = model.aic
#bic = model.bic
tp = model.pvalues[0]
llf = model.llf
#m_coefs = model.params[0].tolist()
#m_coefs.reverse()
r2s.append(np.round(pr2, 3))
pvals.append(np.round(tp, 3))
aics.append(np.round(aic, 3))
llf_ls.append(np.round(llf, 5))
Ys.append(y_o)
PredY.append(ypred)
y_o = y_o.tolist()
prc_null = y_o.count(1)/len(y_o)
cols = ['r-square']
df_models = pd.DataFrame(columns=cols)
df_models['r-square'] = r2s
df_models['p-value'] = pvals
df_models['AIC'] = aics
df_models['log-likelihood'] = llf_ls
df_models['FPR'] = [fpr]
df_models['TPR'] = [tpr]
df_models['PPV'] = [ppv]
df_models['Recall'] = [recall]
df_models['auprc'] = [auprc]
df_models['auroc'] = [auroc]
df_models['pred_y'] = PredY
df_models['pred_prob'] = [PredProb]
df_models['prc_null'] = [prc_null]
df_models['optimal_threshold'] = [opt_threshold]
df_models['optimal_tpr'] = [opt_tpr]
df_models['optimal_fpr'] = [opt_fpr]
df_models['optimal_ppv'] = [opt_ppv]
df_models['coefficients'] = coefs
#df_models = df_models.replace('_', ' ', regex=True)
#for col in list(df_models):
# col2 = col.replace("_", " ")
# df_models.rename(columns={col: col2})
df_models.reset_index(drop=True, inplace=True)
#col = df.pop('probability of ')
#df.insert(0, col.name, col)
col = df.pop('Predicted probability')
df.insert(0, col.name, col)
col = df.pop(lab)
df.insert(0, col.name, col)
col = df.pop(yvar)
df.insert(0, col.name, col)
return df_models, df1_summary, df2_summary, 0, df
#########################################################################################
#################### DASH APP CONTROL CARDS ############################################
#########################################################################################
def description_card1():
"""
:return: A Div containing dashboard title & descriptions.
"""
return html.Div(
id="description-card1",
children=[
html.H5("Regression workbench",
style={
'textAlign': 'left',
}),
dcc.Markdown("This app makes it easy to discover and explore interesting and powerful relationships within your data. Use it via the web or download the source code from [here] (https://github.com/klocey/regression-workbench) and run it locally.",
style={
'textAlign': 'left',
}),
],
)
def description_card_final():
"""
:return: A Div containing dashboard title & descriptions.
"""
return html.Div(
id="description-card-final",
children=[
html.H5("Developer",
style={
'textAlign': 'left',
}),
html.P("Kenneth J. Locey, PhD. Senior clinical data scientist. Center for Quality, Safety and Value Analytics. Rush University Medical Center.",
style={
'textAlign': 'left',
}),
html.H5("Testers",
style={
'textAlign': 'left',
}),
html.P("Ryan Schipfer. Senior clinical data scientist. Center for Quality, Safety and Value Analytics. Rush University Medical Center.",
style={
'textAlign': 'left',
}),
html.P("Brittnie Dotson. Clinical data scientist. Center for Quality, Safety and Value Analytics. Rush University Medical Center.",
style={
'textAlign': 'left',
}),
],
)
def control_card_upload():
return html.Div(
id="control-card-upload1",
children=[
html.H5("Begin by uploading your data", style={'display': 'inline-block',
'width': '295px'},),
html.I(className="fas fa-question-circle fa-lg", id="target1",
style={'display': 'inline-block', 'width': '20px', 'color':'#99ccff'},
),
dbc.Tooltip("Column headers should be short and should not have commas or colons. Values to be analyzed should not contain mixed data types, e.g., 10% and 10cm contain numeric and non-numeric characters.", target="target1",
style = {'font-size': 12},
),
html.P("This app only accepts .csv files. It also expects a simple format: rows, columns, one row of column headers, and nothing else. Check the tooltips for more info."),
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select a File', style={'color':'#2c8cff', "text-decoration": "underline"},),
]),
style={
'lineHeight': '68px',
'borderWidth': '2px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '20px',
},
multiple=False
),
html.P("Data are deleted when the app is refreshed, closed, or when another file is uploaded. Still, do not upload sensitive data."),
],
)
def control_card1():
return html.Div(
id="control-card1",
children=[
html.H5("Explore relationships between multiple features at once",
style={'display': 'inline-block', 'width': '41.5%'},),
html.I(className="fas fa-question-circle fa-lg", id="target_select_vars",
style={'display': 'inline-block', 'width': '3%', 'color':'#99ccff'},),
dbc.Tooltip("These analyses are based on ordinary least squares regression. They exclude categorical features, any features suspected of being dates or times, and any numeric features having less than 4 unique values.", target="target_select_vars", style = {'font-size': 12},),
html.Hr(),
html.B("Choose one or more x-variables. These are also known as predictors.",
style={'display': 'inline-block',
'vertical-align': 'top',
'margin-right': '10px',
}),
dcc.Dropdown(
id='xvar',
options=[{"label": i, "value": i} for i in []],
multi=True, value=None,
style={'width': '100%',
#'display': 'inline-block',
},
),
html.Br(),
html.B("Choose one or more y-variables. These are also known as response variables.",
style={'display': 'inline-block',
'vertical-align': 'top',
'margin-right': '10px',
}),
dcc.Dropdown(
id='yvar',
options=[{"label": i, "value": i} for i in []],
multi=True, value=None,
style={'width': '100%',
#'display': 'inline-block',
},
),
html.Hr(),
html.Br(),
dbc.Button('Run regressions',
id='btn1', n_clicks=0,
style={'width': '20%',
'font-size': 12,
"background-color": "#2a8cff",
'display': 'inline-block',
'margin-right': '20px',
},
),
dbc.Button("View results table",
id="open-centered2",
#color="dark",
#className="mr-1",
style={
"background-color": "#2a8cff",
'width': '16%',
'font-size': 12,
'display': 'inline-block',
#"height": "40px",
#'padding': '10px',
#'margin-bottom': '10px',
'margin-right': '20px',
#'margin-left': '11px',
},
),
dbc.Modal(
[dbc.ModalBody([html.Div(id='table_plot1'), html.Br(), html.P("", id='table1txt')]),
dbc.ModalFooter(
dbc.Button("Close", id="close-centered2", className="ml-auto")
),
],
id="modal-centered2",
is_open=False,
centered=True,
autoFocus=True,
size="xl",
keyboard=True,
fade=True,
backdrop=True,
),
dbc.Button('Smart scale',
id='btn_ss', n_clicks=0,
style={'width': '20%',
'font-size': 12,
"background-color": "#2a8cff",
'display': 'inline-block',
'margin-right': '10px',
},
),
html.I(className="fas fa-question-circle fa-lg", id="ss1",
style={'display': 'inline-block', 'width': '3%', 'color':'#99ccff'},),
dbc.Tooltip("Skewed data can weaken analyses and visualizations. Click on 'Smart Scale' and the app will automatically detect and rescale any skewed variables. To remove the rescaling just click 'Run Regressions'.",
target="ss1", style = {'font-size': 12},),
html.P("", id='rt0'),
],
style={'margin-bottom': '0px',
'margin': '10px',
'width': '98.5%',
},
)
def control_card2():
return html.Div(
id="control-card2",
children=[
html.H5("Conduct a single regression for deeper insights",
style={'display': 'inline-block', 'width': '35.4%'},),
html.I(className="fas fa-question-circle fa-lg", id="target_select_vars2",
style={'display': 'inline-block', 'width': '3%', 'color':'#99ccff'},),
dbc.Tooltip("These analyses are based on ordinary least squares regression. They exclude categorical features, any features suspected of being dates or times, and any numeric features having less than 4 unique values.", target="target_select_vars2", style = {'font-size': 12},),
html.Hr(),
html.Div(
id="control-card2a",
children=[
html.B("Choose a predictor (x) variable",
style={'display': 'inline-block',
'vertical-align': 'top',
'margin-right': '10px',
}),
dcc.Dropdown(
id='xvar2',
options=[{"label": i, "value": i} for i in []],
multi=False,
placeholder='Select a feature',
style={'width': '100%',
'display': 'inline-block',
},
),
],
style={'display': 'inline-block',
'vertical-align': 'top',
'margin-right': '20px',
'width': '20%',
}),
html.Div(
id="control-card2b",
children=[
html.B("Choose a data transformation",
style={'display': 'inline-block',
'vertical-align': 'top',
'margin-right': '10px',
}),
dcc.Dropdown(
id='x_transform',
options=[{"label": i, "value": i} for i in ['None', 'log10', 'square root', 'cube root',
'squared', 'cubed', 'log-modulo', 'log-shift']],
multi=False, value='None',
style={'width': '90%',
'display': 'inline-block',
},
),
],
style={'display': 'inline-block',
'vertical-align': 'top',
'margin-right': '20px',
'width': '20%',
}),
html.Div(
id="control-card2c",
children=[
html.B("Choose a response (y) variable",
style={'display': 'inline-block',
'vertical-align': 'top',
'margin-right': '10px',
}),
dcc.Dropdown(
id='yvar2',
options=[{"label": i, "value": i} for i in []],
multi=False,
placeholder='Select a feature',
style={'width': '100%',
'display': 'inline-block',
},
),
],
style={'display': 'inline-block',
'vertical-align': 'top',
'margin-right': '20px',
'width': '20%',
}),
html.Div(
id="control-card2d",
children=[
html.B("Choose a data transformation",
style={'display': 'inline-block',
'vertical-align': 'top',
'margin-right': '10px',
}),
dcc.Dropdown(
id='y_transform',
options=[{"label": i, "value": i} for i in ['None', 'log10', 'square root', 'cube root',
'squared', 'cubed', 'log-modulo', 'log-shift']],
multi=False, value='None',
style={'width': '90%',
'display': 'inline-block',
},
),
],
style={'display': 'inline-block',
'vertical-align': 'top',
'margin-right': '20px',
'width': '20%',
}),
html.Div(
id="control-card2e",
children=[
html.B("Choose a model",
style={'display': 'inline-block',
'vertical-align': 'top',
'margin-right': '10px',
}),
dcc.Dropdown(
id='model2',
options=[{"label": i, "value": i} for i in ['linear', 'quadratic', 'cubic']],
multi=False, value='linear',
style={'width': '100%',
'display': 'inline-block',