-
Notifications
You must be signed in to change notification settings - Fork 1
/
stage_03_Objective_1a_ML_v004.py
4767 lines (3813 loc) · 203 KB
/
stage_03_Objective_1a_ML_v004.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
'''Purpose of file
To produce profile of features more commonly associated with patients
who DNA Using Supervised Machine Learning to do so
Method/overview of what this file does:
- ingest / load pre-processed data
- Split data into features (X) and label (y)
- Split data into training and test sets (we will test on data that has
not been used to fit the model)
- Standardise data
- Fit a logistic regression model (from sklearn learn)
- Predict survival of the test set
- Define a function to calculate a range of accuracy measure (and return
as a dictionary)
- Report multiple accuracy scores for model
... repeat above for total of 9 variants of Logistic Regression model.
Measures of accuracy
The common measure of accuracy is "proportion of cases where the
classification / prediction was correct. DNAs are likely routinely a
relatively rare event and the data likely to be imbalanced (i.e. it is
not the case that 50% attend 50% DNA). If 1 person in 20 DNA's, the model
could have a 95% accuracy, by predicting no one ever DNA's and only
being wrong 1 in 20 times (i.e. missing every single DNA it exists
to predict). For this reason, alternative, more sophisticated accuracy
measure(s) are needed:
sensitivity = proportion of positive cases (DNA) correctly classified
specificity = proportion of negative (didnt DNA) correctly classified
Machine learning thresholds can be adjusted to change the balance between
these sensitivity and specificity.
In addition to sensitivity and specificity, common measures used in ML are:
precision
recall
f1 (combination of precision and recall)
Full list of measures that returned from accuracy functon are listed below.
NOTE: These are relevant for binomial classification problems (attend/DNA).
Where there are >two possible classes, a confusion matrix is commonly used
(see https://pythonhealthcare.org/2018/04/21/77-machine-learning-visualising-accuracy-and-error-in-a-classification-model-with-a-confusion-matrix/)
01) observed positive rate: proportion of observed cases that are +ve
02) predicted positive rate: proportion of predicted cases that are +ve
03) observed negative rate: proportion of observed cases that are -ve
04) predicted negative rate: proportion of predicted cases that are -ve
05) accuracy: proportion of predicted results that are correct
06) precision: proportion of predicted +ve that are correct
07) recall: proportion of true +ve correctly identified
08) f1: harmonic mean of precision and recall
09) sensitivity: Same as recall
10) specificity: Proportion of true -ve identified:
11) positive likelihood: increased probability of true +ve if test +ve
12) negative likelihood: reduced probability of true +ve if test -ve
13) false positive rate: proportion of false +ves in true -ve patients
14) false negative rate: proportion of false -ves in true +ve patients
15) true positive rate: Same as recall
16) true negative rate
17) positive predictive value: chance of true +ve if test +ve
18) negative predictive value: chance of true -ve if test -ve
'''
# --------------------------------------------------
# <<< import libraries >>>
# --------------------------------------------------
#import standard libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#import machine learning modules
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import StratifiedKFold
import sklearn.metrics #test new line
from sklearn.metrics import auc
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score #for info: https://builtin.com/data-science/roc-curves-auc
from sklearn.calibration import calibration_curve
from scipy.stats import pearsonr
from sklearn.preprocessing import PolynomialFeatures
from imblearn import under_sampling
from imblearn import over_sampling
from imblearn.over_sampling import SMOTENC # Use SMOTE for continuous data
#import neural net modules
#from keras.models import Sequential
#from keras.layers import Dense
import os
#import libraries for optimisation
import optuna
from tableone import TableOne, load_dataset
# --------------------------------------------------
# <<< set up folders if they dont exist >>>
# --------------------------------------------------
# Check whether the "Assets_produced_by_code folder exists in the current directory.
# If it doesn't exist, create it with the following directory structure:
# Assets_produced_by_code (top level)
# 01_pre_processing_assets<br>
# 02_HEA_assets
# 03_DNA_ML_assets
# 04_Carbon_emissions_assets
#subdirectory folder names for assets folder
preprocessing_assets_path = 'Assets_produced_by_code/01_pre_processing_assets'
hea_assets_path = 'Assets_produced_by_code/02_HEA_assets'
dna_assets_path = 'Assets_produced_by_code/03_DNA_ML_assets'
carbon_emissions_assets_path = 'Assets_produced_by_code/04_Carbon_emissions_assets'
#logic to check if Assets_produced_by_code folder exists, if not, create it with subdirs too
if os.path.exists('Assets_produced_by_code') == False:
os.makedirs('Assets_produced_by_code')
os.makedirs(preprocessing_assets_path)
os.makedirs(hea_assets_path)
os.makedirs(dna_assets_path)
os.makedirs(carbon_emissions_assets_path)
print("New directories have been created to store the outputs from the code.")
print("Existing 'Assets_produced_by_code' directory located.")
# --------------------------------------------------
# <<< setting paramers >>>
# --------------------------------------------------
#Parameters
test_fraction = 0.25
rand_state = 42 #global integer for use in all random_state keyword arguments
number_of_splits = 5 #(was 10) - used for k-fold cross validation stage
number_of_bins = 5 #used for learning plot in log-reg function
#polynomial expansion parameters
max_features = 5 #originally this was 20, reduce to 5 due to laptop limitations
#top X number of features associated with DNA's
#top_x = 5 replaced with user_params file input below
#identify the value for top X number of features associated with DNA's from the user parameters file
filename = "raw_data/user_and_data_parameters/user_and_data_params.xlsx"
top_x = pd.read_excel(filename, 'DNA_ML_parameters', index_col=None, usecols = "C", header = 1, nrows=0)
top_x = list(top_x)[0]
#Finely-tuned SMOTENC parameters
min_number_attendances = 150 #Used when varying balance of attend:DNA
#Neural Network Parameters - not yet used as NN not inc in the model yet.
num_epochs = 50
batch_size = 32
num_dims = 5
#set sample size for sample size vs accuracy chart. The dummy data has this set to 10. For large live data sets, it is recommended this is increased to 250
#Note, this would require you to have a data set with at least 250 data points present.
#sample_size_increment = 250 #original hard coded approach, replaced by user_parameter below
sample_size_increment = pd.read_excel(filename, 'DNA_ML_parameters', index_col=None, usecols = "C", header = 2, nrows=0)
sample_size_increment = list(sample_size_increment)[0]
print(sample_size_increment)
"""
#Code to create a new sub-directory within the current working directory, to store model outputs
directory_name = "Assets"
try:
#Create new directory
os.mkdir(directory_name)
print(f"Directory titled '{directory_name}' successfully created.")
except FileExistsError:
#print if directory already exists
print(f"A directory called '{directory_name}' already exists.")
"""
#16/6/23 variable to make adjusting max iterations easier
max_iterations = 1000
#subdirectory folder names for assets folder
preprocessing_assets_path = 'Assets_produced_by_code/01_pre_processing_assets'
hea_assets_path = 'Assets_produced_by_code/02_HEA_assets'
dna_assets_path = 'Assets_produced_by_code/03_DNA_ML_assets'
carbon_emissions_assets_path = 'Assets_produced_by_code/04_Carbon_emissions_assets'
#logic to check if Assets_produced_by_code folder exists, if not, create it with subdirs too
if os.path.exists('Assets_produced_by_code') == False:
os.makedirs('Assets_produced_by_code')
os.makedirs(preprocessing_assets_path)
os.makedirs(hea_assets_path)
os.makedirs(dna_assets_path)
os.makedirs(carbon_emissions_assets_path)
print("New directories have been created to store the outputs from the code.")
print("Existing 'Assets_produced_by_code' directory located.")
# --------------------------------------------------
# <<< Define functions >>>
# --------------------------------------------------
def standardise_data(X_train, X_test):
"""
Standardise data
We want all of out features to be on roughly the same scale, generally
leads to a better model, and allows us to more easily compare the
importance of different features.
One simple method is to scale all features 0-1 (by subtracting the minimum
value for each value, and dividing by the new remaining maximum value).
But a more common method used in many machine learning methods is
standardisation, where we use the mean and standard deviation of the training
set of data to normalise the data. We subtract the mean of the test set values,
and divide by the standard deviation of the training data. Note that the mean
and standard deviation of the training data are used to standardise the test
set data as well.
Here we will use sklearn's StandardScaler method. This method also copes with
problems we might otherwise have (such as if one feature has zero standard
deviation in the training set).
"""
# Initialise a new scaling object for normalising input data
sc = StandardScaler()
# Set up the scaler just on the training set
sc.fit(X_train)
# Apply the scaler to the training and test sets
train_std=sc.transform(X_train)
test_std=sc.transform(X_test)
return train_std, test_std
# --------------------------------------------------
def calculate_accuracy(observed, predicted):
# Converts list to NumPy arrays
if type(observed) == list:
observed = np.array(observed)
if type(predicted) == list:
predicted = np.array(predicted)
# Calculate accuracy scores
observed_positives = observed == 1
observed_negatives = observed == 0
predicted_positives = predicted == 1
predicted_negatives = predicted == 0
true_positives = (predicted_positives == 1) & (observed_positives == 1)
false_positives = (predicted_positives == 1) & (observed_positives == 0)
true_negatives = (predicted_negatives == 1) & (observed_negatives == 1)
false_negatives = (predicted_negatives == 1) & (observed_negatives == 0)
accuracy = np.mean(predicted == observed)
precision = (np.sum(true_positives) /
(np.sum(true_positives) + np.sum(false_positives)))
recall = np.sum(true_positives) / np.sum(observed_positives)
sensitivity = recall
f1 = 2 * ((precision * recall) / (precision + recall))
specificity = np.sum(true_negatives) / np.sum(observed_negatives)
positive_likelihood = sensitivity / (1 - specificity)
negative_likelihood = (1 - sensitivity) / specificity
false_positive_rate = 1 - specificity
false_negative_rate = 1 - sensitivity
true_positive_rate = sensitivity
true_negative_rate = specificity
positive_predictive_value = (np.sum(true_positives) /
np.sum(observed_positives))
negative_predictive_value = (np.sum(true_negatives) /
np.sum(observed_negatives))
# Create dictionary for results, and add results
results = dict()
results['observed_positive_rate'] = np.mean(observed_positives)
results['observed_negative_rate'] = np.mean(observed_negatives)
results['predicted_positive_rate'] = np.mean(predicted_positives)
results['predicted_negative_rate'] = np.mean(predicted_negatives)
results['accuracy'] = accuracy
results['precision'] = precision
results['recall'] = recall
results['f1'] = f1
results['sensitivity'] = sensitivity
results['specificity'] = specificity
results['positive_likelihood'] = positive_likelihood
results['negative_likelihood'] = negative_likelihood
results['false_positive_rate'] = false_positive_rate
results['false_negative_rate'] = false_negative_rate
results['true_positive_rate'] = true_positive_rate
results['true_negative_rate'] = true_negative_rate
results['positive_predictive_value'] = positive_predictive_value
results['negative_predictive_value'] = negative_predictive_value
return results
# --------------------------------------------------
'''
def get_values_for_learning_curve_log_reg(
test_fraction,
max_train_size,
X_np,
y_np,
rand_state):
"""
Function to derive the accuracy for incremental test sizes from 10, to
the maximum training size (whole data set) in increments of 10.
"""
#Loop through increasing training set sizes
# Set up list to collect results
results_training_size = []
results_accuracy = []
for train_size in range(250, max_train_size, 500): #previously max_training_size instead of max_train_size but not an input param, so changed to match? previously interval of 10, now 250 (was 500, 1000)
replicate_accuracy = []
for replicate in range(10):
# Split data into training and test
#added Shuffle = True
X_train, X_test, y_train, y_test = train_test_split(
X_np, y_np, test_size = test_fraction, shuffle=True, random_state = rand_state)
# Reduce training set size (use np random choice for random index values)
selection_index = np.random.choice(
max_train_size, train_size, replace=False) #previously max_training_size instead of max_train_size but not an input param, so changed to match?
X_train = X_train[selection_index]
y_train = y_train[selection_index]
# Standardise
X_train_std, X_test_std = standardise_data(X_train, X_test)
# Fit model
model = LogisticRegression(solver='lbfgs')
#print('X_train_std:')
#print(X_train_std)
#print('')
#print('y_train')
#print(y_train)
model.fit(X_train_std,y_train)
# Predict test set
y_pred_test = model.predict(X_test_std)
# Get accuracy and record results
accuracy = np.mean(y_pred_test == y_test)
replicate_accuracy.append(accuracy)
results_accuracy.append(np.mean(replicate_accuracy))
results_training_size.append(train_size)
return results_accuracy, results_training_size
'''
def get_values_for_learning_curve_log_reg(
test_fraction,
max_train_size,
X_np,
y_np,
rand_state,
sample_size_increment):
"""
Function to derive the accuracy for incremental test sizes from 10, to
the maximum training size (whole data set) in increments of 10.
"""
#Loop through increasing training set sizes
# Set up list to collect results
results_training_size = []
results_accuracy = []
for train_size in range(sample_size_increment, max_train_size, sample_size_increment): #previously max_training_size instead of max_train_size but not an input param, so changed to match? previously interval of 10, now 250 (was 500, 1000)
replicate_accuracy = []
for replicate in range(10):
# Split data into training and test
#added Shuffle = True
X_train, X_test, y_train, y_test = train_test_split(
X_np, y_np, test_size = test_fraction, shuffle=True, random_state = rand_state)
# Reduce training set size (use np random choice for random index values)
selection_index = np.random.choice(
max_train_size, train_size, replace=False) #previously max_training_size instead of max_train_size but not an input param, so changed to match?
X_train = X_train[selection_index]
y_train = y_train[selection_index]
# Standardise
X_train_std, X_test_std = standardise_data(X_train, X_test)
# Fit model
model = LogisticRegression(solver='lbfgs')
#print('X_train_std:')
#print(X_train_std)
#print('')
#print('y_train')
#print(y_train)
model.fit(X_train_std,y_train)
# Predict test set
y_pred_test = model.predict(X_test_std)
# Get accuracy and record results
accuracy = np.mean(y_pred_test == y_test)
replicate_accuracy.append(accuracy)
results_accuracy.append(np.mean(replicate_accuracy))
results_training_size.append(train_size)
return results_accuracy, results_training_size
# --------------------------------------------------
#required for training size chart to run. require min data set size of 250
def round_nearest_250(n):
number_of_250s = n // 250
nearest_250 = number_of_250s * 250
return nearest_250
# --------------------------------------------------
def plot_learning_curve(results_training_size, results_accuracy):
"""
Function to plot the learning curve based on outputs from the
get_values_for_learning_curve_log_reg function
"""
#Plot the learning curve, inc. moving average (mean of 5 points).
#Moving averages can help show trends when data is noisy.
#Calculate moving average (of last 5 points) with np.convolve
moving_average = np.convolve(results_accuracy, np.ones((5,))/5, mode='valid')
x_moving_average = results_training_size[2:-2] # Include offset to centre mean
plt.scatter(results_training_size, results_accuracy,
label='Accuracy')
plt.plot(x_moving_average, moving_average,
label='Moving average',
color='orange',
linewidth=3)
plt.xlabel('Training set size')
plt.ylabel('Test set accuracy')
plt.legend()
plt.title("Scatter plot of Training set size vs. Test set accuracy.")
plt.grid(True)
plt.figtext(0.5, 0.0001, "Interpretation: look for diminishing return on accuracy for increased sample size. Adjust sample size if limited computational power.", ha="center", va="baseline", fontsize=6)
plt.show()
return (moving_average, x_moving_average)
# --------------------------------------------------
#Round input int to nearest 10, default to 30 if int <30
#check lowest value in moving_average (from plot_learning_curve function) is 30
#check the max value in moving_average (from plot_learning curve function is sample size - 20)
#when running real data
def round_nearest_10(x, base=10):
if x <30:
return 30
else:
return (base * round(x/base)) - 20
# --------------------------------------------------
''' NEW ALTERNATIVE PASTED BELOW THIS ONE
def plot_learning_curve_with_sample_size_new(results_training_size, results_accuracy, sample_size):
"""
Function to plot the learning curve based on outputs from the
get_values_for_learning_curve_log_reg function
"""
#Plot the learning curve, inc. moving average (mean of 5 points).
#Moving averages can help show trends when data is noisy.
#Calculate moving average (of last 5 points) with np.convolve
moving_average = np.convolve(results_accuracy, np.ones((5,))/5, mode='valid')
x_moving_average = results_training_size[2:-2] # Include offset to centre mean
fig, ax = plt.subplots() #new line
#fig = plt.figure(figsize=(6,5)) #defines the dimensions of the figure (horizontal, vertical)
ax.scatter(results_training_size, results_accuracy,
label='Accuracy')
ax.plot(x_moving_average, moving_average,
label='Moving average',
color='orange',
linewidth=3)
index = x_moving_average.index(round_nearest_10(sample_size)-10)
sample_size_x_mov_avg = x_moving_average[index]
sample_size_mov_avg = moving_average[index]
ax.scatter(sample_size_x_mov_avg,sample_size_mov_avg, label="selected sample size", color="red", marker="x", s=200, linewidths=3)
ax.set_xlabel('Training set size')
ax.set_ylabel('Test set accuracy')
ax.set_title("Scatter plot of Training set size vs. Test set accuracy.")
ax.legend()
ax.grid(True)
ax.tick_params(labelsize = 14)
plt.figtext(0.5, 0.0001, "Interpretation: look for diminishing return on accuracy for increased sample size. Adjust sample size if limited computational power.", ha="center", va="baseline", fontsize=6)
# Set background color of Figure
fig.patch.set_facecolor('white')
# Set transparency of figure
fig.patch.set_alpha(1)
plt.savefig(f"{dna_assets_path}/chart001_FigSelectedSampleSizeAccuracy.png", bbox_inches='tight')
plt.show()
fig.tight_layout()
return(plt)
'''
'''
def plot_learning_curve_with_sample_size_new(results_training_size, results_accuracy, sample_size):
"""
Function to plot the learning curve based on outputs from the
get_values_for_learning_curve_log_reg function
"""
#Plot the learning curve, inc. moving average (mean of 5 points).
#Moving averages can help show trends when data is noisy.
#Calculate moving average (of last 5 points) with np.convolve
moving_average = np.convolve(results_accuracy, np.ones((5,))/5, mode='valid')
x_moving_average = results_training_size[2:-2] # Include offset to centre mean
fig, ax = plt.subplots() #new line
#fig = plt.figure(figsize=(6,5)) #defines the dimensions of the figure (horizontal, vertical)
ax.scatter(results_training_size, results_accuracy,
label='Accuracy')
ax.plot(x_moving_average, moving_average,
label='Moving average',
color='orange',
linewidth=3)
#index = x_moving_average.index(round_nearest_10(sample_size)-500)
#index = x_moving_average.index(results_training_size)
index = [results_training_size.index(item) for item in x_moving_average]
#sample_size_x_mov_avg = x_moving_average[index]
sample_size_x_mov_avg = [x_moving_average[num] for num in index[:-3]]
#sample_size_x_mov_avg = x_moving_average[index]
sample_size_mov_avg = [moving_average[num] for num in index[:-3]]
ax.scatter(sample_size_x_mov_avg,sample_size_mov_avg, label="selected sample size", color="red", marker="x", s=200, linewidths=3)
ax.set_xlabel('Training set size')
ax.set_ylabel('Test set accuracy')
ax.set_title("Scatter plot of Training set size vs. Test set accuracy.")
ax.legend()
ax.grid(True)
ax.tick_params(labelsize = 14)
plt.figtext(0.5, 0.0001, "Interpretation: look for diminishing return on accuracy for increased sample size. Adjust sample size if limited computational power.", ha="center", va="baseline", fontsize=6)
# Set background color of Figure
fig.patch.set_facecolor('white')
# Set transparency of figure
fig.patch.set_alpha(1)
plt.savefig(f"{dna_assets_path}/chart001_FigSelectedSampleSizeAccuracy.png", bbox_inches='tight')
plt.show()
fig.tight_layout()
return(plt)
'''
#revised function - needs replacing in above function section
def plot_learning_curve_with_sample_size_new(results_training_size, results_accuracy, sample_size):
"""
Function to plot the learning curve based on outputs from the
get_values_for_learning_curve_log_reg function
"""
#Plot the learning curve, inc. moving average (mean of 5 points).
#Moving averages can help show trends when data is noisy.
#Calculate moving average (of last 5 points) with np.convolve
moving_average = np.convolve(results_accuracy, np.ones((5,))/5, mode='valid')
x_moving_average = results_training_size[2:-2] # Include offset to centre mean
fig, ax = plt.subplots() #new line
#fig = plt.figure(figsize=(6,5)) #defines the dimensions of the figure (horizontal, vertical)
ax.scatter(results_training_size, results_accuracy,
label='Accuracy')
ax.plot(x_moving_average, moving_average,
label='Moving average',
color='orange',
linewidth=3)
#round down the given sample size to the nearest 250
rounded_sample_size = round_nearest_250(sample_size)
if rounded_sample_size not in range(sample_size, max_training_size, sample_size):
result = range(sample_size, max_training_size, 500)[-1]
else:
result = rounded_sample_size
#locate accuracy for the rounded sample size to visually display on chart as a X
accuracy_index_chosen_sample_size = results_training_size.index(result)
result_chosen_sample_size = results_accuracy[accuracy_index_chosen_sample_size]
ax.scatter(result,result_chosen_sample_size, label="selected sample size", color="red", marker="x", s=200, linewidths=3)
ax.set_xlabel('Training set size')
ax.set_ylabel('Test set accuracy')
ax.set_title("Scatter plot of Training set size vs. Test set accuracy.")
ax.legend()
ax.grid(True)
ax.tick_params(labelsize = 14)
plt.figtext(0.5, 0.0001, "Interpretation: look for diminishing return on accuracy for increased sample size. Adjust sample size if limited computational power.", ha="center", va="baseline", fontsize=6)
# Set background color of Figure
fig.patch.set_facecolor('white')
# Set transparency of figure
fig.patch.set_alpha(1)
plt.savefig(f"{dna_assets_path}/chart001_FigSelectedSampleSizeAccuracy.png", bbox_inches='tight')
plt.show()
fig.tight_layout()
return(plt)
# --------------------------------------------------
def plot_learning_curve_with_sample_size(results_training_size, results_accuracy, sample_size):
"""
Function to plot the learning curve based on outputs from the
get_values_for_learning_curve_log_reg function
"""
#Plot the learning curve, inc. moving average (mean of 5 points).
#Moving averages can help show trends when data is noisy.
#Calculate moving average (of last 5 points) with np.convolve
moving_average = np.convolve(results_accuracy, np.ones((5,))/5, mode='valid')
x_moving_average = results_training_size[2:-2] # Include offset to centre mean
fig, ax = plt.subplots() #new line
fig = plt.figure(figsize=(6,5)) #defines the dimensions of the figure (horizontal, vertical)
plt.scatter(results_training_size, results_accuracy,
label='Accuracy')
plt.plot(x_moving_average, moving_average,
label='Moving average',
color='orange',
linewidth=3)
index = x_moving_average.index(round_nearest_10(sample_size))
sample_size_x_mov_avg = x_moving_average[index]
sample_size_mov_avg = moving_average[index]
plt.scatter(sample_size_x_mov_avg,sample_size_mov_avg, label="selected sample size", color="red", marker="x", s=200, linewidths=3)
plt.xlabel('Training set size')
plt.ylabel('Test set accuracy')
plt.title("Scatter plot of Training set size vs. Test set accuracy.")
plt.legend()
plt.grid(True)
plt.tick_params(labelsize = 14)
plt.figtext(0.5, 0.0001, "Interpretation: look for diminishing return on accuracy for increased sample size. Adjust sample size if limited computational power.", ha="center", va="baseline", fontsize=6)
plt.show()
fig.tight_layout()
return(fig)
# --------------------------------------------------
def add_performance_metrics_to_summary(summary_df, dict_metrics_summary, dict_metrics, model_variant_name):
"""
Function to add the identified model performance metrics of precision,
recall, f1 and specificity, to the provided summary_df.
Use this function after each model, and subsequent methods to boost predictive
power, is run, to add the performance metrics of each model variant to the
growing summary df.
"""
list_of_metrics_measures = []
list_of_metrics_labels = []
for num in range(len(dict_metrics_summary)):
list_of_metrics_measures.append(dict_metrics[dict_metrics_summary[num]])
list_of_metrics_labels.append(dict_metrics_summary[num])
data_tuples = list(zip(list_of_metrics_labels,list_of_metrics_measures))
temp_df = pd.DataFrame(data_tuples, columns=['performance_metrics',model_variant_name])
temp_df.set_index('performance_metrics', inplace=True)
new_df = pd.merge(summary_df, temp_df, how="left", left_index=True, right_index=True)
return new_df
# --------------------------------------------------
#test cell to check incorporating coeff lists to average
def run_log_reg_within_k_fold_and_output_accuracy_scores(
num_splits,
random_state,
X,
X_np,
y_np,
num_bins,
model_name,
):
"""
New function to use, replacing previous function of same name.
This revision has less repeated lines of code and also outputs both
test set and training set mean performance measures as 2 separate dictionaries
from which the summary of performance will later be created for this baseline
log reg
"""
"""
The following code:
- sets up lists to hold the results of each k-fold split
- Sets up the splits using sklearn's StratifiedKFold method
- Trains a logistic regression model, and tests its fit, for each k-fold split
- Add each k-fold training / test accuracy to the lists
- generates the observed and predicted probabilities for each split - later used for ROC curve
"""
# Set up lists to hold results for each k-fold run
training_acc_results = []
test_acc_results = []
#extended accuracy lists
list_all_performance_metrics = [
"observed_positive_rate",
"observed_negative_rate",
"predicted_positive_rate",
"predicted_negative_rate",
"accuracy",
"precision",
"recall",
"f1",
"sensitivity",
"specificity",
"positive_likelihood",
"negative_likelihood",
"false_positive_rate",
"false_negative_rate",
"true_positive_rate",
"true_negative_rate",
"positive_predictive_value",
"negative_predictive_value"
]
#create a nested dictionary containing all performance metrics for both train and test
#as keys e.g. ["train"]["f1"]. All values are place holders at this point (empty lists)
list_outer_dict_levels = ["train", "test"]
dict_train_test_metrics = {level: {metric:list() for metric in list_all_performance_metrics} for level in list_outer_dict_levels}
# Set up splits
number_of_splits = num_splits #was 10
#skf = StratifiedKFold(n_splits = number_of_splits) #original logistic regression stratified k-fold split code
skf = StratifiedKFold(n_splits = number_of_splits, shuffle=True, random_state = random_state) #from Random Forest example, should ensure repeatable splits
skf.get_n_splits(X_np, y_np)
# Set up results lists (to get results from each run)
#These will be used to create the reliability plot
results_model_probability = []
results_fraction_positive = []
#Define number of bins - used for reliability plot
number_of_bins = num_bins
# Set up lists for observed and predicted - used for the ROC Curve
observed = []
predicted_proba = []
predicted = [] #CHECK why is this list present, looks empty?
#set up list to capture the coefficient values for each fold in the kfold step - to later take average to give model coefficients
coeff_list_of_lists = []
#set up list to store the auc for each split
replicate_auc = []
counter = 0
# Loop through the k-fold splits
for train_index, test_index in skf.split(X_np, y_np):
counter +=1
# Get X and Y train/test
X_train, X_test = X_np[train_index], X_np[test_index]
y_train, y_test = y_np[train_index], y_np[test_index]
# Standardise X data
X_train_std, X_test_std = standardise_data(X_train, X_test)
# Set up and fit model
model = LogisticRegression(solver='lbfgs')
model.fit(X_train_std,y_train)
#get coefficients for this fold
"""
Weights with higher negative numbers mean that that feature correlates with
reduced chance of DNA (outcome variable, y).
Weights with higher positive numbers mean that that feature correlates with
increased chance of DNA (outcome variable, y).
Those weights with values closer to zero (either positive or negative) have
less influence in the model.
We access model weights via the model coef_ attribute.
A model may predict >1 outcome label, in which case we have weights for each label.
This model only predicts a single label (DNA or not), so the weights are found
in the first element ([0]) of the coef_ attribute.
"""
co_eff = model.coef_[0]
coeff_list_of_lists.append(co_eff)
# Predict training and test set labels, using standardised data
y_pred_train = model.predict(X_train_std)
y_pred_test = model.predict(X_test_std)
# Get test set proabilities - reliability curve
y_calibrate_probabilities = model.predict_proba(X_test_std)[:,1]
#Get ROC AUC for this split, append to list of AUC's
auc = roc_auc_score(y_test, y_calibrate_probabilities)
replicate_auc.append(auc)
# Get calibration curve (use quantile to make sure all bins exist) - reliability curve
fraction_pos, model_prob = calibration_curve(
y_test, y_calibrate_probabilities,
n_bins=number_of_bins,
strategy='quantile')
# record run results - reliability curve
results_model_probability.append(model_prob)
results_fraction_positive.append(fraction_pos)
#loop to update nested dict
dict_of_splits = {"train": [y_train, y_pred_train], "test": [y_test, y_pred_test]}
temp_dict = {}
for level in list_outer_dict_levels:
temp_dict[level] = calculate_accuracy(dict_of_splits[level][0], dict_of_splits[level][1])
#append performance metric to the dictionary of performance values for
#each split (train / test), taken from the temp_dict created by the
#calculate_accuracy function
for level in list_outer_dict_levels:
for metric in list_all_performance_metrics:
dict_train_test_metrics[level][metric].append(temp_dict[level][metric])
# Calculate accuracy of training and test sets
accuracy_train = np.mean(y_pred_train == y_train)
accuracy_test = np.mean(y_pred_test == y_test)
# Add accuracy to lists
training_acc_results.append(accuracy_train)
test_acc_results.append(accuracy_test)
#ROC code:
# Get predicted probabilities
y_probs = model.predict_proba(X_test_std)[:,1] #check that 1 relates to attended status
y_class = model.predict(X_test_std) #predict the actual class label
observed.append(y_test)
predicted_proba.append(y_probs)
# Print accuracy
accuracy = np.mean(y_class == y_test)
print (f'Run {counter}, accuracy: {accuracy:0.3f}')
# Transfer results to dataframe
results_auc = pd.DataFrame(columns=[model_name]) #previously had "auc_" prefix in f-string NB was columns=['model_name])
mean_auc_across_all_splits = np.mean(replicate_auc)
results_auc.loc[0] = mean_auc_across_all_splits
#Calculate the mean of the various accuracy scores created in previous step:
dict_mean_train_test_metrics = {level: {f"mean_{metric}":list() for metric in list_all_performance_metrics} for level in list_outer_dict_levels}
for level in list_outer_dict_levels:
for metric in list_all_performance_metrics:
dict_mean_train_test_metrics[level][f"mean_{metric}"] = np.mean(dict_train_test_metrics[level][metric])
dict_mean_test_performance = dict_mean_train_test_metrics["test"]
dict_mean_train_performance = dict_mean_train_test_metrics["train"]
#average the coefficient values produced for each fold, to get to a single array of average coefficients.
#these are in the same order as the columns in X
average_coefficients = np.mean(coeff_list_of_lists, 0)
co_eff_df, co_eff_df_reduced_chance_dna, co_eff_df_higher_chance_dna = create_coefficients_df(average_coefficients, X)
return(dict_mean_test_performance,
dict_mean_train_performance,
observed,
predicted_proba,
results_model_probability,
results_fraction_positive,
skf,
results_auc,
co_eff_df,
co_eff_df_reduced_chance_dna,
co_eff_df_higher_chance_dna
)
# --------------------------------------------------
#function to produce the ROC Area Under the Curve (AUC)
def get_roc(num_splits,
observed,
predicted_proba,
results_model_probability,
results_fraction_positive
):
#Scikit-Learn’s ROC method will automatically test the rate of true postive
#rate (tpr) and false positive rate (fpr) at different thresholds of
#classification. It will return tpr, fpr for each threshold tested. We also
#use Scikit-Learn’s method for caluclating the area under the curve.
"""
#Reciever Operator Characteristic (ROC) Curve
The ROC curve allows us to better understand the trade-off between
sensitivity (the ability to detect positives of a certain class) and
specificity (the ability to detect negatives of a certain class).
The area under the ROC curve is also often used to compare different
models: a higher Area Under Curve (AUC) is frequently the sign of a
better model.
ROC curve is created by plotting the true positive rate (TPR) against
the false positive rate (FPR) at various threshold settings.
The true-positive rate is also known as sensitivity or recall.
The false-positive rate can be calculated as (1 − specificity).
"""
# Set up lists for results
k_fold_fpr = [] # false positive rate
k_fold_tpr = [] # true positive rate
k_fold_thresholds = [] # threshold applied
k_fold_auc = [] # area under curve
# Loop through k fold predictions and get ROC results
for i in range(number_of_splits):
# Get fpr, tpr and thresholds foir each k-fold from scikit-learn's ROC method
fpr, tpr, thresholds = roc_curve(observed[i], predicted_proba[i])
# Use scikit-learn's method for calulcating auc
roc_auc = auc(fpr, tpr)
# Store results
k_fold_fpr.append(fpr)
k_fold_tpr.append(tpr)
k_fold_thresholds.append(thresholds)
k_fold_auc.append(roc_auc)
# Print auc result
print (f'Run {i} AUC {roc_auc:0.4f}')
# Show mean area under curve
mean_auc = np.mean(k_fold_auc)
sd_auc = np.std(k_fold_auc)
print (f'\nMean AUC: {mean_auc:0.4f}')
print (f'SD AUC: {sd_auc:0.4f}')
#Plot ROCs
fig = plt.figure(figsize=(6,6))
ax1 = fig.add_subplot()
for i in range(5):
ax1.plot(k_fold_fpr[i], k_fold_tpr[i], color='orange')
ax1.plot([0, 1], [0, 1], color='darkblue', linestyle='--')
ax1.set_xlabel('False Positive Rate')
ax1.set_ylabel('True Positive Rate')
ax1.set_title('Receiver Operator Characteristic Curve')
text = f'Mean AUC: {mean_auc:.3f}'
ax1.text(0.64,0.07, text,
bbox=dict(facecolor='white', edgecolor='black'))
plt.grid(True)
plt.show()
#Reliability curve
# Convert results to DataFrame to enable plotting reliability curve
results_model_probability = pd.DataFrame(results_model_probability)
results_fraction_positive = pd.DataFrame(results_fraction_positive)
# Add individual k-fold runs
for run in range(number_of_splits):
plt.plot(results_model_probability.loc[run],
results_fraction_positive.loc[run],
linestyle='--',
linewidth=0.75,
color='0.5')
# Add mean
plt.plot(results_model_probability.mean(axis=0),
results_fraction_positive.mean(axis=0),
linestyle='-',
linewidth=2,
color='darkorange',