workbench 0.8.156__py3-none-any.whl → 0.8.158__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -51,16 +51,16 @@ workbench/core/artifacts/__init__.py,sha256=ps7rA_rbWnDbvWbg4kvu--IKMY8WmbPRyv4S
51
51
  workbench/core/artifacts/artifact.py,sha256=mF1lqQ8EP43zMRSxqPYuWoHRwQTjyWdpW9LewU7utEE,17517
52
52
  workbench/core/artifacts/athena_source.py,sha256=RNmCe7s6uH4gVHpcdJcL84aSbF5Q1ahJBLLGwHYRXEU,26081
53
53
  workbench/core/artifacts/cached_artifact_mixin.py,sha256=TNRq-4frDS0GRodfnz6qN2SGP0U_QglZw5X5gw-K7-Y,3755
54
- workbench/core/artifacts/data_source_abstract.py,sha256=27WVCQkIDO-cj0URdDu-9LLnuWxU_3_0wyLt4iFIwsg,10604
54
+ workbench/core/artifacts/data_source_abstract.py,sha256=5IRCzFVK-17cd4NXPMRfx99vQAmQ0WHE5jcm5RfsVTg,10619
55
55
  workbench/core/artifacts/data_source_factory.py,sha256=YL_tA5fsgubbB3dPF6T4tO0rGgz-6oo3ge4i_YXVC-M,2380
56
56
  workbench/core/artifacts/endpoint_core.py,sha256=L6uWOxHKItjbpRS2rFrAbxAqDyZIv2CO9dnZpohKrUI,48768
57
- workbench/core/artifacts/feature_set_core.py,sha256=7yyy_0RFmrhcXqZHVb0P6suo3ye1tSO_kJqqiGgjrFw,29377
57
+ workbench/core/artifacts/feature_set_core.py,sha256=055VdSYR09HP4ygAuYvIYtHQ7Ec4XxsZygpgEl5H5jQ,29136
58
58
  workbench/core/artifacts/model_core.py,sha256=WjiZyqwUVeVZF22FO8zXFoHmgh-Vd6c_KQLx_da_FTQ,50194
59
59
  workbench/core/artifacts/monitor_core.py,sha256=BP6UuCyBI4zB2wwcIXvUw6RC0EktTcQd5Rv0x73qzio,37670
60
60
  workbench/core/cloud_platform/cloud_meta.py,sha256=J3qqMLdzikRRI9TC7UEk9Ib2-64ovU8X-lzLxhze1uY,8669
61
61
  workbench/core/cloud_platform/aws/README.md,sha256=QT5IQXoUHbIA0qQ2wO6_2P2lYjYQFVYuezc22mWY4i8,97
62
- workbench/core/cloud_platform/aws/aws_account_clamp.py,sha256=YRZ_DufSNfuKgW7q9oanSwqlhZecbnapNW-twBajUX8,5683
63
- workbench/core/cloud_platform/aws/aws_df_store.py,sha256=Tdgg8QThmjWQs5gXgjK7D34qaQKe7MsaO5s8fD133F0,15043
62
+ workbench/core/cloud_platform/aws/aws_account_clamp.py,sha256=OzFknZXKW7VTvnDGGX4BXKoh0i1gQ7yaEBhkLCyHFSs,6310
63
+ workbench/core/cloud_platform/aws/aws_df_store.py,sha256=utRIlTCPwFneHHZ8_Z3Hw3rOJSeryiFA4wBtucxULRQ,15055
64
64
  workbench/core/cloud_platform/aws/aws_graph_store.py,sha256=ytYxQTplUmeWbsPmxyZbf6mO9qyTl60ewlJG8MyfyEY,9414
65
65
  workbench/core/cloud_platform/aws/aws_meta.py,sha256=ijbzucUF948RyD-GgYYyxl-Ejvkv5Z6gqB_g497ss7M,33932
66
66
  workbench/core/cloud_platform/aws/aws_parameter_store.py,sha256=9ekuMOQFHFMIEV68UbHhS_fLB9iqG5Hvu4EV6iamEpk,10400
@@ -101,14 +101,14 @@ workbench/core/transforms/features_to_features/__init__.py,sha256=47DEQpj8HBSa-_
101
101
  workbench/core/transforms/features_to_features/heavy/emr/Readme.md,sha256=YtQgCEQeKe0CQXQkhzMTYq9xOtCsCYb5P5LW2BmRKWQ,68
102
102
  workbench/core/transforms/features_to_features/heavy/glue/Readme.md,sha256=TuyCatWfoDr99zUwvOcxf-TqMkQzaMqXlj5nmFcRzfo,48
103
103
  workbench/core/transforms/features_to_model/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
104
- workbench/core/transforms/features_to_model/features_to_model.py,sha256=qtqfiN4a35TqxP_Sxfu90zrbNMA3r-q0F13Yr0VaIbM,19162
104
+ workbench/core/transforms/features_to_model/features_to_model.py,sha256=xAOcbcm2f9iumCCM_T8OTdzRkl3ZLTzyGRdv9ImmnqM,19333
105
105
  workbench/core/transforms/model_to_endpoint/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
106
106
  workbench/core/transforms/model_to_endpoint/model_to_endpoint.py,sha256=5IBhA56qSDSnfh4Xwvb2PP5UDM7md2R7Ur38hP4Mgyw,4624
107
107
  workbench/core/transforms/pandas_transforms/__init__.py,sha256=xL4MT8-fZ1SFqDbTLc8XyxjupHtB1YR6Ej0AC2nwd7I,894
108
108
  workbench/core/transforms/pandas_transforms/data_to_pandas.py,sha256=sJHPeuNF8Q8aQqgRnkdWkyvur5cbggdUVIwR-xF3Dlo,3621
109
109
  workbench/core/transforms/pandas_transforms/features_to_pandas.py,sha256=af6xdPt2V4zhh-SzQa_UYxdmNMzMLXbrbsznV5QoIJg,3441
110
110
  workbench/core/transforms/pandas_transforms/pandas_to_data.py,sha256=cqo6hQmzUGUFACvNuVLZQdgrlXrQIu4NjqK-ujPmoIc,9181
111
- workbench/core/transforms/pandas_transforms/pandas_to_features.py,sha256=wdPFnnVUBbMK2_xTSbGJ9x2TESHf6znHl3LwXtPxlX0,20183
111
+ workbench/core/transforms/pandas_transforms/pandas_to_features.py,sha256=XiUz2BqOX4N34g6hvFvcLswhkEouyU0AjyIy9EGv2zg,20440
112
112
  workbench/core/transforms/pandas_transforms/pandas_to_features_chunked.py,sha256=0R8mQlWfbIlTVmYUmrtu2gsw0AE815k6kqPgpd0bmyQ,4422
113
113
  workbench/core/views/__init__.py,sha256=UZJMAJBCMVM3uSYmnFg8c2LWtdu9-479WNAdVMIohAc,962
114
114
  workbench/core/views/column_subset_view.py,sha256=vGDKTTGrPIY-IFOeWvudJrhKiq0OjWDp5rTuuj-X40U,4261
@@ -130,6 +130,10 @@ workbench/model_scripts/custom_models/chem_info/requirements.txt,sha256=7HBUzvNi
130
130
  workbench/model_scripts/custom_models/chem_info/tautomerize.py,sha256=KAxTAqtTql4_FvnrAyYRgaJEmtAx399HXA_iw_awa08,3125
131
131
  workbench/model_scripts/custom_models/meta_endpoints/example.py,sha256=hzOAuLhIGB8vei-555ruNxpsE1GhuByHGjGB0zw8GSs,1726
132
132
  workbench/model_scripts/custom_models/network_security/Readme.md,sha256=Z2gtiu0hLHvEJ1x-_oFq3qJZcsK81sceBAGAGltpqQ8,222
133
+ workbench/model_scripts/custom_models/nn_models/Readme.md,sha256=x6U_gox2yV-kLspgmzE77t2xk5GFNgcpcuQq-Q78G7w,146
134
+ workbench/model_scripts/custom_models/nn_models/generated_model_script.py,sha256=PsowW-kosyN2wWhuDgP_41mBYscUDYKOhzzQFVUKBzc,20695
135
+ workbench/model_scripts/custom_models/nn_models/pytorch.template,sha256=-gd0FbDW1ilTo1WcwiOLVZPAyTQ09naVlnSXxrVxKYU,20422
136
+ workbench/model_scripts/custom_models/nn_models/requirements.txt,sha256=sC6v1LSBkwJFbvObn6DUD1HwPM86_rbmXEMH5Tcn2kM,184
133
137
  workbench/model_scripts/custom_models/proximity/Readme.md,sha256=RlMFAJZgAT2mCgDk-UwR_R0Y_NbCqeI5-8DUsxsbpWQ,289
134
138
  workbench/model_scripts/custom_models/proximity/feature_space_proximity.template,sha256=2c3eDu4sLP_bCTBAf_aIR1QdC7CpYDpXo8UU_2ZoLuE,4833
135
139
  workbench/model_scripts/custom_models/proximity/generated_model_script.py,sha256=RdbKbXtrSNYQJvB-oLcRHpJ6w0TM7zbmMfuocHb7GM0,7967
@@ -142,7 +146,6 @@ workbench/model_scripts/custom_models/uq_models/gaussian_process.template,sha256
142
146
  workbench/model_scripts/custom_models/uq_models/generated_model_script.py,sha256=l74VibzFnhmPeNUEiFwIIg5aNujcCs9LtRywUvc5Avo,14528
143
147
  workbench/model_scripts/custom_models/uq_models/mapie_xgb.template,sha256=ZTmerwkmXtewJwx3GGJSdLRyzJV5SJ86PvCu3dV_GHw,7330
144
148
  workbench/model_scripts/custom_models/uq_models/meta_uq.template,sha256=26FNangcpyV9nFOIufRuVZ45BQv6oPf9xlJZkVIULG4,9287
145
- workbench/model_scripts/custom_models/uq_models/meta_uq_experiment.template,sha256=2MT6-jzhmz69DuQCXAmMXoKRkBruto1m92LDsG8vdVI,14326
146
149
  workbench/model_scripts/custom_models/uq_models/ngboost.template,sha256=N-eWP967-X2Qbvk18VL7LPXRJMKne9SS2fb_jntwTec,7738
147
150
  workbench/model_scripts/custom_models/uq_models/proximity.py,sha256=zqmNlX70LnWXr5fdtFFQppSNTLjlOciQVrjGr-g9jRE,13716
148
151
  workbench/model_scripts/custom_models/uq_models/requirements.txt,sha256=jfwV5b1t6BFtdaRGrSz8LnuQzJm-4V5OlhhP-4CGxhs,107
@@ -155,7 +158,7 @@ workbench/model_scripts/quant_regression/quant_regression.template,sha256=AQihff
155
158
  workbench/model_scripts/quant_regression/requirements.txt,sha256=jWlGc7HH7vqyukTm38LN4EyDi8jDUPEay4n45z-30uc,104
156
159
  workbench/model_scripts/scikit_learn/requirements.txt,sha256=aVvwiJ3LgBUhM_PyFlb2gHXu_kpGPho3ANBzlOkfcvs,107
157
160
  workbench/model_scripts/scikit_learn/scikit_learn.template,sha256=d4pgeZYFezUQsB-7iIsjsUgB1FM6d27651wpfDdXmI0,12640
158
- workbench/model_scripts/xgb_model/generated_model_script.py,sha256=aqrDobLcMysjc-q8p5aCyPXPrVlia14CbARRqaG8--Q,21083
161
+ workbench/model_scripts/xgb_model/generated_model_script.py,sha256=BDExjY02zSbcCloW4VNzHvej_kS3H0uJxa92egoASNY,17954
159
162
  workbench/model_scripts/xgb_model/requirements.txt,sha256=jWlGc7HH7vqyukTm38LN4EyDi8jDUPEay4n45z-30uc,104
160
163
  workbench/model_scripts/xgb_model/xgb_model.template,sha256=RaUr8X6al5R2IILNKgGUH05Gb4H7AFFG9RE524_VH7Q,17935
161
164
  workbench/repl/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -194,7 +197,7 @@ workbench/utils/aws_utils.py,sha256=XckM0vzud7Nx1OxD1GoYGLQxdj1PqeQ43cN66tnrRYI,
194
197
  workbench/utils/bulk_utils.py,sha256=s1lYN2Uk536MNGetekLYL_VL0N34hUjk1FX9BAz3Qu0,1182
195
198
  workbench/utils/cache.py,sha256=0R5RXYEz_XHARK3anmQC4VRMawMks_cJ8S4vwC2roAE,5524
196
199
  workbench/utils/chem_utils.py,sha256=tLTAvLKTOiYSzbVQF0M8V5-ej36IVgr21CNB2vVJjYQ,56780
197
- workbench/utils/cloudwatch_handler.py,sha256=ocrj4oXIBIBZHax_ekk4E4r-tD-yTrlDmZeKRFBauOo,5491
200
+ workbench/utils/cloudwatch_handler.py,sha256=dtnkr8tXtTRAASQ60QO0lz3SRA5LEbzsK1VCIqblfKs,5157
198
201
  workbench/utils/color_utils.py,sha256=TmDGLK44t975lkfjt_1O-ee02QxrKfke7vPuXb-V-Uo,11779
199
202
  workbench/utils/config_manager.py,sha256=Yj43Ta67dn34XdOcKcOvXw38ln6TRiv4DePXjPt2jg8,17641
200
203
  workbench/utils/dashboard_metrics.py,sha256=cNFI0GIAjd_IiDzM1oebsJ2QkRZuW068W_66ZC3J100,7398
@@ -252,7 +255,7 @@ workbench/web_interface/components/experiments/dashboard_metric_plots.py,sha256=
252
255
  workbench/web_interface/components/experiments/outlier_plot.py,sha256=5bWsmJEXyt50npeQxLHXCPtiq4WRVgg938Sl0DVjNWg,3647
253
256
  workbench/web_interface/components/plugins/ag_table.py,sha256=HrPOMotlOGigk0v8Cxx_doSHXdOKTT1-bzlsqDwwzng,3979
254
257
  workbench/web_interface/components/plugins/confusion_matrix.py,sha256=1K94JSlDwQwdf5uDYVydQzY-EQm89hYXchxbXoNvons,7176
255
- workbench/web_interface/components/plugins/dashboard_status.py,sha256=KWQW6EArOXhrUwZ0mMZydQk6nOpIoU6ftP4a0goN-Ew,5690
258
+ workbench/web_interface/components/plugins/dashboard_status.py,sha256=8Tu38lR5YgntxDjz_x2XfLiW7SOdreNLOFT5VkbYzKo,5748
256
259
  workbench/web_interface/components/plugins/data_details.py,sha256=pZm1AbM_0EXQwx77qUkfyrU9MedAs4Wlkp6iOtSrUtI,11104
257
260
  workbench/web_interface/components/plugins/endpoint_details.py,sha256=0A7g_Lx5-3XnDWOGT3YEDPNpmME_-WfYc65f-rRVjJE,3769
258
261
  workbench/web_interface/components/plugins/generated_compounds.py,sha256=hC0sh-1_rbN55Huno-E_2wF37kgIHi5Mtaer6Xk5fRM,8052
@@ -272,9 +275,9 @@ workbench/web_interface/page_views/main_page.py,sha256=QIGiQPXu5Q9TU15nPEAYa6sjQ
272
275
  workbench/web_interface/page_views/models_page_view.py,sha256=M0bdC7bAzLyIaE2jviY12FF4abdMFZmg6sFuOY_LaGI,2650
273
276
  workbench/web_interface/page_views/page_view.py,sha256=Gh6YnpOGlUejx-bHZAf5pzqoQ1H1R0OSwOpGhOBO06w,455
274
277
  workbench/web_interface/page_views/pipelines_page_view.py,sha256=v2pxrIbsHBcYiblfius3JK766NZ7ciD2yPx0t3E5IJo,2656
275
- workbench-0.8.156.dist-info/licenses/LICENSE,sha256=z4QMMPlLJkZjU8VOKqJkZiQZCEZ--saIU2Z8-p3aVc0,1080
276
- workbench-0.8.156.dist-info/METADATA,sha256=29854fjJPyoP6gHfmAt9DQFAI_KuS72Cjh2q133azrk,9497
277
- workbench-0.8.156.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
278
- workbench-0.8.156.dist-info/entry_points.txt,sha256=oZykkheWiiIBjRE8cS5SdcxwmZKSFaQEGwMBjNh-eNM,238
279
- workbench-0.8.156.dist-info/top_level.txt,sha256=Dhy72zTxaA_o_yRkPZx5zw-fwumnjGaeGf0hBN3jc_w,10
280
- workbench-0.8.156.dist-info/RECORD,,
278
+ workbench-0.8.158.dist-info/licenses/LICENSE,sha256=z4QMMPlLJkZjU8VOKqJkZiQZCEZ--saIU2Z8-p3aVc0,1080
279
+ workbench-0.8.158.dist-info/METADATA,sha256=gzWmV7xJLnwpDa2r_SM6XIOPXR2zNb6shhtoEwHD1d4,9393
280
+ workbench-0.8.158.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
281
+ workbench-0.8.158.dist-info/entry_points.txt,sha256=oZykkheWiiIBjRE8cS5SdcxwmZKSFaQEGwMBjNh-eNM,238
282
+ workbench-0.8.158.dist-info/top_level.txt,sha256=Dhy72zTxaA_o_yRkPZx5zw-fwumnjGaeGf0hBN3jc_w,10
283
+ workbench-0.8.158.dist-info/RECORD,,
@@ -1,393 +0,0 @@
1
- # Model: NGBoost Regressor with Distribution output
2
- from ngboost import NGBRegressor
3
- from xgboost import XGBRegressor # Base Estimator
4
- from sklearn.model_selection import train_test_split
5
- import numpy as np
6
-
7
- # Model Performance Scores
8
- from sklearn.metrics import (
9
- mean_absolute_error,
10
- r2_score,
11
- root_mean_squared_error
12
- )
13
-
14
- from io import StringIO
15
- import json
16
- import argparse
17
- import joblib
18
- import os
19
- import pandas as pd
20
-
21
- # Local Imports
22
- from proximity import Proximity
23
-
24
-
25
-
26
- # Template Placeholders
27
- TEMPLATE_PARAMS = {
28
- "id_column": "{{id_column}}",
29
- "features": "{{feature_list}}",
30
- "target": "{{target_column}}",
31
- "train_all_data": "{{train_all_data}}",
32
- "track_columns": "{{track_columns}}"
33
- }
34
-
35
-
36
- # Function to check if dataframe is empty
37
- def check_dataframe(df: pd.DataFrame, df_name: str) -> None:
38
- """
39
- Check if the provided dataframe is empty and raise an exception if it is.
40
-
41
- Args:
42
- df (pd.DataFrame): DataFrame to check
43
- df_name (str): Name of the DataFrame
44
- """
45
- if df.empty:
46
- msg = f"*** The training data {df_name} has 0 rows! ***STOPPING***"
47
- print(msg)
48
- raise ValueError(msg)
49
-
50
-
51
- def match_features_case_insensitive(df: pd.DataFrame, model_features: list) -> pd.DataFrame:
52
- """
53
- Matches and renames DataFrame columns to match model feature names (case-insensitive).
54
- Prioritizes exact matches, then case-insensitive matches.
55
-
56
- Raises ValueError if any model features cannot be matched.
57
- """
58
- df_columns_lower = {col.lower(): col for col in df.columns}
59
- rename_dict = {}
60
- missing = []
61
- for feature in model_features:
62
- if feature in df.columns:
63
- continue # Exact match
64
- elif feature.lower() in df_columns_lower:
65
- rename_dict[df_columns_lower[feature.lower()]] = feature
66
- else:
67
- missing.append(feature)
68
-
69
- if missing:
70
- raise ValueError(f"Features not found: {missing}")
71
-
72
- # Rename the DataFrame columns to match the model features
73
- return df.rename(columns=rename_dict)
74
-
75
-
76
- def distance_weighted_calibrated_intervals(
77
- df_pred: pd.DataFrame,
78
- prox_df: pd.DataFrame,
79
- calibration_strength: float = 0.7,
80
- distance_decay: float = 3.0,
81
- ) -> pd.DataFrame:
82
- """
83
- Calibrate intervals using distance-weighted neighbor quantiles.
84
- Uses all 10 neighbors with distance-based weighting.
85
- """
86
- id_column = TEMPLATE_PARAMS["id_column"]
87
- target_column = TEMPLATE_PARAMS["target"]
88
-
89
- # Distance-weighted neighbor statistics
90
- def weighted_quantile(values, weights, q):
91
- """Calculate weighted quantile"""
92
- if len(values) == 0:
93
- return np.nan
94
- sorted_indices = np.argsort(values)
95
- sorted_values = values[sorted_indices]
96
- sorted_weights = weights[sorted_indices]
97
- cumsum = np.cumsum(sorted_weights)
98
- cutoff = q * cumsum[-1]
99
- return np.interp(cutoff, cumsum, sorted_values)
100
-
101
- # Calculate distance weights (closer neighbors get more weight)
102
- prox_df = prox_df.copy()
103
- prox_df['weight'] = 1 / (1 + prox_df['distance'] ** distance_decay)
104
-
105
- # Get weighted quantiles and statistics for each ID
106
- neighbor_stats = []
107
- for id_val, group in prox_df.groupby(id_column):
108
- values = group[target_column].values
109
- weights = group['weight'].values
110
-
111
- # Normalize weights
112
- weights = weights / weights.sum()
113
-
114
- stats = {
115
- id_column: id_val,
116
- 'local_q025': weighted_quantile(values, weights, 0.025),
117
- 'local_q25': weighted_quantile(values, weights, 0.25),
118
- 'local_q75': weighted_quantile(values, weights, 0.75),
119
- 'local_q975': weighted_quantile(values, weights, 0.975),
120
- 'local_median': weighted_quantile(values, weights, 0.5),
121
- 'local_std': np.sqrt(np.average((values - np.average(values, weights=weights)) ** 2, weights=weights)),
122
- 'avg_distance': group['distance'].mean(),
123
- 'min_distance': group['distance'].min(),
124
- 'max_distance': group['distance'].max(),
125
- }
126
- neighbor_stats.append(stats)
127
-
128
- neighbor_df = pd.DataFrame(neighbor_stats)
129
- out = df_pred.merge(neighbor_df, on=id_column, how='left')
130
-
131
- # Model disagreement score (normalized by prediction std)
132
- model_disagreement = (out["prediction"] - out["prediction_uq"]).abs()
133
- disagreement_score = (model_disagreement / out["prediction_std"]).clip(0, 2)
134
-
135
- # Local confidence based on:
136
- # 1. How close the neighbors are (closer = more confident)
137
- # 2. How much local variance there is (less variance = more confident)
138
- max_reasonable_distance = out['max_distance'].quantile(0.8) # 80th percentile as reference
139
- distance_confidence = (1 - (out['avg_distance'] / max_reasonable_distance)).clip(0.1, 1.0)
140
-
141
- variance_confidence = (out["prediction_std"] / out["local_std"]).clip(0.5, 2.0)
142
- local_confidence = distance_confidence * variance_confidence.clip(0.5, 1.5)
143
-
144
- # Calibration weight: higher when models disagree and we have good local data
145
- calibration_weight = (
146
- calibration_strength *
147
- local_confidence * # Weight by local data quality
148
- disagreement_score.clip(0.3, 1.0) # More calibration when models disagree
149
- )
150
-
151
- # Consensus prediction (slight preference for NGBoost since it provides intervals)
152
- consensus_pred = 0.65 * out["prediction_uq"] + 0.35 * out["prediction"]
153
-
154
- # Re-center local intervals around consensus prediction
155
- local_center_offset = consensus_pred - out["local_median"]
156
-
157
- # Apply calibration to each quantile
158
- quantile_pairs = [
159
- ("q_025", "local_q025"),
160
- ("q_25", "local_q25"),
161
- ("q_75", "local_q75"),
162
- ("q_975", "local_q975")
163
- ]
164
-
165
- for model_q, local_q in quantile_pairs:
166
- # Adjust local quantiles to be centered around consensus
167
- adjusted_local_q = out[local_q] + local_center_offset
168
-
169
- # Blend model and local intervals
170
- out[model_q] = (
171
- (1 - calibration_weight) * out[model_q] +
172
- calibration_weight * adjusted_local_q
173
- )
174
-
175
- # Ensure proper interval ordering and bounds using pandas
176
- out["q_025"] = pd.concat([out["q_025"], consensus_pred], axis=1).min(axis=1)
177
- out["q_975"] = pd.concat([out["q_975"], consensus_pred], axis=1).max(axis=1)
178
- out["q_25"] = pd.concat([out["q_25"], out["q_75"]], axis=1).min(axis=1)
179
-
180
- # Optional: Add some interval expansion when neighbors are very far
181
- # (indicates we're in a sparse region of feature space)
182
- sparse_region_mask = out['min_distance'] > out['min_distance'].quantile(0.9)
183
- expansion_factor = 1 + 0.2 * sparse_region_mask # 20% expansion in sparse regions
184
-
185
- for q in ["q_025", "q_25", "q_75", "q_975"]:
186
- interval_width = out[q] - consensus_pred
187
- out[q] = consensus_pred + interval_width * expansion_factor
188
-
189
- # Clean up temporary columns
190
- cleanup_cols = [col for col in out.columns if col.startswith("local_")] + \
191
- ['avg_distance', 'min_distance', 'max_distance']
192
-
193
- return out.drop(columns=cleanup_cols)
194
-
195
-
196
- # TRAINING SECTION
197
- #
198
- # This section (__main__) is where SageMaker will execute the training job
199
- # and save the model artifacts to the model directory.
200
- #
201
- if __name__ == "__main__":
202
- # Template Parameters
203
- id_column = TEMPLATE_PARAMS["id_column"]
204
- features = TEMPLATE_PARAMS["features"]
205
- target = TEMPLATE_PARAMS["target"]
206
- train_all_data = TEMPLATE_PARAMS["train_all_data"]
207
- track_columns = TEMPLATE_PARAMS["track_columns"] # Can be None
208
- validation_split = 0.2
209
-
210
- # Script arguments for input/output directories
211
- parser = argparse.ArgumentParser()
212
- parser.add_argument("--model-dir", type=str, default=os.environ.get("SM_MODEL_DIR", "/opt/ml/model"))
213
- parser.add_argument("--train", type=str, default=os.environ.get("SM_CHANNEL_TRAIN", "/opt/ml/input/data/train"))
214
- parser.add_argument(
215
- "--output-data-dir", type=str, default=os.environ.get("SM_OUTPUT_DATA_DIR", "/opt/ml/output/data")
216
- )
217
- args = parser.parse_args()
218
-
219
- # Load training data from the specified directory
220
- training_files = [
221
- os.path.join(args.train, file)
222
- for file in os.listdir(args.train) if file.endswith(".csv")
223
- ]
224
- print(f"Training Files: {training_files}")
225
-
226
- # Combine files and read them all into a single pandas dataframe
227
- df = pd.concat([pd.read_csv(file, engine="python") for file in training_files])
228
-
229
- # Check if the DataFrame is empty
230
- check_dataframe(df, "training_df")
231
-
232
- # Training data split logic
233
- if train_all_data:
234
- # Use all data for both training and validation
235
- print("Training on all data...")
236
- df_train = df.copy()
237
- df_val = df.copy()
238
- elif "training" in df.columns:
239
- # Split data based on a 'training' column if it exists
240
- print("Splitting data based on 'training' column...")
241
- df_train = df[df["training"]].copy()
242
- df_val = df[~df["training"]].copy()
243
- else:
244
- # Perform a random split if no 'training' column is found
245
- print("Splitting data randomly...")
246
- df_train, df_val = train_test_split(df, test_size=validation_split, random_state=42)
247
-
248
- # We're using XGBoost for point predictions and NGBoost for uncertainty quantification
249
- xgb_model = XGBRegressor()
250
- ngb_model = NGBRegressor()
251
-
252
- # Prepare features and targets for training
253
- X_train = df_train[features]
254
- X_val = df_val[features]
255
- y_train = df_train[target]
256
- y_val = df_val[target]
257
-
258
- # Train both models using the training data
259
- xgb_model.fit(X_train, y_train)
260
- ngb_model.fit(X_train, y_train, X_val=X_val, Y_val=y_val)
261
-
262
- # Make Predictions on the Validation Set
263
- print(f"Making Predictions on Validation Set...")
264
- y_validate = df_val[target]
265
- X_validate = df_val[features]
266
- preds = xgb_model.predict(X_validate)
267
-
268
- # Calculate various model performance metrics (regression)
269
- rmse = root_mean_squared_error(y_validate, preds)
270
- mae = mean_absolute_error(y_validate, preds)
271
- r2 = r2_score(y_validate, preds)
272
- print(f"RMSE: {rmse:.3f}")
273
- print(f"MAE: {mae:.3f}")
274
- print(f"R2: {r2:.3f}")
275
- print(f"NumRows: {len(df_val)}")
276
-
277
- # Save the trained XGBoost model
278
- xgb_model.save_model(os.path.join(args.model_dir, "xgb_model.json"))
279
-
280
- # Save the trained NGBoost model
281
- joblib.dump(ngb_model, os.path.join(args.model_dir, "ngb_model.joblib"))
282
-
283
- # Save the feature list to validate input during predictions
284
- with open(os.path.join(args.model_dir, "feature_columns.json"), "w") as fp:
285
- json.dump(features, fp)
286
-
287
- # Now the Proximity model
288
- model = Proximity(df_train, id_column, features, target, track_columns=track_columns)
289
-
290
- # Now serialize the model
291
- model.serialize(args.model_dir)
292
-
293
-
294
- #
295
- # Inference Section
296
- #
297
- def model_fn(model_dir) -> dict:
298
- """Load and return XGBoost and NGBoost regressors from model directory."""
299
-
300
- # Load XGBoost regressor
301
- xgb_path = os.path.join(model_dir, "xgb_model.json")
302
- xgb_model = XGBRegressor(enable_categorical=True)
303
- xgb_model.load_model(xgb_path)
304
-
305
- # Load NGBoost regressor
306
- ngb_model = joblib.load(os.path.join(model_dir, "ngb_model.joblib"))
307
-
308
- # Deserialize the proximity model
309
- prox_model = Proximity.deserialize(model_dir)
310
-
311
- return {
312
- "xgboost": xgb_model,
313
- "ngboost": ngb_model,
314
- "proximity": prox_model
315
- }
316
-
317
-
318
- def input_fn(input_data, content_type):
319
- """Parse input data and return a DataFrame."""
320
- if not input_data:
321
- raise ValueError("Empty input data is not supported!")
322
-
323
- # Decode bytes to string if necessary
324
- if isinstance(input_data, bytes):
325
- input_data = input_data.decode("utf-8")
326
-
327
- if "text/csv" in content_type:
328
- return pd.read_csv(StringIO(input_data))
329
- elif "application/json" in content_type:
330
- return pd.DataFrame(json.loads(input_data)) # Assumes JSON array of records
331
- else:
332
- raise ValueError(f"{content_type} not supported!")
333
-
334
-
335
- def output_fn(output_df, accept_type):
336
- """Supports both CSV and JSON output formats."""
337
- if "text/csv" in accept_type:
338
- csv_output = output_df.fillna("N/A").to_csv(index=False) # CSV with N/A for missing values
339
- return csv_output, "text/csv"
340
- elif "application/json" in accept_type:
341
- return output_df.to_json(orient="records"), "application/json" # JSON array of records (NaNs -> null)
342
- else:
343
- raise RuntimeError(f"{accept_type} accept type is not supported by this script.")
344
-
345
-
346
- def predict_fn(df, models) -> pd.DataFrame:
347
- """Make Predictions with our XGB Quantile Regression Model
348
-
349
- Args:
350
- df (pd.DataFrame): The input DataFrame
351
- models (dict): The dictionary of models to use for predictions
352
-
353
- Returns:
354
- pd.DataFrame: The DataFrame with the predictions added
355
- """
356
-
357
- # Grab our feature columns (from training)
358
- model_dir = os.environ.get("SM_MODEL_DIR", "/opt/ml/model")
359
- with open(os.path.join(model_dir, "feature_columns.json")) as fp:
360
- model_features = json.load(fp)
361
-
362
- # Match features in a case-insensitive manner
363
- matched_df = match_features_case_insensitive(df, model_features)
364
-
365
- # Use XGBoost for point predictions
366
- df["prediction"] = models["xgboost"].predict(matched_df[model_features])
367
-
368
- # NGBoost predict returns distribution objects
369
- y_dists = models["ngboost"].pred_dist(matched_df[model_features])
370
-
371
- # Extract parameters from distribution
372
- dist_params = y_dists.params
373
-
374
- # Extract mean and std from distribution parameters
375
- df["prediction_uq"] = dist_params['loc'] # mean
376
- df["prediction_std"] = dist_params['scale'] # standard deviation
377
-
378
- # Add 95% prediction intervals using ppf (percent point function)
379
- df["q_025"] = y_dists.ppf(0.025) # 2.5th percentile
380
- df["q_975"] = y_dists.ppf(0.975) # 97.5th percentile
381
-
382
- # Add 50% prediction intervals
383
- df["q_25"] = y_dists.ppf(0.25) # 25th percentile
384
- df["q_75"] = y_dists.ppf(0.75) # 75th percentile
385
-
386
- # Compute Nearest neighbors with Proximity model
387
- prox_df = models["proximity"].neighbors(df)
388
-
389
- # Shrink prediction intervals based on KNN variance
390
- df = distance_weighted_calibrated_intervals(df, prox_df)
391
-
392
- # Return the modified DataFrame
393
- return df