workbench 0.8.174__py3-none-any.whl → 0.8.227__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.
Potentially problematic release.
This version of workbench might be problematic. Click here for more details.
- workbench/__init__.py +1 -0
- workbench/algorithms/dataframe/__init__.py +1 -2
- workbench/algorithms/dataframe/compound_dataset_overlap.py +321 -0
- workbench/algorithms/dataframe/feature_space_proximity.py +168 -75
- workbench/algorithms/dataframe/fingerprint_proximity.py +422 -86
- workbench/algorithms/dataframe/projection_2d.py +44 -21
- workbench/algorithms/dataframe/proximity.py +259 -305
- workbench/algorithms/graph/light/proximity_graph.py +12 -11
- workbench/algorithms/models/cleanlab_model.py +382 -0
- workbench/algorithms/models/noise_model.py +388 -0
- workbench/algorithms/sql/column_stats.py +0 -1
- workbench/algorithms/sql/correlations.py +0 -1
- workbench/algorithms/sql/descriptive_stats.py +0 -1
- workbench/algorithms/sql/outliers.py +3 -3
- workbench/api/__init__.py +5 -1
- workbench/api/df_store.py +17 -108
- workbench/api/endpoint.py +14 -12
- workbench/api/feature_set.py +117 -11
- workbench/api/meta.py +0 -1
- workbench/api/meta_model.py +289 -0
- workbench/api/model.py +52 -21
- workbench/api/parameter_store.py +3 -52
- workbench/cached/cached_meta.py +0 -1
- workbench/cached/cached_model.py +49 -11
- workbench/core/artifacts/__init__.py +11 -2
- workbench/core/artifacts/artifact.py +7 -7
- workbench/core/artifacts/data_capture_core.py +8 -1
- workbench/core/artifacts/df_store_core.py +114 -0
- workbench/core/artifacts/endpoint_core.py +323 -205
- workbench/core/artifacts/feature_set_core.py +249 -45
- workbench/core/artifacts/model_core.py +133 -101
- workbench/core/artifacts/parameter_store_core.py +98 -0
- workbench/core/cloud_platform/aws/aws_account_clamp.py +48 -2
- workbench/core/cloud_platform/cloud_meta.py +0 -1
- workbench/core/pipelines/pipeline_executor.py +1 -1
- workbench/core/transforms/features_to_model/features_to_model.py +60 -44
- workbench/core/transforms/model_to_endpoint/model_to_endpoint.py +43 -10
- workbench/core/transforms/pandas_transforms/pandas_to_features.py +38 -2
- workbench/core/views/training_view.py +113 -42
- workbench/core/views/view.py +53 -3
- workbench/core/views/view_utils.py +4 -4
- workbench/model_script_utils/model_script_utils.py +339 -0
- workbench/model_script_utils/pytorch_utils.py +405 -0
- workbench/model_script_utils/uq_harness.py +277 -0
- workbench/model_scripts/chemprop/chemprop.template +774 -0
- workbench/model_scripts/chemprop/generated_model_script.py +774 -0
- workbench/model_scripts/chemprop/model_script_utils.py +339 -0
- workbench/model_scripts/chemprop/requirements.txt +3 -0
- workbench/model_scripts/custom_models/chem_info/fingerprints.py +175 -0
- workbench/model_scripts/custom_models/chem_info/mol_descriptors.py +18 -7
- workbench/model_scripts/custom_models/chem_info/mol_standardize.py +80 -58
- workbench/model_scripts/custom_models/chem_info/molecular_descriptors.py +0 -1
- workbench/model_scripts/custom_models/chem_info/morgan_fingerprints.py +1 -2
- workbench/model_scripts/custom_models/proximity/feature_space_proximity.py +194 -0
- workbench/model_scripts/custom_models/proximity/feature_space_proximity.template +8 -10
- workbench/model_scripts/custom_models/uq_models/bayesian_ridge.template +7 -8
- workbench/model_scripts/custom_models/uq_models/ensemble_xgb.template +20 -21
- workbench/model_scripts/custom_models/uq_models/feature_space_proximity.py +194 -0
- workbench/model_scripts/custom_models/uq_models/gaussian_process.template +5 -11
- workbench/model_scripts/custom_models/uq_models/ngboost.template +15 -16
- workbench/model_scripts/ensemble_xgb/ensemble_xgb.template +15 -17
- workbench/model_scripts/meta_model/generated_model_script.py +209 -0
- workbench/model_scripts/meta_model/meta_model.template +209 -0
- workbench/model_scripts/pytorch_model/generated_model_script.py +443 -499
- workbench/model_scripts/pytorch_model/model_script_utils.py +339 -0
- workbench/model_scripts/pytorch_model/pytorch.template +440 -496
- workbench/model_scripts/pytorch_model/pytorch_utils.py +405 -0
- workbench/model_scripts/pytorch_model/requirements.txt +1 -1
- workbench/model_scripts/pytorch_model/uq_harness.py +277 -0
- workbench/model_scripts/scikit_learn/generated_model_script.py +7 -12
- workbench/model_scripts/scikit_learn/scikit_learn.template +4 -9
- workbench/model_scripts/script_generation.py +15 -12
- workbench/model_scripts/uq_models/generated_model_script.py +248 -0
- workbench/model_scripts/xgb_model/generated_model_script.py +371 -403
- workbench/model_scripts/xgb_model/model_script_utils.py +339 -0
- workbench/model_scripts/xgb_model/uq_harness.py +277 -0
- workbench/model_scripts/xgb_model/xgb_model.template +367 -399
- workbench/repl/workbench_shell.py +18 -14
- workbench/resources/open_source_api.key +1 -1
- workbench/scripts/endpoint_test.py +162 -0
- workbench/scripts/lambda_test.py +73 -0
- workbench/scripts/meta_model_sim.py +35 -0
- workbench/scripts/ml_pipeline_sqs.py +122 -6
- workbench/scripts/training_test.py +85 -0
- workbench/themes/dark/custom.css +59 -0
- workbench/themes/dark/plotly.json +5 -5
- workbench/themes/light/custom.css +153 -40
- workbench/themes/light/plotly.json +9 -9
- workbench/themes/midnight_blue/custom.css +59 -0
- workbench/utils/aws_utils.py +0 -1
- workbench/utils/chem_utils/fingerprints.py +87 -46
- workbench/utils/chem_utils/mol_descriptors.py +18 -7
- workbench/utils/chem_utils/mol_standardize.py +80 -58
- workbench/utils/chem_utils/projections.py +16 -6
- workbench/utils/chem_utils/vis.py +25 -27
- workbench/utils/chemprop_utils.py +141 -0
- workbench/utils/config_manager.py +2 -6
- workbench/utils/endpoint_utils.py +5 -7
- workbench/utils/license_manager.py +2 -6
- workbench/utils/markdown_utils.py +57 -0
- workbench/utils/meta_model_simulator.py +499 -0
- workbench/utils/metrics_utils.py +256 -0
- workbench/utils/model_utils.py +274 -87
- workbench/utils/pipeline_utils.py +0 -1
- workbench/utils/plot_utils.py +159 -34
- workbench/utils/pytorch_utils.py +87 -0
- workbench/utils/shap_utils.py +11 -57
- workbench/utils/theme_manager.py +95 -30
- workbench/utils/xgboost_local_crossfold.py +267 -0
- workbench/utils/xgboost_model_utils.py +127 -220
- workbench/web_interface/components/experiments/outlier_plot.py +0 -1
- workbench/web_interface/components/model_plot.py +16 -2
- workbench/web_interface/components/plugin_unit_test.py +5 -3
- workbench/web_interface/components/plugins/ag_table.py +2 -4
- workbench/web_interface/components/plugins/confusion_matrix.py +3 -6
- workbench/web_interface/components/plugins/model_details.py +48 -80
- workbench/web_interface/components/plugins/scatter_plot.py +192 -92
- workbench/web_interface/components/settings_menu.py +184 -0
- workbench/web_interface/page_views/main_page.py +0 -1
- {workbench-0.8.174.dist-info → workbench-0.8.227.dist-info}/METADATA +31 -17
- {workbench-0.8.174.dist-info → workbench-0.8.227.dist-info}/RECORD +125 -111
- {workbench-0.8.174.dist-info → workbench-0.8.227.dist-info}/entry_points.txt +4 -0
- {workbench-0.8.174.dist-info → workbench-0.8.227.dist-info}/licenses/LICENSE +1 -1
- workbench/core/cloud_platform/aws/aws_df_store.py +0 -404
- workbench/core/cloud_platform/aws/aws_parameter_store.py +0 -280
- workbench/model_scripts/custom_models/meta_endpoints/example.py +0 -53
- workbench/model_scripts/custom_models/proximity/generated_model_script.py +0 -138
- workbench/model_scripts/custom_models/proximity/proximity.py +0 -384
- workbench/model_scripts/custom_models/uq_models/generated_model_script.py +0 -393
- workbench/model_scripts/custom_models/uq_models/mapie.template +0 -502
- workbench/model_scripts/custom_models/uq_models/meta_uq.template +0 -386
- workbench/model_scripts/custom_models/uq_models/proximity.py +0 -384
- workbench/model_scripts/ensemble_xgb/generated_model_script.py +0 -279
- workbench/model_scripts/quant_regression/quant_regression.template +0 -279
- workbench/model_scripts/quant_regression/requirements.txt +0 -1
- workbench/themes/quartz/base_css.url +0 -1
- workbench/themes/quartz/custom.css +0 -117
- workbench/themes/quartz/plotly.json +0 -642
- workbench/themes/quartz_dark/base_css.url +0 -1
- workbench/themes/quartz_dark/custom.css +0 -131
- workbench/themes/quartz_dark/plotly.json +0 -642
- workbench/utils/fast_inference.py +0 -167
- workbench/utils/resource_utils.py +0 -39
- {workbench-0.8.174.dist-info → workbench-0.8.227.dist-info}/WHEEL +0 -0
- {workbench-0.8.174.dist-info → workbench-0.8.227.dist-info}/top_level.txt +0 -0
workbench/utils/model_utils.py
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import logging
|
|
4
4
|
import pandas as pd
|
|
5
5
|
import numpy as np
|
|
6
|
+
from scipy.stats import spearmanr
|
|
6
7
|
import importlib.resources
|
|
7
8
|
from pathlib import Path
|
|
8
9
|
import os
|
|
@@ -92,13 +93,158 @@ def get_custom_script_path(package: str, script_name: str) -> Path:
|
|
|
92
93
|
return script_path
|
|
93
94
|
|
|
94
95
|
|
|
95
|
-
def
|
|
96
|
-
"""Create a
|
|
96
|
+
def proximity_model_local(model: "Model", include_all_columns: bool = False):
|
|
97
|
+
"""Create a FeatureSpaceProximity Model for this Model
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
model (Model): The Model/FeatureSet used to create the proximity model
|
|
101
|
+
include_all_columns (bool): Include all DataFrame columns in neighbor results (default: False)
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
FeatureSpaceProximity: The proximity model
|
|
105
|
+
"""
|
|
106
|
+
from workbench.algorithms.dataframe.feature_space_proximity import FeatureSpaceProximity # noqa: F401
|
|
107
|
+
from workbench.api import Model, FeatureSet # noqa: F401 (avoid circular import)
|
|
108
|
+
|
|
109
|
+
# Get Feature and Target Columns from the existing given Model
|
|
110
|
+
features = model.features()
|
|
111
|
+
target = model.target()
|
|
112
|
+
|
|
113
|
+
# Backtrack our FeatureSet to get the ID column
|
|
114
|
+
fs = FeatureSet(model.get_input())
|
|
115
|
+
id_column = fs.id_column
|
|
116
|
+
|
|
117
|
+
# Create the Proximity Model from both the full FeatureSet and the Model training data
|
|
118
|
+
full_df = fs.pull_dataframe()
|
|
119
|
+
model_df = model.training_view().pull_dataframe()
|
|
120
|
+
|
|
121
|
+
# Mark rows that are in the model
|
|
122
|
+
model_ids = set(model_df[id_column])
|
|
123
|
+
full_df["in_model"] = full_df[id_column].isin(model_ids)
|
|
124
|
+
|
|
125
|
+
# Create and return the FeatureSpaceProximity Model
|
|
126
|
+
return FeatureSpaceProximity(
|
|
127
|
+
full_df, id_column=id_column, features=features, target=target, include_all_columns=include_all_columns
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def fingerprint_prox_model_local(
|
|
132
|
+
model: "Model",
|
|
133
|
+
include_all_columns: bool = False,
|
|
134
|
+
radius: int = 2,
|
|
135
|
+
n_bits: int = 1024,
|
|
136
|
+
counts: bool = False,
|
|
137
|
+
):
|
|
138
|
+
"""Create a FingerprintProximity Model for this Model
|
|
139
|
+
|
|
140
|
+
Args:
|
|
141
|
+
model (Model): The Model used to create the fingerprint proximity model
|
|
142
|
+
include_all_columns (bool): Include all DataFrame columns in neighbor results (default: False)
|
|
143
|
+
radius (int): Morgan fingerprint radius (default: 2)
|
|
144
|
+
n_bits (int): Number of bits for the fingerprint (default: 1024)
|
|
145
|
+
counts (bool): Use count fingerprints instead of binary (default: False)
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
FingerprintProximity: The fingerprint proximity model
|
|
149
|
+
"""
|
|
150
|
+
from workbench.algorithms.dataframe.fingerprint_proximity import FingerprintProximity # noqa: F401
|
|
151
|
+
from workbench.api import Model, FeatureSet # noqa: F401 (avoid circular import)
|
|
152
|
+
|
|
153
|
+
# Get Target Column from the existing given Model
|
|
154
|
+
target = model.target()
|
|
155
|
+
|
|
156
|
+
# Backtrack our FeatureSet to get the ID column
|
|
157
|
+
fs = FeatureSet(model.get_input())
|
|
158
|
+
id_column = fs.id_column
|
|
159
|
+
|
|
160
|
+
# Create the Proximity Model from both the full FeatureSet and the Model training data
|
|
161
|
+
full_df = fs.pull_dataframe()
|
|
162
|
+
model_df = model.training_view().pull_dataframe()
|
|
163
|
+
|
|
164
|
+
# Mark rows that are in the model
|
|
165
|
+
model_ids = set(model_df[id_column])
|
|
166
|
+
full_df["in_model"] = full_df[id_column].isin(model_ids)
|
|
167
|
+
|
|
168
|
+
# Create and return the FingerprintProximity Model
|
|
169
|
+
return FingerprintProximity(
|
|
170
|
+
full_df,
|
|
171
|
+
id_column=id_column,
|
|
172
|
+
target=target,
|
|
173
|
+
include_all_columns=include_all_columns,
|
|
174
|
+
radius=radius,
|
|
175
|
+
n_bits=n_bits,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def noise_model_local(model: "Model"):
|
|
180
|
+
"""Create a NoiseModel for detecting noisy/problematic samples in a Model's training data.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
model (Model): The Model used to create the noise model
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
NoiseModel: The noise model with precomputed noise scores for all samples
|
|
187
|
+
"""
|
|
188
|
+
from workbench.algorithms.models.noise_model import NoiseModel # noqa: F401 (avoid circular import)
|
|
189
|
+
from workbench.api import Model, FeatureSet # noqa: F401 (avoid circular import)
|
|
190
|
+
|
|
191
|
+
# Get Feature and Target Columns from the existing given Model
|
|
192
|
+
features = model.features()
|
|
193
|
+
target = model.target()
|
|
194
|
+
|
|
195
|
+
# Backtrack our FeatureSet to get the ID column
|
|
196
|
+
fs = FeatureSet(model.get_input())
|
|
197
|
+
id_column = fs.id_column
|
|
198
|
+
|
|
199
|
+
# Create the NoiseModel from both the full FeatureSet and the Model training data
|
|
200
|
+
full_df = fs.pull_dataframe()
|
|
201
|
+
model_df = model.training_view().pull_dataframe()
|
|
202
|
+
|
|
203
|
+
# Mark rows that are in the model
|
|
204
|
+
model_ids = set(model_df[id_column])
|
|
205
|
+
full_df["in_model"] = full_df[id_column].isin(model_ids)
|
|
206
|
+
|
|
207
|
+
# Create and return the NoiseModel
|
|
208
|
+
return NoiseModel(full_df, id_column, features, target)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def cleanlab_model_local(model: "Model"):
|
|
212
|
+
"""Create a CleanlabModels instance for detecting data quality issues in a Model's training data.
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
model (Model): The Model used to create the cleanlab models
|
|
216
|
+
|
|
217
|
+
Returns:
|
|
218
|
+
CleanlabModels: Factory providing access to CleanLearning and Datalab models.
|
|
219
|
+
- clean_learning(): CleanLearning model with enhanced get_label_issues()
|
|
220
|
+
- datalab(): Datalab instance with report(), get_issues()
|
|
221
|
+
"""
|
|
222
|
+
from workbench.algorithms.models.cleanlab_model import create_cleanlab_model # noqa: F401 (avoid circular import)
|
|
223
|
+
from workbench.api import Model, FeatureSet # noqa: F401 (avoid circular import)
|
|
224
|
+
|
|
225
|
+
# Get Feature and Target Columns from the existing given Model
|
|
226
|
+
features = model.features()
|
|
227
|
+
target = model.target()
|
|
228
|
+
model_type = model.model_type
|
|
229
|
+
|
|
230
|
+
# Backtrack our FeatureSet to get the ID column
|
|
231
|
+
fs = FeatureSet(model.get_input())
|
|
232
|
+
id_column = fs.id_column
|
|
233
|
+
|
|
234
|
+
# Get the full FeatureSet data
|
|
235
|
+
full_df = fs.pull_dataframe()
|
|
236
|
+
|
|
237
|
+
# Create and return the CleanLearning model
|
|
238
|
+
return create_cleanlab_model(full_df, id_column, features, target, model_type=model_type)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def published_proximity_model(model: "Model", prox_model_name: str, include_all_columns: bool = False) -> "Model":
|
|
242
|
+
"""Create a published proximity model based on the given model
|
|
97
243
|
|
|
98
244
|
Args:
|
|
99
245
|
model (Model): The model to create the proximity model from
|
|
100
246
|
prox_model_name (str): The name of the proximity model to create
|
|
101
|
-
|
|
247
|
+
include_all_columns (bool): Include all DataFrame columns in results (default: False)
|
|
102
248
|
Returns:
|
|
103
249
|
Model: The proximity model
|
|
104
250
|
"""
|
|
@@ -121,45 +267,23 @@ def proximity_model(model: "Model", prox_model_name: str, track_columns: list =
|
|
|
121
267
|
description=f"Proximity Model for {model.name}",
|
|
122
268
|
tags=["proximity", model.name],
|
|
123
269
|
custom_script=script_path,
|
|
124
|
-
custom_args={"
|
|
270
|
+
custom_args={"include_all_columns": include_all_columns},
|
|
125
271
|
)
|
|
126
272
|
return prox_model
|
|
127
273
|
|
|
128
274
|
|
|
129
|
-
def
|
|
130
|
-
"""Create a Uncertainty Quantification (UQ) model based on the given model
|
|
131
|
-
|
|
132
|
-
Args:
|
|
133
|
-
model (Model): The model to create the UQ model from
|
|
134
|
-
uq_model_name (str): The name of the UQ model to create
|
|
135
|
-
train_all_data (bool, optional): Whether to train the UQ model on all data (default: False)
|
|
136
|
-
|
|
137
|
-
Returns:
|
|
138
|
-
Model: The UQ model
|
|
275
|
+
def safe_extract_tarfile(tar_path: str, extract_path: str) -> None:
|
|
139
276
|
"""
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
# Get the custom script path for the UQ model
|
|
143
|
-
script_path = get_custom_script_path("uq_models", "mapie.template")
|
|
144
|
-
|
|
145
|
-
# Get Feature and Target Columns from the existing given Model
|
|
146
|
-
features = model.features()
|
|
147
|
-
target = model.target()
|
|
277
|
+
Extract a tarball safely, using data filter if available.
|
|
148
278
|
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
tags=["uq", model.name],
|
|
158
|
-
train_all_data=train_all_data,
|
|
159
|
-
custom_script=script_path,
|
|
160
|
-
custom_args={"id_column": fs.id_column, "track_columns": [target]},
|
|
161
|
-
)
|
|
162
|
-
return uq_model
|
|
279
|
+
The filter parameter was backported to Python 3.8+, 3.9+, 3.10.13+, 3.11+
|
|
280
|
+
as a security patch, but may not be present in older patch versions.
|
|
281
|
+
"""
|
|
282
|
+
with tarfile.open(tar_path, "r:gz") as tar:
|
|
283
|
+
if hasattr(tarfile, "data_filter"):
|
|
284
|
+
tar.extractall(path=extract_path, filter="data")
|
|
285
|
+
else:
|
|
286
|
+
tar.extractall(path=extract_path)
|
|
163
287
|
|
|
164
288
|
|
|
165
289
|
def load_category_mappings_from_s3(model_artifact_uri: str) -> Optional[dict]:
|
|
@@ -180,8 +304,7 @@ def load_category_mappings_from_s3(model_artifact_uri: str) -> Optional[dict]:
|
|
|
180
304
|
wr.s3.download(path=model_artifact_uri, local_file=local_tar_path)
|
|
181
305
|
|
|
182
306
|
# Extract tarball
|
|
183
|
-
|
|
184
|
-
tar.extractall(path=tmpdir, filter="data")
|
|
307
|
+
safe_extract_tarfile(local_tar_path, tmpdir)
|
|
185
308
|
|
|
186
309
|
# Look for category mappings in base directory only
|
|
187
310
|
mappings_path = os.path.join(tmpdir, "category_mappings.json")
|
|
@@ -197,6 +320,63 @@ def load_category_mappings_from_s3(model_artifact_uri: str) -> Optional[dict]:
|
|
|
197
320
|
return category_mappings
|
|
198
321
|
|
|
199
322
|
|
|
323
|
+
def load_hyperparameters_from_s3(model_artifact_uri: str) -> Optional[dict]:
|
|
324
|
+
"""
|
|
325
|
+
Download and extract hyperparameters from a model artifact in S3.
|
|
326
|
+
|
|
327
|
+
Args:
|
|
328
|
+
model_artifact_uri (str): S3 URI of the model artifact (model.tar.gz).
|
|
329
|
+
|
|
330
|
+
Returns:
|
|
331
|
+
dict: The loaded hyperparameters or None if not found.
|
|
332
|
+
"""
|
|
333
|
+
hyperparameters = None
|
|
334
|
+
|
|
335
|
+
with tempfile.TemporaryDirectory() as tmpdir:
|
|
336
|
+
# Download model artifact
|
|
337
|
+
local_tar_path = os.path.join(tmpdir, "model.tar.gz")
|
|
338
|
+
wr.s3.download(path=model_artifact_uri, local_file=local_tar_path)
|
|
339
|
+
|
|
340
|
+
# Extract tarball
|
|
341
|
+
safe_extract_tarfile(local_tar_path, tmpdir)
|
|
342
|
+
|
|
343
|
+
# Look for hyperparameters in base directory only
|
|
344
|
+
hyperparameters_path = os.path.join(tmpdir, "hyperparameters.json")
|
|
345
|
+
|
|
346
|
+
if os.path.exists(hyperparameters_path):
|
|
347
|
+
try:
|
|
348
|
+
with open(hyperparameters_path, "r") as f:
|
|
349
|
+
hyperparameters = json.load(f)
|
|
350
|
+
log.info(f"Loaded hyperparameters from {hyperparameters_path}")
|
|
351
|
+
except Exception as e:
|
|
352
|
+
log.warning(f"Failed to load hyperparameters from {hyperparameters_path}: {e}")
|
|
353
|
+
|
|
354
|
+
return hyperparameters
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def get_model_hyperparameters(workbench_model: Any) -> Optional[dict]:
|
|
358
|
+
"""Get the hyperparameters used to train a Workbench model.
|
|
359
|
+
|
|
360
|
+
This retrieves the hyperparameters.json file from the model artifacts
|
|
361
|
+
that was saved during model training.
|
|
362
|
+
|
|
363
|
+
Args:
|
|
364
|
+
workbench_model: Workbench model object
|
|
365
|
+
|
|
366
|
+
Returns:
|
|
367
|
+
dict: The hyperparameters used during training, or None if not found
|
|
368
|
+
"""
|
|
369
|
+
# Get the model artifact URI
|
|
370
|
+
model_artifact_uri = workbench_model.model_data_url()
|
|
371
|
+
|
|
372
|
+
if model_artifact_uri is None:
|
|
373
|
+
log.warning(f"No model artifact found for {workbench_model.uuid}")
|
|
374
|
+
return None
|
|
375
|
+
|
|
376
|
+
log.info(f"Loading hyperparameters from {model_artifact_uri}")
|
|
377
|
+
return load_hyperparameters_from_s3(model_artifact_uri)
|
|
378
|
+
|
|
379
|
+
|
|
200
380
|
def uq_metrics(df: pd.DataFrame, target_col: str) -> Dict[str, Any]:
|
|
201
381
|
"""
|
|
202
382
|
Evaluate uncertainty quantification model with essential metrics.
|
|
@@ -217,37 +397,51 @@ def uq_metrics(df: pd.DataFrame, target_col: str) -> Dict[str, Any]:
|
|
|
217
397
|
if "prediction" not in df.columns:
|
|
218
398
|
raise ValueError("Prediction column 'prediction' not found in DataFrame.")
|
|
219
399
|
|
|
400
|
+
# Drop rows with NaN predictions (e.g., from models that can't handle missing features)
|
|
401
|
+
n_total = len(df)
|
|
402
|
+
df = df.dropna(subset=["prediction", target_col])
|
|
403
|
+
n_valid = len(df)
|
|
404
|
+
if n_valid < n_total:
|
|
405
|
+
log.info(f"UQ metrics: dropped {n_total - n_valid} rows with NaN predictions")
|
|
406
|
+
|
|
220
407
|
# --- Coverage and Interval Width ---
|
|
221
408
|
if "q_025" in df.columns and "q_975" in df.columns:
|
|
222
409
|
lower_95, upper_95 = df["q_025"], df["q_975"]
|
|
223
410
|
lower_90, upper_90 = df["q_05"], df["q_95"]
|
|
224
411
|
lower_80, upper_80 = df["q_10"], df["q_90"]
|
|
412
|
+
lower_68 = df.get("q_16", df["q_10"]) # fallback to 80% interval
|
|
413
|
+
upper_68 = df.get("q_84", df["q_90"]) # fallback to 80% interval
|
|
225
414
|
lower_50, upper_50 = df["q_25"], df["q_75"]
|
|
226
415
|
elif "prediction_std" in df.columns:
|
|
227
416
|
lower_95 = df["prediction"] - 1.96 * df["prediction_std"]
|
|
228
417
|
upper_95 = df["prediction"] + 1.96 * df["prediction_std"]
|
|
418
|
+
lower_90 = df["prediction"] - 1.645 * df["prediction_std"]
|
|
419
|
+
upper_90 = df["prediction"] + 1.645 * df["prediction_std"]
|
|
420
|
+
lower_80 = df["prediction"] - 1.282 * df["prediction_std"]
|
|
421
|
+
upper_80 = df["prediction"] + 1.282 * df["prediction_std"]
|
|
422
|
+
lower_68 = df["prediction"] - 1.0 * df["prediction_std"]
|
|
423
|
+
upper_68 = df["prediction"] + 1.0 * df["prediction_std"]
|
|
229
424
|
lower_50 = df["prediction"] - 0.674 * df["prediction_std"]
|
|
230
425
|
upper_50 = df["prediction"] + 0.674 * df["prediction_std"]
|
|
231
426
|
else:
|
|
232
427
|
raise ValueError(
|
|
233
428
|
"Either quantile columns (q_025, q_975, q_25, q_75) or 'prediction_std' column must be present."
|
|
234
429
|
)
|
|
430
|
+
median_std = df["prediction_std"].median()
|
|
235
431
|
coverage_95 = np.mean((df[target_col] >= lower_95) & (df[target_col] <= upper_95))
|
|
236
432
|
coverage_90 = np.mean((df[target_col] >= lower_90) & (df[target_col] <= upper_90))
|
|
237
433
|
coverage_80 = np.mean((df[target_col] >= lower_80) & (df[target_col] <= upper_80))
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
434
|
+
coverage_68 = np.mean((df[target_col] >= lower_68) & (df[target_col] <= upper_68))
|
|
435
|
+
median_width_95 = np.median(upper_95 - lower_95)
|
|
436
|
+
median_width_90 = np.median(upper_90 - lower_90)
|
|
437
|
+
median_width_80 = np.median(upper_80 - lower_80)
|
|
438
|
+
median_width_50 = np.median(upper_50 - lower_50)
|
|
439
|
+
median_width_68 = np.median(upper_68 - lower_68)
|
|
243
440
|
|
|
244
441
|
# --- CRPS (measures calibration + sharpness) ---
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
mean_crps = np.mean(crps)
|
|
249
|
-
else:
|
|
250
|
-
mean_crps = np.nan
|
|
442
|
+
z = (df[target_col] - df["prediction"]) / df["prediction_std"]
|
|
443
|
+
crps = df["prediction_std"] * (z * (2 * norm.cdf(z) - 1) + 2 * norm.pdf(z) - 1 / np.sqrt(np.pi))
|
|
444
|
+
mean_crps = np.mean(crps)
|
|
251
445
|
|
|
252
446
|
# --- Interval Score @ 95% (penalizes miscoverage) ---
|
|
253
447
|
alpha_95 = 0.05
|
|
@@ -258,44 +452,50 @@ def uq_metrics(df: pd.DataFrame, target_col: str) -> Dict[str, Any]:
|
|
|
258
452
|
)
|
|
259
453
|
mean_is_95 = np.mean(is_95)
|
|
260
454
|
|
|
261
|
-
# ---
|
|
455
|
+
# --- Interval to Error Correlation ---
|
|
262
456
|
abs_residuals = np.abs(df[target_col] - df["prediction"])
|
|
263
|
-
|
|
264
|
-
|
|
457
|
+
width_68 = upper_68 - lower_68
|
|
458
|
+
|
|
459
|
+
# Spearman correlation for robustness
|
|
460
|
+
interval_to_error_corr = spearmanr(width_68, abs_residuals)[0]
|
|
265
461
|
|
|
266
462
|
# Collect results
|
|
267
463
|
results = {
|
|
268
|
-
"
|
|
269
|
-
"coverage_90": coverage_90,
|
|
464
|
+
"coverage_68": coverage_68,
|
|
270
465
|
"coverage_80": coverage_80,
|
|
271
|
-
"
|
|
272
|
-
"
|
|
273
|
-
"
|
|
274
|
-
"
|
|
275
|
-
"
|
|
276
|
-
"
|
|
466
|
+
"coverage_90": coverage_90,
|
|
467
|
+
"coverage_95": coverage_95,
|
|
468
|
+
"median_std": median_std,
|
|
469
|
+
"median_width_50": median_width_50,
|
|
470
|
+
"median_width_68": median_width_68,
|
|
471
|
+
"median_width_80": median_width_80,
|
|
472
|
+
"median_width_90": median_width_90,
|
|
473
|
+
"median_width_95": median_width_95,
|
|
474
|
+
"interval_to_error_corr": interval_to_error_corr,
|
|
277
475
|
"n_samples": len(df),
|
|
278
476
|
}
|
|
279
477
|
|
|
280
478
|
print("\n=== UQ Metrics ===")
|
|
281
|
-
print(f"Coverage @
|
|
282
|
-
print(f"Coverage @ 90%: {coverage_90:.3f} (target: 0.90)")
|
|
479
|
+
print(f"Coverage @ 68%: {coverage_68:.3f} (target: 0.68)")
|
|
283
480
|
print(f"Coverage @ 80%: {coverage_80:.3f} (target: 0.80)")
|
|
284
|
-
print(f"Coverage @
|
|
285
|
-
print(f"
|
|
286
|
-
print(f"
|
|
287
|
-
print(f"
|
|
288
|
-
print(f"
|
|
481
|
+
print(f"Coverage @ 90%: {coverage_90:.3f} (target: 0.90)")
|
|
482
|
+
print(f"Coverage @ 95%: {coverage_95:.3f} (target: 0.95)")
|
|
483
|
+
print(f"Median Prediction StdDev: {median_std:.3f}")
|
|
484
|
+
print(f"Median 50% Width: {median_width_50:.3f}")
|
|
485
|
+
print(f"Median 68% Width: {median_width_68:.3f}")
|
|
486
|
+
print(f"Median 80% Width: {median_width_80:.3f}")
|
|
487
|
+
print(f"Median 90% Width: {median_width_90:.3f}")
|
|
488
|
+
print(f"Median 95% Width: {median_width_95:.3f}")
|
|
289
489
|
print(f"CRPS: {mean_crps:.3f} (lower is better)")
|
|
290
490
|
print(f"Interval Score 95%: {mean_is_95:.3f} (lower is better)")
|
|
291
|
-
print(f"
|
|
491
|
+
print(f"Interval/Error Corr: {interval_to_error_corr:.3f} (higher is better, target: >0.5)")
|
|
292
492
|
print(f"Samples: {len(df)}")
|
|
293
493
|
return results
|
|
294
494
|
|
|
295
495
|
|
|
296
496
|
if __name__ == "__main__":
|
|
297
497
|
"""Exercise the Model Utilities"""
|
|
298
|
-
from workbench.api import Model
|
|
498
|
+
from workbench.api import Model
|
|
299
499
|
|
|
300
500
|
# Get the instance information
|
|
301
501
|
print(model_instance_info())
|
|
@@ -310,24 +510,11 @@ if __name__ == "__main__":
|
|
|
310
510
|
# Get the custom script path
|
|
311
511
|
print(get_custom_script_path("chem_info", "molecular_descriptors.py"))
|
|
312
512
|
|
|
313
|
-
# Test
|
|
513
|
+
# Test loading hyperparameters
|
|
314
514
|
m = Model("aqsol-regression")
|
|
515
|
+
hyperparams = get_model_hyperparameters(m)
|
|
516
|
+
print(hyperparams)
|
|
517
|
+
|
|
518
|
+
# Test the proximity model
|
|
315
519
|
# prox_model = proximity_model(m, "aqsol-prox")
|
|
316
520
|
# print(prox_model)#
|
|
317
|
-
|
|
318
|
-
# Test the UQ model
|
|
319
|
-
# uq_model_instance = uq_model(m, "aqsol-uq")
|
|
320
|
-
# print(uq_model_instance)
|
|
321
|
-
# uq_model_instance.to_endpoint()
|
|
322
|
-
|
|
323
|
-
# Test the uq_metrics function
|
|
324
|
-
end = Endpoint("aqsol-uq")
|
|
325
|
-
df = end.auto_inference(capture=True)
|
|
326
|
-
results = uq_metrics(df, target_col="solubility")
|
|
327
|
-
print(results)
|
|
328
|
-
|
|
329
|
-
# Test the uq_metrics function
|
|
330
|
-
end = Endpoint("aqsol-uq-100")
|
|
331
|
-
df = end.auto_inference(capture=True)
|
|
332
|
-
results = uq_metrics(df, target_col="solubility")
|
|
333
|
-
print(results)
|