workbench 0.8.188__py3-none-any.whl → 0.8.190__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.

@@ -1,279 +0,0 @@
1
- # Template Placeholders
2
- TEMPLATE_PARAMS = {
3
- "model_type": "ensemble_regressor",
4
- "target_column": "solubility",
5
- "feature_list": ['molwt', 'mollogp', 'molmr', 'heavyatomcount', 'numhacceptors', 'numhdonors', 'numheteroatoms', 'numrotatablebonds', 'numvalenceelectrons', 'numaromaticrings', 'numsaturatedrings', 'numaliphaticrings', 'ringcount', 'tpsa', 'labuteasa', 'balabanj', 'bertzct'],
6
- "model_metrics_s3_path": "s3://sandbox-sageworks-artifacts/models/aqsol-ensemble/training"
7
- }
8
-
9
- # Imports for XGB Model
10
- import xgboost as xgb
11
- import awswrangler as wr
12
- import numpy as np
13
-
14
- # Model Performance Scores
15
- from sklearn.metrics import (
16
- mean_absolute_error,
17
- r2_score,
18
- root_mean_squared_error
19
- )
20
-
21
- from io import StringIO
22
- import json
23
- import argparse
24
- import os
25
- import pandas as pd
26
-
27
-
28
- # Function to check if dataframe is empty
29
- def check_dataframe(df: pd.DataFrame, df_name: str) -> None:
30
- """
31
- Check if the provided dataframe is empty and raise an exception if it is.
32
-
33
- Args:
34
- df (pd.DataFrame): DataFrame to check
35
- df_name (str): Name of the DataFrame
36
- """
37
- if df.empty:
38
- msg = f"*** The training data {df_name} has 0 rows! ***STOPPING***"
39
- print(msg)
40
- raise ValueError(msg)
41
-
42
- def match_features_case_insensitive(df: pd.DataFrame, model_features: list) -> pd.DataFrame:
43
- """
44
- Matches and renames the DataFrame's column names to match the model's feature names (case-insensitive).
45
- Prioritizes exact case matches first, then falls back to case-insensitive matching if no exact match exists.
46
-
47
- Args:
48
- df (pd.DataFrame): The DataFrame with the original columns.
49
- model_features (list): The desired list of feature names (mixed case allowed).
50
-
51
- Returns:
52
- pd.DataFrame: The DataFrame with renamed columns to match the model's feature names.
53
- """
54
- # Create a mapping for exact and case-insensitive matching
55
- exact_match_set = set(df.columns)
56
- column_map = {}
57
-
58
- # Build the case-insensitive map (if we have any duplicate columns, the first one wins)
59
- for col in df.columns:
60
- lower_col = col.lower()
61
- if lower_col not in column_map:
62
- column_map[lower_col] = col
63
-
64
- # Create a dictionary for renaming
65
- rename_dict = {}
66
- for feature in model_features:
67
- # Check for an exact match first
68
- if feature in exact_match_set:
69
- rename_dict[feature] = feature
70
-
71
- # If not an exact match, fall back to case-insensitive matching
72
- elif feature.lower() in column_map:
73
- rename_dict[column_map[feature.lower()]] = feature
74
-
75
- # Rename the columns in the DataFrame to match the model's feature names
76
- return df.rename(columns=rename_dict)
77
-
78
-
79
- if __name__ == "__main__":
80
- """The main function is for training the XGBoost Quantile Regression models"""
81
-
82
- # Harness Template Parameters
83
- target = TEMPLATE_PARAMS["target_column"]
84
- feature_list = TEMPLATE_PARAMS["feature_list"]
85
- model_metrics_s3_path = TEMPLATE_PARAMS["model_metrics_s3_path"]
86
- models = {}
87
-
88
- # Script arguments for input/output directories
89
- parser = argparse.ArgumentParser()
90
- parser.add_argument("--model-dir", type=str, default=os.environ.get("SM_MODEL_DIR", "/opt/ml/model"))
91
- parser.add_argument("--train", type=str, default=os.environ.get("SM_CHANNEL_TRAIN", "/opt/ml/input/data/train"))
92
- parser.add_argument(
93
- "--output-data-dir", type=str, default=os.environ.get("SM_OUTPUT_DATA_DIR", "/opt/ml/output/data")
94
- )
95
- args = parser.parse_args()
96
-
97
- # Read the training data into DataFrames
98
- training_files = [
99
- os.path.join(args.train, file)
100
- for file in os.listdir(args.train)
101
- if file.endswith(".csv")
102
- ]
103
- print(f"Training Files: {training_files}")
104
-
105
- # Combine files and read them all into a single pandas dataframe
106
- df = pd.concat([pd.read_csv(file, engine="python") for file in training_files])
107
-
108
- # Check if the dataframe is empty
109
- check_dataframe(df, "training_df")
110
-
111
- # Features/Target output
112
- print(f"Target: {target}")
113
- print(f"Features: {str(feature_list)}")
114
- print(f"Data Shape: {df.shape}")
115
-
116
- # Grab our Features and Target with traditional X, y handles
117
- y = df[target]
118
- X = df[feature_list]
119
-
120
- # Train 50 models with random 70/30 splits of the data
121
- for model_id in range(50):
122
- # Model Name
123
- model_name = f"m_{model_id:02}"
124
-
125
- # Bootstrap sample (50% with replacement)
126
- sample_size = int(0.5 * len(X))
127
- bootstrap_indices = np.random.choice(len(X), size=sample_size, replace=True)
128
- X_train, y_train = X.iloc[bootstrap_indices], y.iloc[bootstrap_indices]
129
- print(f"Training Model {model_name} with {len(X_train)} rows")
130
- model = xgb.XGBRegressor(reg_alpha=0.1, reg_lambda=1.0)
131
- model.fit(X_train, y_train)
132
-
133
- # Store the model
134
- models[model_name] = model
135
-
136
- # Run predictions for each model
137
- all_predictions = {model_name: model.predict(X) for model_name, model in models.items()}
138
-
139
- # Create a copy of the provided DataFrame and add the new columns
140
- result_df = df[[target]].copy()
141
-
142
- # Add the model predictions to the DataFrame
143
- for name, preds in all_predictions.items():
144
- result_df[name] = preds
145
-
146
- # Add the main prediction to the DataFrame (mean of all models)
147
- result_df["prediction"] = result_df[[name for name in result_df.columns if name.startswith("m_")]].mean(axis=1)
148
-
149
- # Now compute residuals on the rmse prediction
150
- result_df["residual"] = result_df[target] - result_df["prediction"]
151
- result_df["residual_abs"] = result_df["residual"].abs()
152
-
153
-
154
- # Save the results dataframe to S3
155
- wr.s3.to_csv(
156
- result_df,
157
- path=f"{model_metrics_s3_path}/validation_predictions.csv",
158
- index=False,
159
- )
160
-
161
- # Report Performance Metrics
162
- rmse = root_mean_squared_error(result_df[target], result_df["prediction"])
163
- mae = mean_absolute_error(result_df[target], result_df["prediction"])
164
- r2 = r2_score(result_df[target], result_df["prediction"])
165
- print(f"RMSE: {rmse:.3f}")
166
- print(f"MAE: {mae:.3f}")
167
- print(f"R2: {r2:.3f}")
168
- print(f"NumRows: {len(result_df)}")
169
-
170
- # Now save the models
171
- for name, model in models.items():
172
- model_path = os.path.join(args.model_dir, f"{name}.json")
173
- print(f"Saving model: {model_path}")
174
- model.save_model(model_path)
175
-
176
- # Also save the features (this will validate input during predictions)
177
- with open(os.path.join(args.model_dir, "feature_columns.json"), "w") as fp:
178
- json.dump(feature_list, fp)
179
-
180
-
181
- def model_fn(model_dir) -> dict:
182
- """Deserialized and return all the fitted models from the model directory.
183
-
184
- Args:
185
- model_dir (str): The directory where the models are stored.
186
-
187
- Returns:
188
- dict: A dictionary of the models.
189
- """
190
-
191
- # Load ALL the models from the model directory
192
- models = {}
193
- for file in os.listdir(model_dir):
194
- if file.startswith("m_") and file.endswith(".json"): # The Quantile models
195
- # Load the model
196
- model_path = os.path.join(model_dir, file)
197
- print(f"Loading model: {model_path}")
198
- model = xgb.XGBRegressor()
199
- model.load_model(model_path)
200
-
201
- # Store the model
202
- m_name = os.path.splitext(file)[0]
203
- models[m_name] = model
204
-
205
- # Return all the models
206
- return models
207
-
208
-
209
- def input_fn(input_data, content_type):
210
- """Parse input data and return a DataFrame."""
211
- if not input_data:
212
- raise ValueError("Empty input data is not supported!")
213
-
214
- # Decode bytes to string if necessary
215
- if isinstance(input_data, bytes):
216
- input_data = input_data.decode("utf-8")
217
-
218
- if "text/csv" in content_type:
219
- return pd.read_csv(StringIO(input_data))
220
- elif "application/json" in content_type:
221
- return pd.DataFrame(json.loads(input_data)) # Assumes JSON array of records
222
- else:
223
- raise ValueError(f"{content_type} not supported!")
224
-
225
-
226
- def output_fn(output_df, accept_type):
227
- """Supports both CSV and JSON output formats."""
228
- if "text/csv" in accept_type:
229
- csv_output = output_df.fillna("N/A").to_csv(index=False) # CSV with N/A for missing values
230
- return csv_output, "text/csv"
231
- elif "application/json" in accept_type:
232
- return output_df.to_json(orient="records"), "application/json" # JSON array of records (NaNs -> null)
233
- else:
234
- raise RuntimeError(f"{accept_type} accept type is not supported by this script.")
235
-
236
-
237
- def predict_fn(df, models) -> pd.DataFrame:
238
- """Make Predictions with our XGB Quantile Regression Model
239
-
240
- Args:
241
- df (pd.DataFrame): The input DataFrame
242
- models (dict): The dictionary of models to use for predictions
243
-
244
- Returns:
245
- pd.DataFrame: The DataFrame with the predictions added
246
- """
247
-
248
- # Grab our feature columns (from training)
249
- model_dir = os.environ.get("SM_MODEL_DIR", "/opt/ml/model")
250
- with open(os.path.join(model_dir, "feature_columns.json")) as fp:
251
- model_features = json.load(fp)
252
- print(f"Model Features: {model_features}")
253
-
254
- # We're going match features in a case-insensitive manner, accounting for all the permutations
255
- # - Model has a feature list that's any case ("Id", "taCos", "cOunT", "likes_tacos")
256
- # - Incoming data has columns that are mixed case ("ID", "Tacos", "Count", "Likes_Tacos")
257
- matched_df = match_features_case_insensitive(df, model_features)
258
-
259
- # Predict the features against all the models
260
- for name, model in models.items():
261
- df[name] = model.predict(matched_df[model_features])
262
-
263
- # Add quantiles for consistency with other UQ models
264
- df["q_025"] = df[[name for name in df.columns if name.startswith("m_")]].quantile(0.025, axis=1)
265
- df["q_975"] = df[[name for name in df.columns if name.startswith("m_")]].quantile(0.975, axis=1)
266
- df["q_25"] = df[[name for name in df.columns if name.startswith("m_")]].quantile(0.25, axis=1)
267
- df["q_75"] = df[[name for name in df.columns if name.startswith("m_")]].quantile(0.75, axis=1)
268
-
269
- # Compute the mean, min, max and stddev of the predictions
270
- df["prediction"] = df[[name for name in df.columns if name.startswith("m_")]].mean(axis=1)
271
- df["p_min"] = df[[name for name in df.columns if name.startswith("m_")]].min(axis=1)
272
- df["p_max"] = df[[name for name in df.columns if name.startswith("m_")]].max(axis=1)
273
- df["prediction_std"] = df[[name for name in df.columns if name.startswith("m_")]].std(axis=1)
274
-
275
- # Reorganize the columns so they are in alphabetical order
276
- df = df.reindex(sorted(df.columns), axis=1)
277
-
278
- # All done, return the DataFrame
279
- return df