Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1745 lines (1408 loc) · 64.5 KB
/
Copy pathapp.py
File metadata and controls
1745 lines (1408 loc) · 64.5 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
import os
import json
import joblib
import dill
import uuid
from tqdm import trange
import time
import shutil
from datetime import datetime
from flask import Flask, request, jsonify, send_file, send_from_directory, url_for
from werkzeug.utils import secure_filename
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.compose import make_column_selector, ColumnTransformer
from scipy.stats import chisquare
import statistics
from collections import defaultdict
from flask_cors import CORS
from env_loader import load_env_file
# Import models and utilities
from model import MTLR
from icp import ConformalSurvDist, CSDiPOT
from icp.scorer import QuantileRegressionNC, SurvivalPredictionNC
from utils import set_seed, save_params
from utils.util_survival import survival_data_split, make_time_bins, xcal_from_hist
from SurvivalEVAL import QuantileRegEvaluator
from CondCalEvaluation import wsc_xcal
load_env_file()
def _safe_int(value, fallback):
try:
return int(value)
except (TypeError, ValueError):
return fallback
DEFAULT_CORS = "http://localhost:5174,http://localhost:5173"
API_HOST = os.getenv("API_HOST", "localhost")
API_PORT = _safe_int(os.getenv("API_PORT"), 5000)
API_URL = os.getenv("API_URL", f"http://{API_HOST}:{API_PORT}")
CORS_ORIGINS = [
origin.strip()
for origin in os.getenv("CORS_ORIGINS", DEFAULT_CORS).split(",")
if origin.strip()
]
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')
app.config['MODEL_FOLDER'] = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'trained_models')
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # 100MB max file size
app.config['API_HOST'] = API_HOST
app.config['API_PORT'] = API_PORT
app.config['API_URL'] = API_URL
CORS(app, origins=CORS_ORIGINS, supports_credentials=True)
# Create necessary directories
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs(app.config['MODEL_FOLDER'], exist_ok=True)
ci = []
mae_hinge = []
mae_po = []
ibs = []
km_cal = []
xcal_stats = []
wsc_xcal_stats = []
dcal_chisquare = []
dcal_p_value_stat = []
train_times = []
infer_times = []
dcal_hists = []
n_features = 0
class Args:
"""Configuration object for model training"""
def __init__(self, config):
# Model parameters
self.model = config.get('model', 'MTLR')
self.neurons = config.get('neurons', [64, 64])
self.norm = config.get('norm', True)
self.activation = config.get('activation', 'ReLU')
self.dropout = config.get('dropout', 0.3)
self.n_quantiles = config.get('n_quantiles', 10)
self.interpolate = config.get('interpolate', 'Pchip')
self.decensor_method = config.get('decensor_method', 'sampling') # <-- Difference between sampling and margin? ---------------- Changed from margin to sampling ------
self.post_process = config.get('post_process', 'CSD')
self.selected_features = config.get('selected_features', None)
# Training parameters
self.lr = config.get('lr', 1e-3)
self.batch_size = config.get('batch_size', 256)
self.n_epochs = config.get('n_epochs', 1000)
self.weight_decay = config.get('weight_decay', 1e-4)
self.early_stop = config.get('early_stop', True)
self.mono_method = config.get('mono_method', 'bootstrap') # <-- Changed to bootstrap and Pchip worked
self.use_train = config.get('use_train', True)
self.n_sample = config.get('n_sample', 1000)
self.seed = config.get('seed', 0)
self.n_exp = config.get('n_exp', 10)
# Device
self.device = "cuda:0" if torch.cuda.is_available() else "cpu"
# Verbose and other flags
self.verbose = config.get('verbose', True)
def prepare_data(dataset_path, selected_features=None, args=None):
"""
Load and preprocess the dataset for survival analysis.
Expected CSV format:
- First column: Time/Label (survival time or duration)
- Second column: Censored (0 or u=event occurred/uncensored, 1 or c=censored)
- Remaining columns: Features for prediction
"""
# Load dataset
data = pd.read_csv(dataset_path)
# Standardize column names for survival
columns = data.columns.tolist()
if len(columns) < 3:
raise ValueError(f"Dataset must have at least 3 columns. Found {len(columns)} columns.")
data = data.rename(columns={columns[0]: 'time', columns[1]: 'censored'})
data['event'] = ((data['censored'] == 0) | (data['censored'] == 'u')).astype(int)
# Remove invalid zero-time rows (Time = 0 and Event = 1/occurred). Not plausible
invalid_mask = (data["time"] <= 0)
data = data[~invalid_mask]
data = data.drop(columns='censored')
# Filter selected features
feature_columns = [col for col in data.columns if col not in ['time', 'event']]
# Define survival columns
SURVIVAL_COLS = {'time', 'event', 'censored'}
if selected_features:
# Removes survival columns silently
selected_features = [f for f in selected_features if f not in SURVIVAL_COLS]
# Check for missing features now
missing_features = [f for f in selected_features if f not in feature_columns]
if missing_features:
raise ValueError(f"Features not found: {missing_features}")
feature_columns = selected_features
data = data[feature_columns + ['time', 'event']]
# Identify columns
numeric_cols = data.select_dtypes(include=['int64', 'float64']).columns.tolist()
numeric_cols = [c for c in numeric_cols if c not in ['time', 'event']]
ordinal_cols = [c for c in numeric_cols if data[c].dtype == 'int64'] # Discrete/ordinal
continuous_cols = [c for c in numeric_cols if data[c].dtype == 'float64'] # Continuous
cat_cols = [c for c in data.columns if c not in numeric_cols + ['time', 'event']]
binary_cols = [c for c in cat_cols if data[c].nunique() == 2]
nominal_cols = [c for c in cat_cols if data[c].nunique() > 2]
# Pipelines
continuous_pipeline = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler())
])
ordinal_pipeline = Pipeline([
("impute", SimpleImputer(strategy="most_frequent"))
])
binary_pipeline = Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("encode", OneHotEncoder(drop="if_binary", sparse_output=False))
])
nominal_pipeline = Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("encode", OneHotEncoder(handle_unknown="ignore", sparse_output=False))
])
# ColumnTransformer for features only
encoder = ColumnTransformer(
transformers=[
("cont", continuous_pipeline, continuous_cols),
("ord", ordinal_pipeline, ordinal_cols),
("bin", binary_pipeline, binary_cols),
("nom", nominal_pipeline, nominal_cols)
],
remainder='passthrough', # <--- Appends time and event columns after transformation of the rest of the columns
verbose_feature_names_out=False
)
encoder.set_output(transform='pandas')
# Train / val / test split
if args.early_stop:
pct_train = 0.8
pct_val = 0.1
pct_test = 0.1
else:
pct_train = 0.9
pct_val = 0.0
pct_test = 0.1
return encoder, pct_train, pct_val, pct_test, data
def print_performance(
path: str = None,
**kwargs
) -> dict: # Changed return type
"""
Print performance using mean and std. And also save to file.
Returns dictionary with calculated metrics.
"""
prf = ""
metrics_dict = {} # Store calculated metrics
for k, v in kwargs.items():
if len(v) == 0 or None in v:
continue
if isinstance(v, list):
mean = statistics.mean(v)
std = statistics.stdev(v) # sample standard deviation (n-1)
prf += f"{k}: {mean:.3f} +/- {std:.3f}\n"
# Store in dict for JSON response
metrics_dict[k] = {
'mean': round(mean, 3),
'std': round(std, 3),
}
else:
prf += f"{k}: {v:.3f}\n"
metrics_dict[k] = round(v, 3)
print(prf)
if path is not None:
prf_dict = {k: v for k, v in kwargs.items()}
with open(f"{path}/performance.pkl", 'wb') as f:
pickle.dump(prf_dict, f)
with open(f"{path}/performance.txt", 'w') as f:
f.write(prf)
return metrics_dict # Return the dictionary
def train_mtlr_model(dataset_path, selected_features, args, i, return_predictions=False):
"""Train MTLR model with conformal prediction"""
# ADD THIS AT THE START OF THE FUNCTION
global ci, mae_hinge, mae_po, ibs, km_cal, xcal_stats, wsc_xcal_stats
global dcal_chisquare, dcal_p_value_stat, train_times, infer_times, dcal_hists, n_features
# ✅ START TIMING
# t0 = time.time()
device = torch.device(args.device)
# One unified seed per trial
seed = args.seed + i
# Set ALL RNG controls
set_seed(seed, device) # this should set torch + cuda + python.random
# t1 = time.time()
# print(f"[Exp {i+1}] Setup & seeding: {t1-t0:.3f}s")
# Prepare data AFTER seeding
enc_df, pct_train, pct_val, pct_test, data = prepare_data(
dataset_path, selected_features, args
)
# t2 = time.time()
# print(f"[Exp {i+1}] prepare_data(): {t2-t1:.3f}s")
# path = save_params(config)
# Train/val/test split seeded identically
data_train, data_val, data_test = survival_data_split(
data,
stratify_colname='both',
frac_train=pct_train,
frac_val=pct_val,
frac_test=pct_test,
random_state=seed
)
# t3 = time.time()
# print(f"[Exp {i+1}] Data split: {t3-t2:.3f}s")
# standardize the data
data_train = enc_df.fit_transform(data_train).astype('float32')
data_val = enc_df.transform(data_val).astype('float32') if not data_val.empty else data_val
data_test = enc_df.transform(data_test).astype('float32')
# get the labels for evaluation
t_train, e_train = data_train["time"].values, data_train["event"].values
t_val, e_val = data_val["time"].values, data_val["event"].values if not data_val.empty else None
x_test = data_test.drop(['time', 'event'], axis=1).values
t_test, e_test = data_test["time"].values, data_test["event"].values
t_train_val = np.concatenate((t_train, t_val)) if not data_val.empty else t_train
e_train_val = np.concatenate((e_train, e_val)) if not data_val.empty else e_train
discrete_bins = make_time_bins(t_train, event=e_train)
n_features = data_train.shape[1] - 2 # Exlucde time and event
# Build MTLR model
model = MTLR(
n_features=n_features,
time_bins=discrete_bins,
hidden_size=args.neurons,
norm=args.norm,
activation=args.activation,
dropout=args.dropout
)
# Setup conformal prediction
if args.post_process == "CSD":
nc_model = QuantileRegressionNC(model, args)
icp = ConformalSurvDist(
nc_model, condition=None,
decensor_method=args.decensor_method,
n_quantiles=args.n_quantiles
)
elif args.post_process == "CSD-iPOT":
nc_model = SurvivalPredictionNC(model, args)
icp = CSDiPOT(
nc_model,
decensor_method=args.decensor_method,
n_percentile=args.n_quantiles
)
# Fit the ICP using the proper training set, and using valset for early stopping
start_time = datetime.now()
icp.fit(data_train, data_val)
# Calibrate the ICP using the calibration set
if args.use_train:
data_val = pd.concat([data_train, data_val], ignore_index=True)
icp.calibrate(data_val)
mid_time = datetime.now()
# Produce predictions for the test set
quan_levels, quan_preds = icp.predict(x_test)
end_time = datetime.now()
# Produce predictions for test set
quan_levels, quan_preds = icp.predict(x_test)
# NEW: Calculate additional statistics for each prediction
individual_predictions = None
if return_predictions:
# For each sample, calculate additional metrics
median_preds = []
mean_preds = []
prob_at_actual_time = []
median_preds, mean_preds, prob_at_actual_time = summarize_prediction_stats(
quan_levels, quan_preds, t_test
)
individual_predictions = {
'fold': i,
'test_indices': data_test.index.tolist(),
'actual_times': t_test.tolist(),
'actual_events': e_test.tolist(),
'quantile_levels': quan_levels.tolist(),
'quantile_predictions': quan_preds.tolist(),
'median_predictions': median_preds,
'mean_predictions': mean_preds,
'prob_at_actual_time': prob_at_actual_time,
'features': x_test.tolist()
}
train_time = (mid_time - start_time).total_seconds()
infer_time = (end_time - mid_time).total_seconds()
evaler = QuantileRegEvaluator(
quan_preds, quan_levels, t_test, e_test,
t_train_val, e_train_val,
predict_time_method="Median", interpolation=args.interpolate
)
c_index = float(evaler.concordance(ties="All")[0])
ibs_score = float(evaler.integrated_brier_score(num_points=10))
hinge_abs = float(evaler.mae(method='Hinge', verbose=False, weighted=True))
po_abs = float(evaler.mae(method='Pseudo_obs', verbose=False, weighted=True))
km_cal_score = float(evaler.km_calibration())
_ , dcal_hist = evaler.d_calibration()
xcal_score = float(xcal_from_hist(dcal_hist))
pred_probs = evaler.predict_probability_from_curve(evaler.event_times)
dcal_chisquare_stat, dcal_p_value = chisquare(dcal_hist)
if data.shape[0] >= 1000:
wsc_xcal_score = float(wsc_xcal(x_test, e_test, pred_probs, random_state=seed))
else:
wsc_xcal_score = 0 # not enough data to compute the WSC
ci.append(c_index)
ibs.append(ibs_score)
mae_hinge.append(hinge_abs)
mae_po.append(po_abs)
km_cal.append(km_cal_score)
xcal_stats.append(xcal_score)
dcal_chisquare.append(float(dcal_chisquare_stat))
dcal_p_value_stat.append(float(dcal_p_value))
wsc_xcal_stats.append(wsc_xcal_score)
dcal_hists.append(torch.tensor(dcal_hist))
train_times.append(train_time)
infer_times.append(infer_time)
return icp, enc_df, individual_predictions
@app.route('/health', methods=['GET'])
def health_check():
"""Health check endpoint"""
return jsonify({
'status': 'healthy',
'timestamp': datetime.now().isoformat(),
'device': 'cuda' if torch.cuda.is_available() else 'cpu'
})
@app.route("/models/<model_id>/<filename>")
def serve_model_file(model_id, filename):
folder = os.path.join(app.config['MODEL_FOLDER'], model_id)
if not os.path.exists(os.path.join(folder, filename)):
return {"error": "File not found"}, 404
return send_from_directory(folder, filename)
@app.route("/models/<model_id>/cv_predictions", methods=['GET'])
def get_cv_predictions_file(model_id):
"""Serve the per-fold aggregated cv_predictions.json for a model."""
folder = os.path.join(app.config['MODEL_FOLDER'], model_id)
target = os.path.join(folder, "cv_predictions.json")
if not os.path.exists(target):
return jsonify({"error": "cv_predictions.json not found"}), 404
return send_from_directory(folder, "cv_predictions.json")
@app.route("/models/<model_id>/full_predictions", methods=['GET'])
def get_full_predictions_file(model_id):
"""Serve the full_predictions.json (all identifiers) for a model."""
folder = os.path.join(app.config['MODEL_FOLDER'], model_id)
target = os.path.join(folder, "full_predictions.json")
if not os.path.exists(target):
return jsonify({"error": "full_predictions.json not found"}), 404
return send_from_directory(folder, "full_predictions.json")
@app.route('/train', methods=['POST'])
def train_model():
"""
Train MTLR model with feature selection
Expected CSV format:
- First column: Time/Label (survival time or duration)
- Second column: Censored (0=event occurred/uncensored, 1=censored)
- Remaining columns: Features for prediction
Feature Selection Logic:
- selected_features='all' → Use ALL features from dataset
- selected_features=['feat1', 'feat2'] → Use ONLY these specific features
- selected_features=None (or not provided) → No features selected (will use all by default)
Example JSON request:
{
"dataset_path": "/path/to/data.csv",
"selected_features": "all", // or ["Height", "Weight"] or null
"parameters": {"neurons": [64, 64], "dropout": 0.1}
"return_cv_predictions": true # NEW: Return individual predictions
}
"""
# Reset metrics before training
global ci, mae_hinge, mae_po, ibs, km_cal, xcal_stats, wsc_xcal_stats
global dcal_chisquare, dcal_p_value_stat, train_times, infer_times, dcal_hists, n_features
ci.clear()
mae_hinge.clear()
mae_po.clear()
ibs.clear()
km_cal.clear()
xcal_stats.clear()
wsc_xcal_stats.clear()
dcal_chisquare.clear()
dcal_p_value_stat.clear()
train_times.clear()
infer_times.clear()
dcal_hists.clear()
n_features = 0
model_dir = None
try:
# Handle dataset - either as file upload or JSON path
dataset_path = None
# Dataset MUST be a File upload (multipart/form-data)
if 'dataset' in request.files:
file = request.files['dataset']
if file.filename == '':
return jsonify({'error': 'No dataset file selected'}), 400
if not file.filename.endswith('.csv'):
return jsonify({'error': 'Dataset file must be a CSV'}), 400
# Save uploaded file
filename = secure_filename(file.filename)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
dataset_filename = f"{timestamp}_{filename}"
dataset_path = os.path.join(app.config['UPLOAD_FOLDER'], dataset_filename)
file.save(dataset_path)
else:
return jsonify({'error': 'No dataset provided. Please upload file'}), 400
# Parse user-selected configuration
parameters = json.loads(request.form.get('parameters', '{}'))
# Load dataset
data = pd.read_csv(dataset_path)
# selected features
selected_features = data.columns[2:].tolist()
# Train on all features by default
selected_features_for_training = None
config = {'selected_features': selected_features}
# Merge parameters into config
config.update(parameters)
# Pass configurations + features into Args
args = Args(config)
# safety: ensure n_exp is an int >= 1
n_exp = max(1, int(getattr(args, 'n_exp', 1)))
# Create model ID
now = datetime.now()
model_timestamp = now.strftime("%Y%m%d_%H%M%S")
model_timestamp_date = now.isoformat() # e.g., "2025-11-09T15:45:30+00:00"
suffix = uuid.uuid4().hex[:6] # 6-character random ID
model_id = f"mtlr_{model_timestamp}_{suffix}"
# Create model dir
model_dir = os.path.join(app.config['MODEL_FOLDER'], model_id)
os.makedirs(model_dir, exist_ok=True)
# NEW: Collect predictions across all folds
all_fold_predictions = []
# Training Loop
train_start = time.time()
for i in trange(n_exp, disable=not args.verbose, desc='Experiment'):
icp, encoder, indiv_preds = train_mtlr_model(
dataset_path, selected_features_for_training, args, i, return_predictions=True)
# Collect predictions
if indiv_preds is not None:
all_fold_predictions.append(indiv_preds)
train_end = time.time()
train_duration = train_end - train_start
# -------------------------------
# Aggregate individual predictions
# -------------------------------
aggregated_predictions = aggregate_cv_predictions(all_fold_predictions)
full_dataset_predictions = generate_full_dataset_predictions(
icp, encoder, dataset_path, selected_features_for_training, args
)
# ----------------------------
# Save artifacts
# ----------------------------
# Save model config (only model architecture params, NOT selected_features)
model_config = {
"model_type": "MTLR",
"n_features": icp.nc_function.model.in_features,
"time_bins": icp.nc_function.model.time_bins.tolist(),
"neurons": args.neurons,
"dropout": args.dropout,
"activation": args.activation,
"norm": args.norm,
}
config_path = os.path.join(model_dir, "model_config.json")
with open(config_path, 'w') as f:
json.dump(model_config, f, indent=2)
# Save training metadata separately (includes selected_features)
training_metadata = {
"selected_features": selected_features, # Store as 'all' for training
"dataset_path": dataset_path,
"n_experiments": n_exp,
"timestamp": model_timestamp_date
}
metadata_path = os.path.join(model_dir, "training_metadata.json")
with open(metadata_path, 'w') as f:
json.dump(training_metadata, f, indent=2)
# Save encoder pipeline
encoder_path = os.path.join(model_dir, "encoder.joblib")
joblib.dump(encoder, encoder_path)
# Save ICP state
icp_state_path = os.path.join(model_dir, "icp_state.dill")
with open(icp_state_path, "wb") as f:
dill.dump(icp, f)
# Save model dimensions to .mtlr file
dimensions_path = os.path.join(model_dir, f"mtlr_model_{model_id}.mtlr")
save_dimensions(icp.nc_function.model, dimensions_path)
if aggregated_predictions:
cv_predictions_path = os.path.join(model_dir, "cv_predictions.json")
with open(cv_predictions_path, 'w') as f:
json.dump(aggregated_predictions, f, indent=2)
cv_summary_path = os.path.join(model_dir, "cv_predictions_summary.csv")
create_cv_summary_csv(aggregated_predictions, cv_summary_path)
else:
cv_predictions_path = None
cv_summary_path = None
if full_dataset_predictions:
full_predictions_path = os.path.join(model_dir, "full_predictions.json")
with open(full_predictions_path, 'w') as f:
json.dump(full_dataset_predictions, f, indent=2)
full_summary_path = os.path.join(model_dir, "full_predictions_summary.csv")
create_cv_summary_csv(full_dataset_predictions, full_summary_path)
survival_curve_path = os.path.join(model_dir, "survival_curves.json")
save_survival_curve_mapping(full_dataset_predictions, survival_curve_path)
else:
full_predictions_path = None
full_summary_path = None
survival_curve_path = None
# Save metrics
metrics = print_performance(
Cindex=ci,
IBS=ibs,
MAE_Hinge=mae_hinge,
MAE_PO=mae_po,
KM_cal=km_cal,
xCal_stats=xcal_stats,
wsc_xCal_stats=wsc_xcal_stats,
dcal_p=dcal_p_value_stat,
dcal_Chi=dcal_chisquare,
train_times=train_times,
infer_times=infer_times
)
metrics['n_features'] = n_features
metrics['d_cal_hist'] = torch.stack(dcal_hists).mean(0).tolist()
metrics['train_start_time'] = datetime.fromtimestamp(train_start).isoformat()
metrics['train_duration'] = train_duration
# Make base_url
base_url = request.host_url.rstrip("/") # e.g., http://localhost:5000
cv_info = None
if aggregated_predictions:
cv_info = {
"summary_csv": f"{base_url}/models/{model_id}/cv_predictions_summary.csv" if cv_summary_path else None,
"full_predictions": f"{base_url}/models/{model_id}/cv_predictions.json" if cv_predictions_path else None,
"n_folds": len(all_fold_predictions),
"total_predictions": len(aggregated_predictions['actual_times'])
}
full_info = None
if full_dataset_predictions:
full_info = {
"summary_csv": f"{base_url}/models/{model_id}/full_predictions_summary.csv",
"full_predictions": f"{base_url}/models/{model_id}/full_predictions.json",
"survival_curves": f"{base_url}/models/{model_id}/survival_curves.json",
"total_identifiers": len(full_dataset_predictions['test_indices'])
}
response_data = {
"status": "success",
"model_id": model_id,
"metrics": metrics,
"selected_features": selected_features,
"model_config": f"{base_url}/models/{model_id}/model_config.json",
"mtlr_model": f"{base_url}/models/{model_id}/mtlr_model_{model_id}.mtlr",
"cv_predictions": cv_info,
"full_dataset_predictions": full_info,
"trained_at": model_timestamp_date,
"train_duration": train_duration,
"timestamp": datetime.now().isoformat()
}
return jsonify(response_data), 200
except Exception as e:
# ---------------------------------
# Cleanup on failure
# ---------------------------------
if model_dir and os.path.exists(model_dir):
shutil.rmtree(model_dir, ignore_errors=True)
return jsonify({
'status': 'error',
'error': str(e),
'error_type': type(e).__name__
}), 500
# Restrict this endpoint with user permissions
@app.route('/retrain', methods=['POST'])
def retrain_model():
"""
Retrain an existing model with different feature selections and/or parameters
Expected JSON request:
{
"model_id": "mtlr_20231103_120000_abc123", # REQUIRED - existing model to retrain
"dataset_path": "/path/to/data.csv", # OPTIONAL - Input to use different dataset from parent predictor model
"selected_features": "all", # OPTIONAL - see feature selection logic below
"parameters": {"neurons": [64, 64], "dropout": 0.1} # Optional parameter overrides
}
Feature Selection Logic:
- selected_features='all' → Use ALL features from dataset
- selected_features=['feat1', 'feat2'] → Use ONLY these specific features
- selected_features=None (or not provided) → INHERIT from parent model
Three retraining scenarios:
1. All features + different parameters: set selected_features='all', provide parameters
2. Selected features + same parameters: provide selected_features list, omit parameters
3. Selected features + different parameters: provide both
"""
# Reset metrics before training
global ci, mae_hinge, mae_po, ibs, km_cal, xcal_stats, wsc_xcal_stats
global dcal_chisquare, dcal_p_value_stat, train_times, infer_times, dcal_hists, n_features
ci.clear()
mae_hinge.clear()
mae_po.clear()
ibs.clear()
km_cal.clear()
xcal_stats.clear()
wsc_xcal_stats.clear()
dcal_chisquare.clear()
dcal_p_value_stat.clear()
train_times.clear()
infer_times.clear()
dcal_hists.clear()
n_features = 0
try:
# Get request data
if not request.is_json:
return jsonify({'error': 'Content-Type must be application/json'}), 400
json_data = request.json
# REQUIRED: model_id of existing model
model_id = json_data.get('model_id')
if not model_id:
return jsonify({'error': 'model_id is required for retraining'}), 400
# Check if model exists
original_model_dir = os.path.join(app.config['MODEL_FOLDER'], model_id)
if not os.path.exists(original_model_dir):
return jsonify({'error': f'Model {model_id} not found'}), 404
# Load original model config and metadata
original_config_path = os.path.join(original_model_dir, 'model_config.json')
original_metadata_path = os.path.join(original_model_dir, 'training_metadata.json')
with open(original_config_path, 'r') as f:
original_config = json.load(f)
# Load metadata if exists, otherwise use defaults
if os.path.exists(original_metadata_path):
with open(original_metadata_path, 'r') as f:
original_metadata = json.load(f)
else:
# Fallback for older models that might have selected_features in config
original_metadata = {
'selected_features': original_config.get('selected_features', None)
}
# Dataset Override Logic
file = None
try:
file = request.files.get("dataset")
except Exception:
# request.files may not exist or parsing failed (JSON-only request)
file = None
if file:
if file.filename == "":
return jsonify({"error": "No dataset file selected"}), 400
if not file.filename.lower().endswith(".csv"):
return jsonify({"error": "Dataset file must be a CSV"}), 400
# ✅ Save uploaded dataset file
filename = secure_filename(file.filename)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
dataset_filename = f"{timestamp}_{filename}"
dataset_path = os.path.join(app.config["UPLOAD_FOLDER"], dataset_filename)
file.save(dataset_path)
else:
# ✅ Fallback: use dataset path from metadata or JSON
dataset_path = (
request.json.get("dataset_path")
if request.is_json else None
) or original_metadata.get("dataset_path")
# ✅ Final validation
if not dataset_path:
return jsonify({"error": "Dataset missing: upload a CSV or provide dataset_path"}), 400
# dataset_path_input = json_data.get("dataset_path")
# if dataset_path_input:
# dataset_path = dataset_path_input
# else:
# # Just pull the dataset from the original model's training metadata)
# dataset_path = original_metadata.get("dataset_path")
# if not dataset_path:
# return jsonify({"error": "dataset_path missing and not found in parent model metadata"}), 400
# Feature Selection Logic
selected_features_input = json_data.get('selected_features', None)
if isinstance(selected_features_input, list):
# Specific feature list
if len(selected_features_input) == 0:
return jsonify({'error': 'selected_features list cannot be empty'}), 400
selected_features = selected_features_input
selected_features_for_training = selected_features_input
if selected_features_input == original_metadata.get('selected_features'):
features_source = 'inherited'
else:
features_source = 'selected'
elif selected_features_input is None:
# Explicitly set to None - inherit from parent
selected_features = original_metadata.get('selected_features')
selected_features_for_training = None
features_source = 'inherited'
else:
return jsonify({
'error': 'selected_features must be a list of features, None, or omitted to inherit'
}), 400
# Get optional parameter overrides
parameters = json_data.get('parameters', {})
# Start with original config, then override with new parameters
config = {
'selected_features': selected_features_for_training,
'neurons': parameters.get('neurons', original_config.get('neurons')),
'dropout': parameters.get('dropout', original_config.get('dropout')),
'activation': parameters.get('activation', original_config.get('activation')),
'norm': parameters.get('norm', original_config.get('norm')),
}
# Override with any other user-provided parameters
for key, value in parameters.items():
if value is not None:
config[key] = value
args = Args(config)
n_exp = max(1, int(getattr(args, 'n_exp', 1)))
# Create NEW model ID for the retrained version
now = datetime.now()
model_timestamp = now.strftime("%Y%m%d_%H%M%S")
model_timestamp_date = now.date().isoformat()
suffix = uuid.uuid4().hex[:6]
new_model_id = f"mtlr_retrain_{model_timestamp}_{suffix}"
model_dir = os.path.join(app.config['MODEL_FOLDER'], new_model_id)
os.makedirs(model_dir, exist_ok=True)
# NEW: Collect predictions across all folds
all_fold_predictions = []
# Training Loop
train_start = time.time()
for i in trange(n_exp, disable=not args.verbose, desc='Experiment'):
icp, encoder, indiv_preds = train_mtlr_model(
dataset_path, selected_features_for_training, args, i, return_predictions=True
)
if indiv_preds:
all_fold_predictions.append(indiv_preds)
# -------------------------------
# Aggregate individual predictions
# -------------------------------
aggregated_predictions = aggregate_cv_predictions(all_fold_predictions)
full_dataset_predictions = generate_full_dataset_predictions(
icp, encoder, dataset_path, selected_features_for_training, args
)
train_end = time.time()
train_duration = train_end - train_start
# ----------------------------
# Save artifacts
# ----------------------------
# Track what changed in this retrain
retrain_history = {
"original_features": original_metadata.get('selected_features'),
"new_features": selected_features,
"features_source": features_source,
"features_changed": original_metadata.get('selected_features') != selected_features,
"parameter_changes": {}
}
# Track which parameters changed
for param in ['neurons', 'dropout', 'activation', 'norm']:
if param in parameters and parameters[param] != original_config.get(param):
retrain_history['parameter_changes'][param] = {
'old': original_config.get(param),
'new': parameters[param]
}
# Save model config (only model architecture params)
model_config = {
"model_type": "MTLR",
"n_features": icp.nc_function.model.in_features,
"time_bins": icp.nc_function.model.time_bins.tolist(),
"neurons": args.neurons,
"dropout": args.dropout,
"activation": args.activation,
"norm": args.norm,
}
config_path = os.path.join(model_dir, "model_config.json")
with open(config_path, 'w') as f:
json.dump(model_config, f, indent=2)
# Save training metadata separately (includes selected_features and retrain history)
training_metadata = {
"selected_features": selected_features,
"parent_model_id": model_id,
"retrain_history": retrain_history,
"dataset_path": dataset_path,
"n_experiments": n_exp,
"timestamp": model_timestamp_date
}
metadata_path = os.path.join(model_dir, "training_metadata.json")