-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctions.py
More file actions
3790 lines (3042 loc) · 182 KB
/
Functions.py
File metadata and controls
3790 lines (3042 loc) · 182 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
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
### IMPORTS ###################################################################
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from copy import deepcopy
from itertools import product
from sklearn.preprocessing import StandardScaler
import warnings
import pickle
import os
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.utils.data import Dataset
import torch.optim as optim
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from torch.nn.utils import clip_grad_norm_
# to use gpu if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
### HELPER FUNCTIONS/CLASSES ##################################################
def save_dictionary(data, file_path):
"""Saves a dictionary as a pickle file.
Args:
data (dict): The dictionary to be saved.
file_path (str): The path to the folder where the dictionary will be saved.
"""
full_path = os.path.join(file_path, 'hyperparameter_grid.pickle')
with open(full_path, 'wb') as handle:
pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL)
def load_dictionary(file_path):
"""Loads a dictionary from a pickle file.
Args:
file_path (str): The path to the file from which the dictionary will be loaded.
Returns:
dict: The loaded dictionary, or None if an error occurs.
"""
full_path = os.path.join(file_path, 'hyperparameter_grid.pickle')
if not os.path.exists(full_path):
print(f"Error: File not found: {full_path}")
return None
with open(full_path, 'rb') as handle:
try:
data = pickle.load(handle)
return data
except Exception as e:
print(f"Error loading dictionary: {e}")
return None
def round_threshold(num, threshold=1000):
"""Takes a float and rounds it to the nearest integer if it is above a
certain threshold. Otherwise rounds the float to 3 decimal places."""
if num >= threshold:
return int(num)
else:
return round(num, 3)
# errors as defined in the essay
# could be used in model training, currently only used for diagnostics
class MeanAbsoluteLogError(nn.Module):
def __init__(self):
super(MeanAbsoluteLogError, self).__init__()
def forward(self, preds, actuals):
# convert negative preds to 1 so that the log will be 0
# smallest true OCL is 16 (training set) 7000 (test set) so penalty will be severe as a test set metric
preds_copy = preds.copy()
preds_copy[preds_copy < 1] = 1
if torch.is_tensor(preds_copy):
return torch.mean(torch.abs(torch.log(preds_copy) - torch.log(actuals)))
else:
return np.mean(np.abs(np.log(preds_copy) - np.log(actuals)))
class MeanSquaredLogError(nn.Module):
def __init__(self):
super(MeanSquaredLogError, self).__init__()
def forward(self, preds, actuals):
# convert negative preds to 1 so that the log will be 0
# smallest true OCL is 16 (training set) 7000 (test set) so penalty will be severe as a test set metric
preds_copy = preds.copy()
preds_copy[preds_copy < 1] = 1
if torch.is_tensor(preds_copy):
return torch.mean(torch.square(torch.log(preds_copy) - torch.log(actuals)))
else:
return np.mean(np.square(np.log(preds_copy) - np.log(actuals)))
class MSLE_with_penalty(nn.Module):
'''Testing a new loss function. Works the same as the regular MSE but adds
a penalty for negative OCL predictions. Should only be used with models
that predict claim_size or log_m.'''
def __init__(self, pen_weight=1, pen_type='constant'):
super(MSLE_with_penalty, self).__init__()
self.pen_weight = pen_weight
self.pen_type = pen_type # 'constant', 'linear' or 'log'
def forward(self, raw_preds, targets, lower_bounds, preds):
# lower bounds refers to the cumulative payments to date (ultimate claim size cannot be less than this)
# raw_preds are in terms of the model's output (e.g. log_m), preds are transformed to always be in terms of ultimate claim size
msle = torch.nn.MSELoss()(raw_preds, targets) # raw preds and targets are already in terms of log_m
if self.pen_type == 'constant':
penalty = self.pen_weight * torch.sum(lower_bounds > preds)
elif self.pen_type == 'linear':
penalty = self.pen_weight * torch.mean(torch.maximum(torch.zeros_like(preds), lower_bounds - preds))
elif self.pen_type == 'log':
penalty = self.pen_weight * torch.mean(torch.maximum(torch.zeros_like(preds), torch.log(lower_bounds) - torch.log(preds)))
else:
raise ValueError("pen_type must be 'constant', 'linear' or 'log'")
return msle + penalty
def __repr__(self):
return f"MSLE_with_penalty(pen_weight={self.pen_weight}, pen_type={self.pen_type})"
def __str__(self):
return self.__repr__()
def initialise_weights(model):
"""
Initialize weights of a PyTorch model, including handling RNNs, LSTMs, GRUs, Linear,
BatchNorm, and LayerNorm layers.
- RNN/LSTM/GRU weights: Kaiming Normal
- Linear weights: Kaiming Normal
- BatchNorm/LayerNorm weights: Gamma (scale) = 1.0, Beta (shift) = 0.0
"""
for name, param in model.named_parameters():
# Handle RNNs, LSTMs, and GRUs
if 'weight_ih' in name: # Input-to-hidden weights
nn.init.kaiming_normal_(param, mode='fan_in', nonlinearity='relu')
elif 'weight_hh' in name: # Hidden-to-hidden weights
nn.init.kaiming_normal_(param, mode='fan_in', nonlinearity='relu')
elif 'bias' in name: # Bias terms
nn.init.zeros_(param)
# Handle all modules explicitly
for module in model.modules():
if isinstance(module, nn.Linear): # Linear layers
nn.init.kaiming_normal_(module.weight, mode='fan_in', nonlinearity='relu')
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)): # BatchNorm
if module.weight is not None: # Gamma
nn.init.ones_(module.weight)
if module.bias is not None: # Beta
nn.init.zeros_(module.bias)
elif isinstance(module, nn.LayerNorm): # LayerNorm
if module.weight is not None: # Gamma
nn.init.ones_(module.weight)
if module.bias is not None: # Beta
nn.init.zeros_(module.bias)
elif isinstance(module, nn.LSTM):
for name, param in module.named_parameters():
if 'bias' in name:
# LSTM: [input, forget, cell, output]
bias_size = param.size(0)
gate_size = bias_size // 4
with torch.no_grad():
param[gate_size:2*gate_size].fill_(1.0) # forget gate
elif isinstance(module, nn.GRU):
for name, param in module.named_parameters():
if 'bias' in name:
# GRU: [reset, update, new]
bias_size = param.size(0)
gate_size = bias_size // 3
with torch.no_grad():
param[gate_size:2*gate_size].fill_(1.0) # update gate (or choose as needed)
def create_grid(target_cols, criterions, types, output_layers,
nOuts, epochss, nHiddens, nLayerss, patiences, batch_sizes,
optimisers, lrs, nonlinearitys, dropouts, normalisations,
include_incurredss, include_covariatess, transform_inputss, model_types):
'''
Inputs: lists of hyperparameter values
Output: a list of dictionaries to be used in the cross_validate function'''
hyperparameter_grid = []
for params in product(target_cols, criterions, types,
output_layers, nOuts, epochss, nHiddens, nLayerss,
patiences, batch_sizes, optimisers, lrs, nonlinearitys,
dropouts, normalisations, include_incurredss,
include_covariatess, transform_inputss, model_types):
hyperparameter_grid.append({
'target_col': params[0],
'criterion': params[1],
'type': params[2],
'output_layer': params[3],
'nOut': params[4],
'epochs': params[5],
'nHidden': params[6],
'nLayers': params[7],
'patience': params[8],
'batch_size': params[9],
'optimiser': params[10],
'lr': params[11],
'nonlinearity': params[12],
'dropout': params[13],
'normalisation': params[14],
'include_incurreds': params[15],
'include_covariates': params[16],
'transform_inputs': params[17],
'model_type': params[18]
})
return hyperparameter_grid
median_colours = {'LSTM+': "#5D3EF8",
'LSTM': "#0DA1EB",
'FNN+': "#07BB43",
'FNN': "#F147D5",
'Case Estimates': "#D4B206",
'Actuals': "#2BC5AB"}
edge_colours = {'LSTM+': '#332288',
'LSTM': "#3B8BB3",
'FNN+': '#117733',
'FNN': '#AA4499',
'Case Estimates': "#B19A27"}
fill_colours = {'LSTM+': "#B1A2FC",
'LSTM': '#88CCEE',
'FNN+': "#B3F7CA",
'FNN': "#F8B9EE",
'Case Estimates': "#F1E296"}
def get_median_colour(model_name):
if model_name in median_colours.keys():
return median_colours[model_name]
return "#FF0000"
def get_edge_colour(model_name):
if model_name in edge_colours.keys():
return edge_colours[model_name]
return "#FF0000"
def get_fill_colour(model_name):
if model_name in fill_colours.keys():
return fill_colours[model_name]
return "#FF0000"
def box_plot(data, positions, model_name=None, alpha=1, widths=0.7, showfliers=False):
data = pd.DataFrame(data)
# dataframe boxplot needed over matplotlib or seaborn to handle missing values correctly !!!
bp = data.boxplot(backend='matplotlib', return_type='dict', grid=False, positions=positions, widths=widths, patch_artist=True, showfliers=showfliers)
plt.setp(bp['medians'], color=get_median_colour(model_name), linewidth=2)
for element in ['boxes', 'whiskers', 'fliers', 'means', 'caps']:
plt.setp(bp[element], color=get_edge_colour(model_name), alpha=alpha)
for patch in bp['boxes']:
patch.set(facecolor=get_fill_colour(model_name), alpha=alpha)
return bp
def bias_correction_factor(preds, targets):
''' assumes preds and targets are both on actual scale (i.e. not log scale) '''
# non-parametric
bias = np.mean(np.exp(np.log(targets) - np.log(preds)))
# log-normal assumption
#bias = np.exp(0.5 * np.var(np.log(targets) - np.log(preds)))
print(f'Bias correction factor: {bias:.3f}')
return bias
def get_model_params_num(model, trainable_only=False):
"""
Calculates the total number of parameters in a PyTorch model.
Args:
model (torch.nn.Module): The PyTorch model.
trainable_only (bool, optional): If True, only count trainable parameters. Defaults to False.
Returns:
int: The total number of parameters.
"""
if trainable_only:
return sum(p.numel() for p in model.parameters() if p.requires_grad)
return sum(p.numel() for p in model.parameters())
### MODEL CLASSES #############################################################
class ClaimsDataset(Dataset):
""" Based on Arkie's ClaimsDataset
Notes:
- dataloader has to iterate from 0:len(dataset)
- all sequences are padded to a minimum length of 70
"""
def __init__(self, target_col, index_path, set_path, include_incurreds=True,
include_covariates=False, transform_inputs=False, model_type='RNN', scaler=None):
self.target_col = target_col # string referring to name of the target column (i.e. 'claim_size', 'log_claim_size', 'log_m', 'true_ocl' or 'log_true_ocl')
self.index = pd.read_csv(index_path)
self.set = pd.read_csv(set_path)
self.include_incurreds = include_incurreds # boolean whether to use case estimate data or not
self.include_covariates = include_covariates # boolean whether to include covariate data or not
self.transform_inputs = transform_inputs # boolean whether to transform inputs or not
self.model_type = model_type # string referring to the type of model being used (either 'RNN' (includes LSTM and GRU) or 'FNN')
self.scaler = scaler # dictionary of scalers to be applied to the data
# creating new column for target output (so that any scalings applied to the target column are not applied to the original data)
self.index['target'] = self.index[self.target_col]
self.index['incurred_copy'] = self.index['latest_incurred']
self.index['pred_time_copy'] = self.index['pred_time']
self.index['acc_quarter_copy'] = self.index['acc_quarter']
if self.transform_inputs:
# log transform some inputs
self.set['paid'] = np.log(self.set['paid'] + 1)
self.set['dev_time'] = np.log(self.set['dev_time'] + 1)
if self.include_incurreds:
self.set['ocl'] = np.log(self.set['ocl'] + 1)
if self.model_type == 'FNN':
self.index['mean_payments'] = np.log(self.index['mean_payments'] + 1)
self.index['vco_payments'] = np.log(self.index['vco_payments'] + 1)
self.index['max_payment'] = np.log(self.index['max_payment'] + 1)
if self.include_incurreds:
self.index['total_revisions'] = np.log(self.index['total_revisions'] + 1)
self.index['incurred_copy'] = np.log(self.index['incurred_copy'] + 1)
# standardise inputs and output
if self.scaler is None:
# learn scalings and apply them
self.scaler = {'target': StandardScaler(),
'paid': StandardScaler(),
'ocl': StandardScaler(),
'dev_time': StandardScaler(),
'cal_time': StandardScaler(),
# can't scale the two below because it will interfere with analysis by time
'pred_time_copy': StandardScaler(),
'acc_quarter_copy': StandardScaler(),
'num_payments': StandardScaler(),
'mean_payments': StandardScaler(),
'vco_payments': StandardScaler(),
'max_payment': StandardScaler(),
'num_revisions': StandardScaler(),
'mean_revisions': StandardScaler(),
'max_revision': StandardScaler(),
'total_revisions': StandardScaler(),
'prop_upward_revisions': StandardScaler(),
'incurred_copy': StandardScaler()}
for key in self.scaler.keys():
if key in self.set.columns:
self.scaler[key].fit(self.set[key].values.reshape(-1, 1))
self.set[key] = self.scaler[key].transform(self.set[key].values.reshape(-1, 1))
elif key in self.index.columns:
self.scaler[key].fit(self.index[key].values.reshape(-1, 1))
self.index[key] = self.scaler[key].transform(self.index[key].values.reshape(-1, 1))
#else:
# warnings.warn(f'{key} not found in either set or index dataframes')
else:
# apply scaling
for key in self.scaler.keys():
if key in self.set.columns:
self.set[key] = self.scaler[key].transform(self.set[key].values.reshape(-1, 1))
elif key in self.index.columns:
self.index[key] = self.scaler[key].transform(self.index[key].values.reshape(-1, 1))
#else:
# warnings.warn(f'{key} not found in either set or index dataframes')
# removing latest 4/8 accident quarters from datasets to see what plots would look like without them
# this is NOT intended to be a permanent change, just for visualisation purposes
# this code appears at the end of the initialisation so that it does not interfere with the scaling above
# self.index = self.index[self.index['acc_quarter'] <= 36]
# self.set = self.set[self.set['index'].isin(self.index['index'])]
def __len__(self):
return len(self.index)
def __getitem__(self, index):
# Retrieves time series data, as well as summary info
# index runs from [0, __len__(self)]
# real_index instead refers to indexes in the csv file
real_index = self.index['index'][index]
df = self.set[(self.set['index']==real_index)]
print(f'Getting item {index}, real index {real_index}, df shape {df.shape}')
if df.shape[0] == 0:
raise ValueError(f'No data found for index {index} real index {real_index}')
claim_no = df['claim_no'].mean()
# Get relevant info from index.csv file
target = self.index['target'][index]
claim_size = self.index['claim_size'][index]
latest_incurred = self.index['latest_incurred'][index]
true_ocl = self.index['true_ocl'][index]
dev_quarter = self.index['dev_quarter'][index]
acc_quarter_copy = self.index['acc_quarter_copy'][index]
pred_time_copy = self.index['pred_time_copy'][index]
if self.include_covariates:
legal_rep = self.index['Legal Representation'][index]
injury_severity = self.index['Injury Severity'][index]
claimant_age = self.index['Age of Claimant'][index]
# Setting up the data to be input into an RNN model
if self.model_type == 'RNN':
nrows = df[(df['dev_time']!=0)\
| (df['cal_time']!=0)\
| (df['paid']!=0)\
| (df['ocl']!=0)].shape[0]
if self.include_incurreds:
databox = df[['dev_time', 'cal_time', 'paid', 'ocl']].copy()
else:
databox = df[['dev_time','cal_time','paid']].copy()
databox = torch.tensor(databox.values)
# Return padded data
if self.include_covariates:
return (F.pad(databox.float(), (0,0,0,70-nrows)), # 70 is arbitrarily hard-coded, increase if you run into errors with mismatching dimensions
target, claim_size, latest_incurred, true_ocl, real_index,
claim_no, pred_time_copy, acc_quarter_copy, nrows, legal_rep, injury_severity, claimant_age)
else:
return (F.pad(databox.float(), (0,0,0,70-nrows)),
target, claim_size, latest_incurred, true_ocl, real_index,
claim_no, pred_time_copy, acc_quarter_copy, nrows)
# Setting up the data to be input into an FNN model
elif self.model_type == 'FNN':
num_payments = self.index['num_payments'][index]
mean_payments = self.index['mean_payments'][index]
vco_payments = self.index['vco_payments'][index]
max_payment = self.index['max_payment'][index]
# finding case estimate summary info
if self.include_incurreds:
num_revisions = self.index['num_revisions'][index]
mean_revisions = self.index['mean_revisions'][index]
max_revision = self.index['max_revision'][index]
total_revisions = self.index['total_revisions'][index]
prop_upward_revisions = self.index['prop_upward_revisions'][index]
incurred_copy = self.index['incurred_copy'][index]
if self.include_incurreds and self.include_covariates:
return (pred_time_copy, dev_quarter, acc_quarter_copy, num_payments, mean_payments, vco_payments, max_payment,
num_revisions, mean_revisions, max_revision, total_revisions, prop_upward_revisions,
legal_rep, injury_severity, claimant_age,
target, claim_size, latest_incurred, true_ocl, real_index,
claim_no, incurred_copy)
elif self.include_incurreds and not self.include_covariates:
return (pred_time_copy, dev_quarter, acc_quarter_copy, num_payments, mean_payments, vco_payments, max_payment,
num_revisions, mean_revisions, max_revision, total_revisions, prop_upward_revisions,
target, claim_size, latest_incurred, true_ocl, real_index,
claim_no, incurred_copy)
elif not self.include_incurreds and self.include_covariates:
return (pred_time_copy, dev_quarter, acc_quarter_copy, num_payments, mean_payments, vco_payments, max_payment,
legal_rep, injury_severity, claimant_age,
target, claim_size, latest_incurred, true_ocl, real_index,
claim_no)
else:
return (pred_time_copy, dev_quarter, acc_quarter_copy, num_payments, mean_payments, vco_payments, max_payment,
target, claim_size, latest_incurred, true_ocl, real_index,
claim_no)
else:
raise ValueError("model_type must be 'RNN' or 'FNN'")
class ClaimsRNN(nn.Module):
"""
Can use vanilla RNN, LSTM and GRU
Can change this to experiement with different architectures/hyperparameters
"""
def __init__(self, nHidden, nLayers, nOut, type='RNN',
nonlinearity='relu', output_layer='linear', dropout=0.0,
normalisation=True, include_incurreds=True, include_covariates=False):
super(ClaimsRNN, self).__init__()
self.nHidden = nHidden # number of hidden units
self.nLayers = nLayers # number of layers
self.type = type # either 'RNN', 'LSTM', or 'GRU'
self.nonlinearity = nonlinearity # either 'relu' or 'tanh'
# nonLinearity only used in vanilla RNN
self.output_layer = output_layer # either 'linear' or 'exponential'
self.dropout = dropout # float between 0 and 1
self.include_incurreds = include_incurreds # needs to match ClaimsDataset
self.relu = nn.ReLU() # used for feed-forward hidden layer, should change this so different activation functions can be specified
self.include_covariates = include_covariates
self.normalisation = normalisation # boolean for whether to use batch and layer normalisation
# nFeatures is the number of features to be input into the RNN layer
self.nFeatures = 3 + self.include_incurreds # 4 features with ocl, 3 without
if self.include_covariates:
self.embedding_dim = 2
else:
self.embedding_dim = 0
self.nstatic = 2 + self.include_covariates * (1 + 2 * self.embedding_dim) # 2 guaranteed inputs (pred_time, acc_quarter) + legal rep + 2 covariate embeddings
self.dropout_layer = nn.Dropout(self.dropout)
if self.normalisation:
self.rnn_layers = nn.ModuleList()
self.layer_norms_rnn = nn.ModuleList()
for i in range(nLayers):
input_size = self.nFeatures if i == 0 else self.nHidden
if type == 'RNN':
self.rnn_layers.append(nn.RNN(input_size, nHidden, 1,
batch_first=True, nonlinearity=nonlinearity))
elif type == 'LSTM':
self.rnn_layers.append(nn.LSTM(input_size, nHidden, 1,
batch_first=True))
elif type == 'GRU':
self.rnn_layers.append(nn.GRU(input_size, nHidden, 1,
batch_first=True))
else:
raise ValueError("type must be 'RNN', 'LSTM' or 'GRU'")
self.layer_norms_rnn.append(nn.LayerNorm(nHidden))
self.layer_norm2 = nn.LayerNorm(nHidden)
self.batch_norm2 = nn.BatchNorm1d(self.nstatic)
self.batch_norm3 = nn.BatchNorm1d(self.nHidden // 2)
else:
if type == 'RNN':
self.rnn = nn.RNN(self.nFeatures, nHidden, nLayers,
batch_first=True, nonlinearity=nonlinearity,
dropout=dropout)
elif type == 'LSTM':
self.rnn = nn.LSTM(self.nFeatures, nHidden, nLayers,
batch_first=True, dropout=dropout) # device = device? should I add this?
elif type == 'GRU':
self.rnn = nn.GRU(self.nFeatures, nHidden, nLayers,
batch_first=True, dropout=dropout)
else:
raise ValueError("type must be 'RNN', 'LSTM' or 'GRU'")
if self.include_covariates:
self.embedding_sev = nn.Embedding(6, self.embedding_dim) # 6 possible injury severities, output 2 dimensions
self.embedding_age = nn.Embedding(5, self.embedding_dim) # 5 possible ages, output 2 dimensions
self.fc3 = nn.Linear(self.nHidden + self.nstatic, self.nHidden // 2)
self.fc4 = nn.Linear(self.nHidden // 2, nOut)
def forward(self, x):
# x[0] will be the packed datapoints, x[1:] will be the static covariates
if self.normalisation:
out = x[0]
for i, rnn in enumerate(self.rnn_layers):
out, ht = rnn(out) # RNN output
if i < self.nLayers - 1:
out, nrows = pad_packed_sequence(out, batch_first=True)
out = self.layer_norms_rnn[i](out)
out = self.dropout_layer(out)
out = pack_padded_sequence(out, nrows, batch_first=True, enforce_sorted=False)
else:
out, ht = self.rnn(x[0])
if self.type == 'LSTM':
ht = ht[0]
out = ht[-1,:,:]
if self.normalisation:
out = self.layer_norm2(out)
if self.include_covariates:
sev_embed = self.embedding_sev(x[4].long())
age_embed = self.embedding_age(x[5].long())
static_out = torch.cat((x[1], x[2], x[3], sev_embed[:, -1, :], age_embed[:, -1, :]), 1)
else:
static_out = torch.cat((x[1], x[2]), 1)
if self.normalisation:
static_out = self.batch_norm2(static_out)
out = torch.cat((out, static_out), 1)
out = self.fc3(out)
if self.normalisation:
out = self.batch_norm3(out)
out = self.relu(out)
out = self.dropout_layer(out)
out = self.fc4(out)
if self.output_layer == 'exponential':
out = torch.exp(out)
elif self.output_layer == 'softplus':
out = F.softplus(out)
return out
class ClaimsFNN(nn.Module):
"""
Feed-Forward Neural Network to be used as a benchmark model
"""
def __init__(self, nLayers=2, nHidden=50, dropout = 0.2,
final_activation='exponential', normalisation=True,
include_incurreds=True, include_covariates=True):
"""
Initialises the Feedforward Neural Network.
Args:
p: Number of features in the input dataset.
nLayers: Number of hidden layers in the network.
nHidden: Number of neurons in each hidden layer.
dropout: Dropout rate for regularization.
final_activation: Output layer activation function. 'exp' for exponential, 'linear' for linear.
normalisation: Whether to normalise inputs or not
"""
super(ClaimsFNN, self).__init__()
self.include_covariates = include_covariates
if self.include_covariates:
self.embedding_dim = 2
self.embedding_sev = nn.Embedding(6, self.embedding_dim) # 6 possible injury severities, output 2 dimensions
self.embedding_age = nn.Embedding(5, self.embedding_dim) # 5 possible ages, output 2 dimensions
# 3 variables for transaction times, 4 for payments, 6 for revisions, 1 raw covariate, 2 covariate embeddings
self.num_features = 7 + 6 * include_incurreds + include_covariates * (1 + 2 * self.embedding_dim)
self.final_activation = final_activation
self.normalisation = normalisation
if self.normalisation:
layers = [nn.Linear(self.num_features, nHidden), nn.BatchNorm1d(nHidden), nn.ReLU(), nn.Dropout(dropout)]
for _ in range(nLayers - 1):
layers.append(nn.Linear(nHidden, nHidden))
layers.append(nn.BatchNorm1d(nHidden))
layers.append(nn.ReLU())
layers.append(nn.Dropout(dropout))
else:
layers = [nn.Linear(self.num_features, nHidden), nn.ReLU(), nn.Dropout(dropout)]
for _ in range(nLayers - 1):
layers.append(nn.Linear(nHidden, nHidden))
layers.append(nn.ReLU())
layers.append(nn.Dropout(dropout)) # Add dropout after each activation
layers.append(nn.Linear(nHidden, 1))
self.nn_output_layer = nn.Sequential(*layers)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Calculate the predicted outputs for the distributions.
Args:
x: the input features (shape: (n, p))
Returns:
the predicted outputs (shape: (n,))
"""
if self.include_covariates:
sev_embed = self.embedding_sev(x[:, -2].long())
age_embed = self.embedding_age(x[:, -1].long())
out = torch.cat((x[:, :-2], sev_embed, age_embed), 1)
else:
out = x
if self.final_activation == 'exponential':
out = torch.exp(self.nn_output_layer(out).squeeze(-1))
elif self.final_activation == 'softplus':
out = F.softplus(self.nn_output_layer(out).squeeze(-1))
elif self.final_activation == 'linear':
out = self.nn_output_layer(out).squeeze(-1)
else:
raise ValueError(f"Unsupported final activation function: {self.final_activation}")
assert out.shape == torch.Size([x.shape[0]])
return out
### TRAINING/TESTING FUNCTIONS ################################################
def train_network(model, train_data, hp_comb, verbose=True,
val_data=None, cv_loss_list=None, cv_vsCE_list=None,
cv_weighted_vsCE_claimsize_list=None,
cv_weighted_vsCE_ocl_list=None, cv_uie_list=None,
epoch_graphs=False):
"""
Args:
model: the model to train
train_data: ClaimsDataset object containing training data
hp_comb: dictionary of hyperparameters along with their values
verbose: whether to print written outputs and progress to console
val_data: ClaimsDataset object containing validation data,
enables early stopping
cv_loss_list/cv_vsCE_list/cv_uie_list: lists to be passed to keep
track of between-model stats during cross-validation
"""
if val_data is not None:
train_loss_list = []
train_weighted_vsCE_ocl_list = []
train_agg_clmsize_percent_error_model = []
val_loss_list = []
val_vsCE_list = []
val_weighted_vsCE_claimsize_list = []
val_weighted_vsCE_ocl_list = []
val_uie_list = []
val_agg_clmsize_percent_error_model = []
best_val_loss = np.inf
best_val_vsCE = 0
best_val_weighted_vsCE_claimsize = 0
best_val_weighted_vsCE_ocl = 0
best_val_uie = np.inf
best_weights = None
patience_counter = 0
# Data loader
trainloader = torch.utils.data.DataLoader(dataset=train_data,
batch_size=hp_comb['batch_size'],
shuffle=True, drop_last=False,
num_workers=4, pin_memory=True)
# Creation of optimiser
if hp_comb['optimiser'] == 'Adam':
optimiser = optim.Adam(model.parameters(), lr=hp_comb['lr'])
elif hp_comb['optimiser'] == 'AdamW':
optimiser = optim.AdamW(model.parameters(), lr=hp_comb['lr'])
else:
raise ValueError("optimiser must be 'Adam' or 'AdamW'. Otherwise, add new optimiser to the function.")
# Train the model
for epoch in range(hp_comb['epochs']):
#print('new epoch')
total_loss = 0
total_datapoints = 0
total_vsCE = 0
total_weighted_vsCE_claimsize = 0
total_weighted_vsCE_ocl = 0
total_uie = 0
total_ultimates = 0
total_ocls = 0
total_preds = 0
total_incurreds = 0
for batch in trainloader:
#print('new batch')
if hp_comb['model_type'] == 'RNN':
# extract batch data
if hp_comb['include_covariates']:
(datapoints, targets, claim_sizes, latest_incurreds, true_ocls,
indexes, claim_nos, pred_time_copys, acc_quarter_copys, nrowss, legal_reps,
injury_severities, claimant_ages) = batch
legal_reps = legal_reps.unsqueeze(1).to(device).float()
injury_severities = injury_severities.unsqueeze(1).to(device).float()
claimant_ages = claimant_ages.unsqueeze(1).to(device).float()
else:
(datapoints, targets, claim_sizes, latest_incurreds,
true_ocls, indexes, claim_nos, pred_time_copys, acc_quarter_copys, nrowss) = batch
datapoints = datapoints.to(device).float()
targets = targets.to(device).float()
claim_sizes = claim_sizes.to(device).float()
latest_incurreds = latest_incurreds.to(device).float()
true_ocls = true_ocls.to(device).float()
pred_time_copys = pred_time_copys.unsqueeze(1).to(device).float()
acc_quarter_copys = acc_quarter_copys.unsqueeze(1).to(device).float()
packed = pack_padded_sequence(datapoints, nrowss,
enforce_sorted=False,
batch_first=True)
if hp_comb['include_covariates']:
packed_extra = (packed, pred_time_copys, acc_quarter_copys, legal_reps,
injury_severities, claimant_ages)
else:
packed_extra = (packed, pred_time_copys, acc_quarter_copys)
elif hp_comb['model_type'] == 'FNN':
if hp_comb['include_incurreds'] and hp_comb['include_covariates']:
(pred_time_copys, dev_quarters, acc_quarter_copys, num_paymentss, mean_paymentss,
vco_paymentss, max_payments, num_revisionss, mean_revisionss, max_revisions,
total_revisionss, prop_upward_revisionss, legal_reps,
injury_severities, claimant_ages, targets, claim_sizes,
latest_incurreds, true_ocls, indexes, claim_nos, incurred_copys) = batch
pred_time_copys = pred_time_copys.to(device).float()
dev_quarters = dev_quarters.to(device).float()
acc_quarter_copys = acc_quarter_copys.to(device).float()
num_paymentss = num_paymentss.to(device).float()
mean_paymentss = mean_paymentss.to(device).float()
vco_paymentss = vco_paymentss.to(device).float()
max_payments = max_payments.to(device).float()
num_revisionss = num_revisionss.to(device).float()
mean_revisionss = mean_revisionss.to(device).float()
max_revisions = max_revisions.to(device).float()
total_revisionss = total_revisionss.to(device).float()
prop_upward_revisionss = prop_upward_revisionss.to(device).float()
legal_reps = legal_reps.to(device).float()
injury_severities = injury_severities.to(device).float()
claimant_ages = claimant_ages.to(device).float()
targets = targets.to(device).float()
claim_sizes = claim_sizes.to(device).float()
latest_incurreds = latest_incurreds.to(device).float()
true_ocls = true_ocls.to(device).float()
incurred_copys = incurred_copys.to(device).float()
packed_extra = torch.stack((pred_time_copys, dev_quarters, acc_quarter_copys, num_paymentss, mean_paymentss,
vco_paymentss, max_payments, incurred_copys, num_revisionss, mean_revisionss, max_revisions,
total_revisionss, prop_upward_revisionss, legal_reps,
injury_severities, claimant_ages), dim=1).to(device)
elif hp_comb['include_incurreds'] and not hp_comb['include_covariates']:
(pred_time_copys, dev_quarters, acc_quarter_copys, num_paymentss, mean_paymentss,
vco_paymentss, max_payments, num_revisionss, mean_revisionss, max_revisions,
total_revisionss, prop_upward_revisionss, targets, claim_sizes,
latest_incurreds, true_ocls, indexes, claim_nos, incurred_copys) = batch
pred_time_copys = pred_time_copys.to(device).float()
dev_quarters = dev_quarters.to(device).float()
acc_quarter_copys = acc_quarter_copys.to(device).float()
num_paymentss = num_paymentss.to(device).float()
mean_paymentss = mean_paymentss.to(device).float()
vco_paymentss = vco_paymentss.to(device).float()
max_payments = max_payments.to(device).float()
num_revisionss = num_revisionss.to(device).float()
mean_revisionss = mean_revisionss.to(device).float()
max_revisions = max_revisions.to(device).float()
total_revisionss = total_revisionss.to(device).float()
prop_upward_revisionss = prop_upward_revisionss.to(device).float()
targets = targets.to(device).float()
claim_sizes = claim_sizes.to(device).float()
latest_incurreds = latest_incurreds.to(device).float()
true_ocls = true_ocls.to(device).float()
incurred_copys = incurred_copys.to(device).float()
packed_extra = torch.stack((pred_time_copys, dev_quarters, acc_quarter_copys, num_paymentss, mean_paymentss,
vco_paymentss, max_payments, incurred_copys, num_revisionss, mean_revisionss, max_revisions,
total_revisionss, prop_upward_revisionss), dim=1).to(device)
elif not hp_comb['include_incurreds'] and hp_comb['include_covariates']:
(pred_time_copys, dev_quarters, acc_quarter_copys, num_paymentss, mean_paymentss,
vco_paymentss, max_payments, legal_reps, injury_severities,
claimant_ages, targets, claim_sizes, latest_incurreds,
true_ocls, indexes, claim_nos) = batch
pred_time_copys = pred_time_copys.to(device).float()
dev_quarters = dev_quarters.to(device).float()
acc_quarter_copys = acc_quarter_copys.to(device).float()
num_paymentss = num_paymentss.to(device).float()
mean_paymentss = mean_paymentss.to(device).float()
vco_paymentss = vco_paymentss.to(device).float()
max_payments = max_payments.to(device).float()
legal_reps = legal_reps.to(device).float()
injury_severities = injury_severities.to(device).float()
claimant_ages = claimant_ages.to(device).float()
targets = targets.to(device).float()
claim_sizes = claim_sizes.to(device).float()
latest_incurreds = latest_incurreds.to(device).float()
true_ocls = true_ocls.to(device).float()
packed_extra = torch.stack((pred_time_copys, dev_quarters, acc_quarter_copys, num_paymentss, mean_paymentss,
vco_paymentss, max_payments, legal_reps, injury_severities,
claimant_ages), dim=1).to(device)
else:
(pred_time_copys, dev_quarters, acc_quarter_copys, num_paymentss, mean_paymentss,
vco_paymentss, max_payments, targets, claim_sizes, latest_incurreds,
true_ocls, indexes, claim_nos) = batch
pred_time_copys = pred_time_copys.to(device).float()
dev_quarters = dev_quarters.to(device).float()
acc_quarter_copys = acc_quarter_copys.to(device).float()
num_paymentss = num_paymentss.to(device).float()
mean_paymentss = mean_paymentss.to(device).float()
vco_paymentss = vco_paymentss.to(device).float()
max_payments = max_payments.to(device).float()
targets = targets.to(device).float()
claim_sizes = claim_sizes.to(device).float()
latest_incurreds = latest_incurreds.to(device).float()
true_ocls = true_ocls.to(device).float()
packed_extra = torch.stack((pred_time_copys, dev_quarters, acc_quarter_copys,
num_paymentss, mean_paymentss,
vco_paymentss, max_payments), dim=1).to(device)
else:
raise ValueError("model_type must be 'RNN' or 'FNN'")
raw_preds = model(packed_extra)
raw_preds = raw_preds.reshape(raw_preds.shape[0])
# undoing any scaling
if train_data.scaler is not None:
target_mean = train_data.scaler['target'].mean_[0]
target_std = train_data.scaler['target'].scale_[0]
preds = raw_preds * target_std + target_mean
ultimates = targets * target_std + target_mean
else:
preds = raw_preds
ultimates = targets
# converting raw preds and targets to be in terms of ultimate claim size
if train_data.target_col == 'claim_size':
preds = preds
ultimates = ultimates
elif train_data.target_col == 'log_claim_size':
preds = torch.exp(preds)
ultimates = torch.exp(ultimates)
elif train_data.target_col == 'log_m':
preds = torch.exp(preds) * latest_incurreds
ultimates = torch.exp(ultimates) * latest_incurreds
elif train_data.target_col == 'true_ocl':
preds = preds + claim_sizes - true_ocls
ultimates = ultimates + claim_sizes - true_ocls
elif train_data.target_col == 'log_true_ocl':
preds = torch.exp(preds) + claim_sizes - true_ocls
ultimates = torch.exp(ultimates) + claim_sizes - true_ocls
else:
ValueError('Invalid target, must be "claim_size", "log_claim_size", "log_m", "true_ocl" or "log_true_ocl"')
# Loss and gradient descent