by the Oracle AutoMLx Team
Regression Demo Notebook.
Copyright © 2025, Oracle and/or its affiliates.
Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
In this notebook we will build a regressor using the Oracle AutoMLx tool for the public California Housing dataset to predict the value of house prices. We explore the various options provided by the Oracle AutoMLx tool, allowing the user to control the AutoMLx training process. We finally evaluate the different models trained by AutoMLx. Depending on the dataset size and the machine running it, it can take about tens of minutes. The dataset is sampled down for a snappier demo, with the option to run it with the full dataset. We finally provide an overview of the possibilities that Oracle AutoMLx provides for explaining the predictions of the tuned model.
Data analytics and modeling problems using Machine Learning (ML) are becoming popular and often rely on data science expertise to build accurate ML models. Such modeling tasks primarily involve the following steps:
All of these steps are significantly time consuming and heavily rely on data scientist expertise. Unfortunately, to make this problem harder, the best feature subset, model, and hyperparameter choice widely varies with the dataset and the prediction task. Hence, there is no one-size-fits-all solution to achieve reasonably good model performance. Using a simple Python API, AutoML can quickly jump-start the datascience process with an accurately-tuned model and appropriate features for a given prediction task.
%matplotlib inline
%load_ext autoreload
%autoreload 2
Load the required modules.
import time
import datetime
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import plotly.figure_factory as ff
from sklearn.datasets import fetch_california_housing
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
# Settings for plots
plt.rcParams['figure.figsize'] = [10, 7]
plt.rcParams['font.size'] = 15
import automlx
from automlx import init
Dataset details are available here: https://scikit-learn.org/stable/datasets/real_world.html#california-housing-dataset. The goal is to predict the median price of a house given some features.
X, y = fetch_california_housing(return_X_y=True)
ds = fetch_california_housing(return_X_y=False)
df = pd.concat([pd.DataFrame(X, columns=ds.feature_names),
pd.DataFrame(y.ravel(), columns=['Median Price'])], axis=1)
target_col='Median Price'
df.shape
(20640, 9)
df.head()
MedInc | HouseAge | AveRooms | AveBedrms | Population | AveOccup | Latitude | Longitude | Median Price | |
---|---|---|---|---|---|---|---|---|---|
0 | 8.3252 | 41.0 | 6.984127 | 1.023810 | 322.0 | 2.555556 | 37.88 | -122.23 | 4.526 |
1 | 8.3014 | 21.0 | 6.238137 | 0.971880 | 2401.0 | 2.109842 | 37.86 | -122.22 | 3.585 |
2 | 7.2574 | 52.0 | 8.288136 | 1.073446 | 496.0 | 2.802260 | 37.85 | -122.24 | 3.521 |
3 | 5.6431 | 52.0 | 5.817352 | 1.073059 | 558.0 | 2.547945 | 37.85 | -122.25 | 3.413 |
4 | 3.8462 | 52.0 | 6.281853 | 1.081081 | 565.0 | 2.181467 | 37.85 | -122.25 | 3.422 |
We first display the density of the target median price.
# drop unlabeled data in train/test dataset
df = df[df[target_col].notna()]
df[target_col]
fig = ff.create_distplot([df[target_col]], group_labels=[target_col], show_hist=False, show_rug=False)
fig.update_layout(
xaxis_title=target_col,
yaxis_title="Density",
showlegend=False)
fig.update_xaxes()
fig.show()
We now separate the targets (y
) from the training features (X
) and split the dataset into training (70%) and test (30%) datasets. The training set will be used to create a Machine Learning model using Oracle AutoMLx, and the test set will be used to evaluate the model's performance on unseen data.
X_full = df.drop(target_col, axis=1)
y_full = df[target_col]
X_train, X_test, y_train, y_test = train_test_split(X_full, y_full, test_size=0.3, random_state=7)
X_train.shape, X_test.shape
((14448, 8), (6192, 8))
The AutoMLx package offers the function init
, which allows to initialize the parallelization engine.
init(engine='ray')
[2025-05-22 05:35:26,721] [automlx.backend] Overwriting ray session directory to /tmp/7dliinvt/ray, which will be deleted at engine shutdown. If you wish to retain ray logs, provide _temp_dir in ray_setup dict of engine_opts when initializing the AutoMLx engine.
The Oracle AutoMLx solution provides a pipeline that automatically finds a tuned model given a prediction task and a training dataset. In particular it allows to find a tuned model for any supervised prediction task, for example, classification or regression, where the target can be binary, categorical or real-valued.
AutoML consists of five main steps:
All these pieces are readily combined into a simple AutoML pipeline which automates the entire Machine Learning process with minimal user input/interaction.
The AutoMLx API is quite simple to work with. We create an instance of AutoMLx pipeline. Next, the training data is passed to the fit()
function which successively executes the previously mentioned modules.
est1 = automlx.Pipeline(task='regression')
est1.fit(X_train, y_train)
[2025-05-22 05:35:30,856] [automlx.interface] Dataset shape: (14448,8) [2025-05-22 05:35:33,431] [sanerec.autotuning.parameter] Hyperparameter epsilon autotune range is set to its validation range. This could lead to long training times [2025-05-22 05:35:33,745] [sanerec.autotuning.parameter] Hyperparameter repeat_quality_threshold autotune range is set to its validation range. This could lead to long training times [2025-05-22 05:35:33,752] [sanerec.autotuning.parameter] Hyperparameter scope autotune range is set to its validation range. This could lead to long training times [2025-05-22 05:35:33,823] [automlx.data_transform] Running preprocessing. Number of features: 9 [2025-05-22 05:35:33,985] [automlx.data_transform] Preprocessing completed. Took 0.162 secs [2025-05-22 05:35:34,029] [automlx.process] Running Model Generation [2025-05-22 05:35:34,077] [automlx.process] KNeighborsRegressor is disabled. The KNeighborsRegressor model is only recommended for datasets with less than 10000 samples and 1000 features. [2025-05-22 05:35:34,078] [automlx.process] SVR is disabled. The SVR model is only recommended for datasets with less than 10000 samples and 1000 features. [2025-05-22 05:35:34,079] [automlx.process] Model Generation completed. [2025-05-22 05:35:34,148] [automlx.model_selection] Running Model Selection [2025-05-22 05:36:14,592] [automlx.model_selection] Model Selection completed - Took 40.444 sec - Selected models: [['LGBMRegressor']] [2025-05-22 05:36:14,633] [automlx.adaptive_sampling] Running Adaptive Sampling. Dataset shape: (14448,9). [2025-05-22 05:36:17,686] [automlx.trials] Adaptive Sampling completed - Took 3.0524 sec. [2025-05-22 05:36:17,782] [automlx.feature_selection] Starting feature ranking for LGBMRegressor [2025-05-22 05:36:26,157] [automlx.feature_selection] Feature Selection completed. Took 8.402 secs. [2025-05-22 05:36:26,215] [automlx.trials] Running Model Tuning for ['LGBMRegressor'] [2025-05-22 05:37:18,586] [automlx.trials] Best parameters for LGBMRegressor: {'num_leaves': 31, 'boosting_type': 'gbdt', 'subsample': 1, 'colsample_bytree': 0.7952797110155084, 'max_depth': 63, 'reg_alpha': 0, 'reg_lambda': 0, 'n_estimators': 377, 'learning_rate': 0.1, 'min_child_weight': 0.001} [2025-05-22 05:37:18,587] [automlx.trials] Model Tuning completed. Took: 52.372 secs [2025-05-22 05:37:31,673] [automlx.interface] Re-fitting pipeline [2025-05-22 05:37:31,687] [automlx.final_fit] Skipping updating parameter seed, already fixed by FinalFit_5653c38b-7 [2025-05-22 05:37:33,814] [automlx.interface] AutoMLx completed.
<automlx._interface.regressor.AutoRegressor at 0x14bb351c0970>
A model is then generated (est1
) and can be used for prediction tasks. We use the mean_squared_error
scoring metric to evaluate the performance of this model on unseen data (X_test
).
y_pred = est1.predict(X_test)
score_default = mean_squared_error(y_test, y_pred)
print(f'Mean squared error on test data : {score_default}')
Mean squared error on test data : 0.2007340045930796
During the Oracle AutoMLx process, a summary of the optimization process is logged, containing:
AutoMLx provides a print_summary
API to output all the different trials performed.
est1.print_summary()
(14448, 8) |
None |
RepeatedKFoldSplit(Shuffle=True, Seed=7, number of splits=5, number of repeats=2) |
neg_mean_squared_error |
LGBMRegressor |
{'num_leaves': 31, 'boosting_type': 'gbdt', 'subsample': 1, 'colsample_bytree': 0.7952797110155084, 'max_depth': 63, 'reg_alpha': 0, 'reg_lambda': 0, 'n_estimators': 377, 'learning_rate': 0.1, 'min_child_weight': 0.001} |
24.4.1 |
3.9.21 (main, Dec 11 2024, 16:24:11) \n[GCC 11.2.0] |
Step | # Samples | # Features | Algorithm | Hyperparameters | Score (neg_mean_squared_error) | Runtime (Seconds) | Memory Usage (GB) | Finished |
---|---|---|---|---|---|---|---|---|
Model Selection | 11559 | 8 | LGBMRegressor | {'num_leaves': 31, 'boosting_type': 'gbdt', 'subsample': 1, 'colsample_bytree': 1, 'max_depth': 63, 'reg_alpha': 0, 'reg_lambda': 0, 'n_estimators': 100, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -0.2183 | 5.3076 | 0.3075 | Thu May 22 05:35:44 2025 |
Model Selection | 11559 | 8 | XGBRegressor | {'n_estimators': 100, 'min_child_weight': 1, 'reg_alpha': 0, 'booster': 'gbtree', 'max_depth': 6, 'learning_rate': 0.1, 'reg_lambda': 1} | -0.2283 | 16.4569 | 0.3459 | Thu May 22 05:35:56 2025 |
Model Selection | 11559 | 8 | RandomForestRegressor | {'n_estimators': 100, 'min_samples_split': 0.0003, 'min_samples_leaf': 0.00015, 'max_features': 0.777777778} | -0.2585 | 34.3275 | 0.3597 | Thu May 22 05:35:48 2025 |
Model Selection | 11559 | 8 | ExtraTreesRegressor | {'n_estimators': 100, 'min_samples_split': 0.00125, 'min_samples_leaf': 0.000625, 'max_features': 0.777777778} | -0.2983 | 6.5971 | 0.2965 | Thu May 22 05:35:43 2025 |
Model Selection | 11559 | 8 | DecisionTreeRegressor | {'min_samples_split': 0.004, 'min_samples_leaf': 0.002, 'max_features': 1.0} | -0.3877 | 3.4246 | 0.2808 | Thu May 22 05:35:42 2025 |
Model Selection | 11559 | 8 | LinearRegression | {} | -0.5296 | 0.7690 | 0.3102 | Thu May 22 05:35:43 2025 |
Model Selection | 11559 | 8 | AdaBoostRegressor | {'learning_rate': 0.667, 'n_estimators': 50} | -0.701 | 13.9089 | 0.2777 | Thu May 22 05:35:42 2025 |
Model Selection | 11559 | 8 | LinearSVR | {'C': 1.0} | -1.6878 | 6.5363 | 0.3188 | Thu May 22 05:35:44 2025 |
Model Selection | 11558 | 8 | TorchMLPRegressor | {'optimizer_class': 'Adam', 'shuffle_dataset_each_epoch': True, 'optimizer_params': {}, 'criterion_class': None, 'criterion_params': {}, 'scheduler_class': None, 'scheduler_params': {}, 'batch_size': 128, 'lr': 0.001, 'epochs': 18, 'input_transform': 'auto', 'tensorboard_dir': None, 'use_tqdm': None, 'prediction_batch_size': 128, 'prediction_input_transform': 'auto', 'shuffling_buffer_size': None, 'depth': 4, 'num_logits': 1000, 'div_factor': 2, 'activation': 'ReLU', 'dropout': 0.1} | -3.1322 | 256.0426 | 0.6121 | Thu May 22 05:36:14 2025 |
Adaptive Sampling | 11559 | 8 | AdaptiveSamplingStage_LGBMRegressor | {'num_leaves': 31, 'boosting_type': 'gbdt', 'subsample': 1, 'colsample_bytree': 1, 'max_depth': 63, 'reg_alpha': 0, 'reg_lambda': 0, 'n_estimators': 100, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -0.2183 | 2.8107 | 0.6115 | Thu May 22 05:36:17 2025 |
... | ... | ... | ... | ... | ... | ... | ... | ... |
Model Tuning | 11559 | 6 | LGBMRegressor | {'num_leaves': 7, 'boosting_type': 'gbdt', 'subsample': 0.4, 'colsample_bytree': 0.4, 'max_depth': 2, 'reg_alpha': 1e-10, 'reg_lambda': 9.999999990000003e-07, 'n_estimators': 5, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -1.1075 | 0.7727 | 0.6235 | Thu May 22 05:36:45 2025 |
Model Tuning | 11559 | 6 | LGBMRegressor | {'num_leaves': 7, 'boosting_type': 'gbdt', 'subsample': 0.4, 'colsample_bytree': 0.4, 'max_depth': 2, 'reg_alpha': 9.999999990000003e-07, 'reg_lambda': 1e-10, 'n_estimators': 5, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -1.1075 | 0.7874 | 0.6233 | Thu May 22 05:36:44 2025 |
Model Tuning | 11559 | 6 | LGBMRegressor | {'num_leaves': 7, 'boosting_type': 'gbdt', 'subsample': 0.4, 'colsample_bytree': 0.4, 'max_depth': 2, 'reg_alpha': 1e-10, 'reg_lambda': 1.7784127779939314e-05, 'n_estimators': 5, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -1.1075 | 0.7908 | 0.6235 | Thu May 22 05:36:46 2025 |
Model Tuning | 11559 | 6 | LGBMRegressor | {'num_leaves': 7, 'boosting_type': 'gbdt', 'subsample': 0.4, 'colsample_bytree': 0.4, 'max_depth': 2, 'reg_alpha': 1e-10, 'reg_lambda': 1.8784127778939314e-05, 'n_estimators': 5, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -1.1075 | 0.8087 | 0.6235 | Thu May 22 05:36:46 2025 |
Model Tuning | 11559 | 6 | LGBMRegressor | {'num_leaves': 7, 'boosting_type': 'gbdt', 'subsample': 0.4, 'colsample_bytree': 0.4, 'max_depth': 2, 'reg_alpha': 1.7784127779939314e-05, 'reg_lambda': 1e-10, 'n_estimators': 5, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -1.1075 | 0.8432 | 0.6233 | Thu May 22 05:36:44 2025 |
Model Tuning | 11559 | 6 | LGBMRegressor | {'num_leaves': 7, 'boosting_type': 'gbdt', 'subsample': 0.4, 'colsample_bytree': 0.4, 'max_depth': 2, 'reg_alpha': 1.8784127778939314e-05, 'reg_lambda': 1e-10, 'n_estimators': 5, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -1.1075 | 0.7551 | 0.6233 | Thu May 22 05:36:45 2025 |
Model Tuning | 11559 | 6 | LGBMRegressor | {'num_leaves': 7, 'boosting_type': 'gbdt', 'subsample': 0.4, 'colsample_bytree': 0.4, 'max_depth': 2, 'reg_alpha': 1e-10, 'reg_lambda': 0.005623553830557401, 'n_estimators': 5, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -1.1075 | 0.6737 | 0.6156 | Thu May 22 05:36:46 2025 |
Model Tuning | 11559 | 6 | LGBMRegressor | {'num_leaves': 7, 'boosting_type': 'gbdt', 'subsample': 0.4, 'colsample_bytree': 0.4, 'max_depth': 2, 'reg_alpha': 1e-10, 'reg_lambda': 0.0056245538305564015, 'n_estimators': 5, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -1.1075 | 0.9709 | 0.6156 | Thu May 22 05:36:46 2025 |
Model Tuning | 11559 | 6 | LGBMRegressor | {'num_leaves': 7, 'boosting_type': 'gbdt', 'subsample': 0.4, 'colsample_bytree': 0.4, 'max_depth': 2, 'reg_alpha': 0.005623553830557401, 'reg_lambda': 1e-10, 'n_estimators': 5, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -1.1075 | 0.8067 | 0.6233 | Thu May 22 05:36:45 2025 |
Model Tuning | 11559 | 6 | LGBMRegressor | {'num_leaves': 7, 'boosting_type': 'gbdt', 'subsample': 0.4, 'colsample_bytree': 0.4, 'max_depth': 2, 'reg_alpha': 0.0056245538305564015, 'reg_lambda': 1e-10, 'n_estimators': 5, 'learning_rate': 0.1, 'min_child_weight': 0.001} | -1.1075 | 0.7816 | 0.6233 | Thu May 22 05:36:45 2025 |
We also provide the capability to visualize the results of each stage of the AutoMLx pipeline.
The plot below shows the scores predicted by Algorithm Selection for each algorithm. The horizontal line shows the average score across all algorithms. Algorithms below the line are colored turquoise, whereas those with a score higher than the mean are colored teal.
# Each trial is a row in a dataframe that contains
# Algorithm, Number of Samples, Number of Features, Hyperparameters, Score, Runtime, Memory Usage, Step as features
trials = est1.completed_trials_summary_[est1.completed_trials_summary_["Step"].str.contains('Model Selection')]
name_of_score_column = f"Score ({est1._inferred_score_metric[0].name})"
trials.replace([np.inf, -np.inf], np.nan, inplace=True)
trials.dropna(subset=[name_of_score_column], inplace = True)
scores = trials[name_of_score_column].tolist()
models = trials['Algorithm'].tolist()
y_margin = 0.10 * (max(scores) - min(scores))
s = pd.Series(scores, index=models).sort_values(ascending=False)
colors = []
for f in s.keys():
if f.strip() == est1.selected_model_.strip():
colors.append('orange')
elif s[f] >= s.mean():
colors.append('teal')
else:
colors.append('turquoise')
fig, ax = plt.subplots(1)
ax.set_title("Algorithm Selection Trials")
ax.set_ylim(min(scores) - y_margin, max(scores) + y_margin)
ax.set_ylabel(est1._inferred_score_metric[0].name)
s.plot.bar(ax=ax, color=colors, edgecolor='black')
ax.axhline(y=s.mean(), color='black', linewidth=0.5)
plt.show()
Following Algorithm Selection, Adaptive Sampling aims to find the smallest dataset sample that can be created without compromising validation set score for the chosen model. This is used to speed up feature selection and tuning; however, the full dataset is still used to train the final model.
# Each trial is a row in a dataframe that contains
# Algorithm, Number of Samples, Number of Features, Hyperparameters, Score, Runtime, Memory Usage, Step as features
trials = est1.completed_trials_summary_[est1.completed_trials_summary_["Step"].str.contains('Adaptive Sampling')]
trials.replace([np.inf, -np.inf], np.nan, inplace=True)
trials.dropna(subset=[name_of_score_column], inplace = True)
scores = trials[name_of_score_column].tolist()
n_samples = trials['# Samples'].tolist()
y_margin = 0.10 * (max(scores) - min(scores))
fig, ax = plt.subplots(1)
ax.set_title("Adaptive Sampling ({})".format(est1.selected_model_))
ax.set_xlabel('Dataset sample size')
ax.set_ylabel(est1._inferred_score_metric[0].name)
ax.grid(color='g', linestyle='-', linewidth=0.1)
ax.set_ylim(min(scores) - y_margin, max(scores) + y_margin)
ax.plot(n_samples, scores, 'k:', marker="s", color='teal', markersize=3)
plt.show()
The next step of the pipeline is to find a relevant feature subset to maximize score for the chosen algorithm. AutoMLx Feature Selection follows an intelligent search strategy, looking at various possible feature rankings and subsets, and identifying that smallest feature subset that does not compromise on score for the chosen algorithm. The orange line shows the optimal number of features chosen by Feature Selection.
print(f"Features selected: {est1.selected_features_names_}")
dropped_features = df.drop(est1.selected_features_names_raw_, axis=1).columns
print(f"Features dropped: {dropped_features.to_list()}")
# Each trial is a row in a dataframe that contains
# Algorithm, Number of Samples, Number of Features, Hyperparameters, Score, Runtime, Memory Usage, Step as features
trials = est1.completed_trials_summary_[est1.completed_trials_summary_["Step"].str.contains('Feature Selection')]
trials.replace([np.inf, -np.inf], np.nan, inplace=True)
trials.dropna(subset=[name_of_score_column], inplace = True)
trials.sort_values(by=['# Features'],ascending=True, inplace = True)
scores = trials[name_of_score_column].tolist()
n_features = trials['# Features'].tolist()
y_margin = 0.10 * (max(scores) - min(scores))
fig, ax = plt.subplots(1)
ax.set_title("Feature Selection Trials")
ax.set_xlabel("Number of Features")
ax.set_ylabel(est1._inferred_score_metric[0].name)
ax.grid(color='g', linestyle='-', linewidth=0.1)
ax.set_ylim(min(scores) - y_margin, max(scores) + y_margin)
ax.plot(n_features, scores, 'k:', marker="s", color='teal', markersize=3)
ax.axvline(x=len(est1.selected_features_names_), color='orange', linewidth=2.0)
plt.show()
Features selected: ['AveOccup', 'AveRooms', 'HouseAge', 'Latitude', 'Longitude', 'MedInc'] Features dropped: ['AveBedrms', 'Population', 'Median Price']
Hyperparameter Tuning is the last stage of the AutoMLx pipeline, and focuses on improving the chosen algorithm's score on the reduced dataset (after Adaptive Sampling and Feature Selection). We use a novel iterative algorithm to search across many hyperparameter dimensions, and converge automatically when optimal hyperparameters are identified. Each trial represents a particular hyperparameter configuration for the selected model.
# Each trial is a row in a dataframe that contains
# Algorithm, Number of Samples, Number of Features, Hyperparameters, Score, Runtime, Memory Usage, Step as features
trials = est1.completed_trials_summary_[est1.completed_trials_summary_["Step"].str.contains('Model Tuning')]
trials.replace([np.inf, -np.inf], np.nan, inplace=True)
trials.dropna(subset=[name_of_score_column], inplace = True)
trials.drop(trials[trials['Finished'] == -1].index, inplace = True)
trials['Finished']= trials['Finished'].apply(lambda x: time.mktime(datetime.datetime.strptime(x,
"%a %b %d %H:%M:%S %Y").timetuple()))
trials.sort_values(by=['Finished'],ascending=True, inplace = True)
scores = trials[name_of_score_column].tolist()
score = []
score.append(scores[0])
for i in range(1,len(scores)):
if scores[i]>= score[i-1]:
score.append(scores[i])
else:
score.append(score[i-1])
y_margin = 0.10 * (max(score) - min(score))
fig, ax = plt.subplots(1)
ax.set_title("Hyperparameter Tuning Trials")
ax.set_xlabel("Iteration $n$")
ax.set_ylabel(est1._inferred_score_metric[0].name)
ax.grid(color='g', linestyle='-', linewidth=0.1)
ax.set_ylim(min(score) - y_margin, max(score) + y_margin)
ax.plot(range(1, len(trials) + 1), score, 'k:', marker="s", color='teal', markersize=3)
plt.show()
You can also configure the pipeline with suitable parameters according to your needs.
custom_pipeline = automlx.Pipeline(
task='regression',
model_list=[ # Specify the models you want the AutoMLx to consider
'LinearRegression',
'AdaBoostRegressor',
'XGBRegressor'
],
n_algos_tuned=2, # Choose how many models to tune
min_features=1.0, # Specify minimum features to force the model to use. It can take 3 possible types of values:
# If int, 0 < min_features <= n_features,
# If float, 0 < min_features <= 1.0, 1.0 means disabling feature selection
# If list, names of features to keep, for example ['a', 'b'] means keep features 'a' and 'b'
adaptive_sampling=False, # Disable or enable Adaptive Sampling step. Default to `True`
preprocessing=True, # Disable or enable Preprocessing step. Default to `True`
search_space={ # You can specify the hyper-parameters and ranges we search
'AdaBoostRegressor': {
"n_estimators": {"range": [10, 20], "type": "discrete"}
},
},
max_tuning_trials=2, # The maximum number of tuning trials. Can be integer or Dict (max number for each model)
score_metric='r2', # Any scikit-learn metric or a custom function
)
You can specify a custom validation set that you want AutoMLx to use to evaluate the quality of models and configurations.
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, train_size=0.7, random_state=0)
A few of the advanced settings can be passed directly to the pipeline's fit method, instead of its constructor.
custom_pipeline.fit(
X_train,
y_train,
X_val,
y_val,
time_budget= 20, # Specify time budget in seconds
cv='auto' # Automatically pick a good cross-validation (cv) strategy for the user's dataset.
# Ignored if X_valid and y_valid are provided.
# Can also be:
# - An integer (For example, to use 5-fold cross validation)
# - A list of data indices to use as splits (for advanced, such as time-based splitting)
)
y_pred = custom_pipeline.predict(X_test)
score_modellist = mean_squared_error(y_test, y_pred)
print(f'Prediction error (MSE) on test data : {score_modellist}')
[2025-05-22 05:37:37,569] [automlx.interface] Dataset shape: (14448,8) [2025-05-22 05:37:37,621] [automlx.interface] Adaptive Sampling disabled. [2025-05-22 05:37:37,661] [automlx.data_transform] Running preprocessing. Number of features: 9 [2025-05-22 05:37:37,814] [automlx.data_transform] Preprocessing completed. Took 0.153 secs [2025-05-22 05:37:37,840] [automlx.process] Running Model Generation [2025-05-22 05:37:37,891] [automlx.process] Model Generation completed. [2025-05-22 05:37:37,922] [automlx.model_selection] Running Model Selection [2025-05-22 05:37:39,276] [automlx.model_selection] Model Selection completed - Took 1.355 sec - Selected models: [['XGBRegressor', 'LinearRegression']] [2025-05-22 05:37:39,351] [automlx.trials] Running Model Tuning for ['XGBRegressor'] [2025-05-22 05:37:41,796] [automlx.trials] Best parameters for XGBRegressor: {'n_estimators': 100, 'min_child_weight': 1, 'reg_alpha': 0, 'booster': 'dart', 'max_depth': 6, 'learning_rate': 0.1, 'reg_lambda': 1} [2025-05-22 05:37:41,797] [automlx.trials] Model Tuning completed. Took: 2.446 secs [2025-05-22 05:37:41,851] [automlx.trials] skipping model tuning for: [<automlx._pipeline.pipeline.Pipeline object at 0x14b3269e0a90>] [2025-05-22 05:37:41,948] [automlx.interface] Re-fitting pipeline [2025-05-22 05:37:41,964] [automlx.final_fit] Skipping updating parameter seed, already fixed by FinalFit_20acbc6f-2 [2025-05-22 05:37:43,400] [automlx.interface] AutoMLx completed. Prediction error (MSE) on test data : 0.23716484748805952
For a variety of decision-making tasks, getting only a prediction as model output is not sufficient. A user may wish to know why the model outputs that prediction, or which data features are relevant for that prediction. For that purpose the Oracle AutoMLx solution defines the MLExplainer
object, which allows to compute multiple types of model explanations.
The MLExplainer
object takes as argument the trained model, the training data and labels, as well as the task.
explainer = automlx.MLExplainer(est1,
X_train,
y_train,
task="regression")
The notion of Global Feature Importance intuitively measures how much the model's performance (relative to the provided train labels) would change if a given feature were dropped from the dataset, without allowing the model to be retrained. This notion of feature importance considers each feature independently from all other features.
By default we use a permutation method to successively measure the importance of each feature. Such a method therefore runs in linear time with respect to the number of features in the dataset.
The method explain_model()
allows to compute such feature importances. It also provides 95% confidence intervals for each feature importance.
result_explain_model_default = explainer.explain_model(
n_iter=5, # Can also be 'auto' to pick a good value for the explainer and task
scoring_metric='r2', # Global feature importance measures how much each feature improved the
# model's score. Users can chose the scoring metric used here.
)
There are two options to show the explanation's results:
to_dataframe()
will return a dataframe of the results.show_in_notebook()
will show the results as a bar plot.The features are returned in decreasing order of importance. We see that Latitude
and Longitude
are considered to be the most important features.
result_explain_model_default.to_dataframe()
feature | attribution | upper_bound | lower_bound | |
---|---|---|---|---|
0 | Latitude | 1.262288 | 1.322257 | 1.202320 |
1 | Longitude | 1.073291 | 1.126496 | 1.020086 |
2 | MedInc | 0.369554 | 0.377468 | 0.361640 |
3 | AveOccup | 0.154384 | 0.164288 | 0.144480 |
4 | AveRooms | 0.116088 | 0.122427 | 0.109748 |
5 | HouseAge | 0.063371 | 0.065839 | 0.060902 |
result_explain_model_default.show_in_notebook()
Another way to measure dependency on a feature is through a partial dependence plot (PDP) or an individual conditional expectation (ICE) plot. For accumulated local effects (ALE) explanations, see Advanced Feature Dependence Options (ALE)
Given a dataset, a PDP displays the average output of the model as a function of the value of the selected set of features (Up to 4 features).
It can be computed for a single feature, as in the cell below. The X-axis is the value of the Latitude
feature and the y-axis is the corresponding outputted price. Since we are considering the whole dataset, the average over outputs is given by the red line, while the shaded interval corresponds to a 95% confidence interval for the average.
The histogram on top shows the distribution of the value of the Latitude
feature in the dataset.
result_explain_feature_dependence_default = explainer.explain_feature_dependence('Latitude')
result_explain_feature_dependence_default.show_in_notebook()
The ICE plot is automatically computed at the same time as any one-feature PDP. It can be accessed by passing ice=True
to show_in_notebook
.
Similar to PDPs, ICE plots show the median prediction as a model red line. However, the variance in the model's predictions are shown by plotting the predictions of a sample of individual data instances as light grey lines. (For categorical features, the distribution in the predictions is instead shown as a violin plot.)
result_explain_feature_dependence_default.show_in_notebook(ice=True)
We can also plot the PDP for multiple features. The plot below is the PDP for the Latitude
and Longitude
features. The X-axis still shows the values of Latitude
, while there is a different curve and confidence interval for each value of the feature Longitude
.
The histogram displays the joint distribution of the two features.
result_explain_feature_dependence_default = explainer.explain_feature_dependence(['Latitude', 'Longitude'])
result_explain_feature_dependence_default.show_in_notebook()
Given a data sample, one can also obtain the local importance, which is the importance of the features for the model's prediction on that sample.
In the following cell, we consider sample $10$. The function explain_prediction()
computes the local importance for a given sample.
Latitude=33.0
means that the value of feature Latitude
for that sample is 33.0
. Removing that feature would change the model's prediction by the magnitude of the bar. That is, in this case, the model's prediction for the median house price is approximately 1.15 (i.e., $115 000) less because the model knows the value of Latitude
is 33.0
.
result_explain_prediction_default = explainer.explain_prediction(X_train.sample(n=10))
result_explain_prediction_default[0].show_in_notebook()
We now summarize all of the individual local feature importance explanations into one single aggregate explanation.
alfi = explainer.aggregate(explanations=result_explain_prediction_default)
alfi.show_in_notebook()
The Oracle AutoMLx solution offers also What-IF tool to explain a trained ML model's predictions through a simple interactive interface.
You can use What-IF explainer to explore and visualize immediately how changing a sample value will affect the model's prediction. Furthermore, What-IF can be used to visualize how model's predictions are related to any feature of the dataset.
explainer.explore_whatif(X_test, y_test)
We now display more advanced configuration for computing feature importance. Here, we will explain a custom LinearRegression
estimator from scikit-learn
. Note that the MLExplainer
object is capable of explaining any regression model, as long as the model follows a scikit-learn-style interface with the predict
function.
scikit_model = LinearRegression()
scikit_model.fit(X_train, y_train)
explainer_sklearn = automlx.MLExplainer(
scikit_model,
X_train,
y_train,
target_names=[ # Used for plot labels/legends.
'Median Price'
],
selected_features='auto', # These features are used by the model; automatically inferred for AutoML Pipelines,
task="regression",
col_types=None # Specify type of features
)
The Oracle AutoMLx solution allows one to change the effect of feature interactions. This can be done through the tabulator_type
argument of both global and local importance methods.
tabulator_type
can be set to one of the following options:
permutation
: This value is the default method in the MLExplainer object, with the behaviour described above
shapley
: Feature importance is computed using the popular game-theoretic Shapley value method. Technically, this measures the importance of each feature while including the effect of all feature interactions. As a result, it runs in exponential time with respect to the number of features in the dataset. This method also includes the interaction effects of the other features, which means that if two features contain duplicate information, they will be less important. Note that the interpretation of this method's result is a bit different from the permutation method's result. An interested reader may find this a good source for learning more about it.
kernel_shap
: Feature importance attributions will be calculated using an approximation of the Shapley value method. It typically provides relatively high-quality approximations; however, it currently does not provide confidence intervals.
shap_pi
: Feature importance attributions will be computed using an approximation of the Shapley value method. It runs in linear time, but may miss the effect of interactions between some features, which may therefore produce lower-quality results. Most likely, you will notice that this method yields larger confidence intervals than the other two.
Summary: permutation
can miss important features for AD. Exact SHAP (shapley
) doesn't, but it is exponential. kernel_shap
is an approximation of exact SHAP method that does not provide confidence intervals. shap_pi
is linear, thus faster than exact SHAP and kernel_shap but unstable and very random leads to lower quality approximations.
explainer_sklearn.configure_explain_prediction(tabulator_type="kernel_shap")
The Oracle AutoMLx solution allows one to change the type of local explainer effect of feature interactions. This can be done through the explainer_type
argument of local importance methods.
explainer_type
can be set to one of the following options:
perturbation
: This value is the default explainer type in local feature importance. As we showed above, the explanation(s) will be computed by perturbing the features of the indicated data instance(s) and measuring the impact on the model predictions.
surrogate
: The LIME-style explanation(s) will be computed by fitting a surrogate model to the predictions of the original model in a small region around the indicated data instance(s) and measuring the importance of the features to the interpretable surrogate model. The method of surrogate explainer can be set to one of the following options:
systematic
: An Oracle-labs-improved version of LIME that uses a systematic sampling and custom sample weighting. (Default)lime
: Local interpretable model-agnostic explanations (LIME) algorithm (https://arxiv.org/pdf/1602.04938).explainer_sklearn.configure_explain_prediction(
explainer_type='surrogate',
method='lime'
)
index = 0
result_explain_prediction_kernel_shap = explainer_sklearn.explain_prediction(X_train.iloc[index:index+1, :])
result_explain_prediction_kernel_shap[0].show_in_notebook()
Oracle AutoMLx solution also provides the evaluator_type
attribute, which allows one to choose whether to get feature importance attributions that explain exactly which features the model has learned to use (interventional
), or which features the model or a retrained model could have learned to use (observational
).
interventional
: The computed feature importances are as faithful to the
model as possible. That is, features that are ignored by
the model will not be considered important. This setting
should be preferred if the primary goal is to learn about
the machine learning model itself. Technically, this
setting is called 'interventional', because the method will
intervene on the data distribution when assessing the
importance of features. The intuition of feature importance attributions computed with this method is that the features are dropped from the dataset and the model is not allowed to retrain.
observational
: The computed feature importances are more faithful to
the relationships that exist in the real world (i.e., relationships
observed in the dataset), even if your specific model did not learn
to use them. For example, when using a permutation tabulator, a feature
that is used by the model will not show a large impact on the model's
performance if there is a second feature that contains near-duplicate
information, because a re-trained model could have learned to use the
other feature instead. (Similarly, for Shapley-based tabulators, a
feature that is ignored by the model may have a non-zero feature
importance if it could have been used by the model to
predict the target.) This setting should be preferred if the
model is merely a means to learn more about the
relationships that exist within the data. Technically, this
setting is called 'observational', because it observes the
relationships in the data without breaking the existing
data distribution.
explainer_sklearn.configure_explain_model(evaluator_type="observational")
result_explain_model_kernel_shap = explainer_sklearn.explain_model()
result_explain_model_kernel_shap.show_in_notebook()
explainer_sklearn.configure_explain_prediction(evaluator_type="observational",
tabulator_type="permutation")
[2025-05-22 05:38:07,469] [automlx.mlx] AutoMLx got an unexpected keyword argument 'evaluator_type', which is not a configurable attribute of any of ['TabularLocalSurrogateExplainer', 'RandomSampleGeneration', 'DistanceWeighting', 'SurrogateHandler']. Valid options are: {'TabularLocalSurrogateExplainer': ['method', 'exp_sorting', 'num_features', 'scale_weight'], 'RandomSampleGeneration': ['discretizer', 'num_samples', 'sample_around_instance'], 'DistanceWeighting': ['kernel_width', 'distance_metric', 'dataset_type'], 'SurrogateHandler': ['model', 'feature_selection', 'force_fit_sample']} [2025-05-22 05:38:07,469] [automlx.mlx] AutoMLx got an unexpected keyword argument 'tabulator_type', which is not a configurable attribute of any of ['TabularLocalSurrogateExplainer', 'RandomSampleGeneration', 'DistanceWeighting', 'SurrogateHandler']. Valid options are: {'TabularLocalSurrogateExplainer': ['method', 'exp_sorting', 'num_features', 'scale_weight'], 'RandomSampleGeneration': ['discretizer', 'num_samples', 'sample_around_instance'], 'DistanceWeighting': ['kernel_width', 'distance_metric', 'dataset_type'], 'SurrogateHandler': ['model', 'feature_selection', 'force_fit_sample']}
index = 0
result_explain_prediction_kernel_shap = explainer_sklearn.explain_prediction(X_train.iloc[index:index+1, :])
result_explain_prediction_kernel_shap[0].show_in_notebook()
We now show how to use an alternative method for computing feature dependence: accumulated local effects (ALE). ALE explanations are sometimes considered a better alternative to PDPs when features are correlated, because it does not evaluate the model outside of its training distribution in these cases. For more information, see https://christophm.github.io/interpretable-ml-book/ale.html.
Given a dataset, an ALE displays the average change in the output of the model, accumulated over multiple small changes in one or two features, when all other features are held fixed. By default, the ALE explanations are centered around 0, and thus, unlike PDPs, ALEs show the change in the prediction measured by changing a given feature, rather than the average model's prediction for a particular feature value.
We can compute ALEs for two features (At least one is numerical). The plot below is the ALE plot for the Latitude
and Longitude
features. The X-axis still shows the values of Latitude
, while there is multiple lines, one for each value of the feature Longitude
.
The histogram displays the joint distribution of the two features.
explainer_sklearn.configure_explain_feature_dependence(explanation_type='ale')
result_explain_feature_dependence_default = explainer_sklearn.explain_feature_dependence(['Latitude', 'Longitude'])
result_explain_feature_dependence_default.show_in_notebook()