Start¶
In this guide, we’ll show how you can use EvalML to automatically find the best pipeline for predicting whether a patient has breast cancer. Along the way, we’ll highlight EvalML’s built-in tools and features for understanding and interacting with the search process.
[1]:
import evalml
from evalml import AutoMLSearch
from evalml.utils import infer_feature_types
First, we load in the features and outcomes we want to use to train our model.
[2]:
X, y = evalml.demos.load_fraud(n_rows=1000, return_pandas=True)
Number of Features
Boolean 1
Categorical 6
Numeric 5
Number of training examples: 1000
Targets
False 85.90%
True 14.10%
Name: fraud, dtype: object
First, we will clean the data. Since EvalML accepts a pandas input, it can run type inference on this data directly. Since we’d like to change the types inferred by EvalML, we can use the infer_feature_types
utility method. Here’s what we’re going to do with the following dataset:
Reformat the
expiration_date
column so it reflects a more familiar date format.Cast the
lat
andlng
columns from float to str.Use
infer_feature_types
to specify what types certain columns should be. For example, to avoid having theprovider
column be inferred as natural language text, we have specified it as a categorical column instead.
The infer_feature_types
utility method takes a pandas or numpy input and converts it to a Woodwork data structure, providing us with flexibility to cast the data as necessary.
[3]:
X['expiration_date'] = X['expiration_date'].apply(lambda x: '20{}-01-{}'.format(x.split("/")[1], x.split("/")[0]))
X[['lat', 'lng']] = X[['lat', 'lng']].astype('str')
X = infer_feature_types(X, feature_types= {'store_id': 'categorical',
'expiration_date': 'datetime',
'lat': 'categorical',
'lng': 'categorical',
'provider': 'categorical'})
X
[3]:
Physical Type | Logical Type | Semantic Tag(s) | |
---|---|---|---|
Data Column | |||
card_id | Int64 | Integer | ['numeric'] |
store_id | category | Categorical | ['category'] |
datetime | datetime64[ns] | Datetime | [] |
amount | Int64 | Integer | ['numeric'] |
currency | category | Categorical | ['category'] |
customer_present | boolean | Boolean | [] |
expiration_date | category | Datetime | [] |
provider | category | Categorical | ['category'] |
lat | category | Categorical | ['category'] |
lng | category | Categorical | ['category'] |
region | category | Categorical | ['category'] |
country | category | Categorical | ['category'] |
In order to validate the results of the pipeline creation and optimization process, we will save some of our data as a holdout set.
[4]:
X_train, X_holdout, y_train, y_holdout = evalml.preprocessing.split_data(X, y, problem_type='binary', test_size=.2)
Note: To provide data to EvalML, it is recommended that you create a DataTable
object using the Woodwork project. Here, split_data()
returns Woodwork data structures.
EvalML also accepts and works well with pandas DataFrames
. But using the DataTable
makes it easy to control how EvalML will treat each feature, as a numeric feature, a categorical feature, a text feature or other type of feature. Woodwork’s DataTable
includes features like inferring when a categorical feature should be treated as a text feature.
EvalML has many options to configure the pipeline search. At the minimum, we need to define an objective function. For simplicity, we will use the F1 score in this example. However, the real power of EvalML is in using domain-specific objective functions or building your own.
Below EvalML utilizes Bayesian optimization (EvalML’s default optimizer) to search and find the best pipeline defined by the given objective.
EvalML provides a number of parameters to control the search process. max_batches
is one of the parameters which controls the stopping criterion for the AutoML search. It indicates the maximum number of rounds of AutoML to evaluate, where each round may train and score a variable number of pipelines. In this example, max_batches
is set to 1.
** Graphing methods, like AutoMLSearch, on Jupyter Notebook and Jupyter Lab require ipywidgets to be installed.
** If graphing on Jupyter Lab, jupyterlab-plotly required. To download this, make sure you have npm installed.
[5]:
automl = AutoMLSearch(X_train=X_train, y_train=y_train,
problem_type='binary', objective='f1', max_batches=1)
Generating pipelines to search over...
When we call search()
, the search for the best pipeline will begin. There is no need to wrangle with missing data or categorical variables as EvalML includes various preprocessing steps (like imputation, one-hot encoding, feature selection) to ensure you’re getting the best results. As long as your data is in a single table, EvalML can handle it. If not, you can reduce your data to a single table by utilizing Featuretools and its Entity Sets.
You can find more information on pipeline components and how to integrate your own custom pipelines into EvalML here.
[6]:
automl.search()
*****************************
* Beginning pipeline search *
*****************************
Optimizing for F1.
Greater score is better.
Using SequentialEngine to train and score pipelines.
Searching up to 1 batches for a total of 9 pipelines.
Allowed model families: xgboost, decision_tree, catboost, linear_model, lightgbm, extra_trees, random_forest
Evaluating Baseline Pipeline: Mode Baseline Binary Classification Pipeline
Mode Baseline Binary Classification Pipeline:
Starting cross validation
Finished cross validation - mean F1: 0.000
*****************************
* Evaluating Batch Number 1 *
*****************************
Decision Tree Classifier w/ Imputer + DateTime Featurization Component + One Hot Encoder:
Starting cross validation
Finished cross validation - mean F1: 0.393
High coefficient of variation (cv >= 0.2) within cross validation scores.
Decision Tree Classifier w/ Imputer + DateTime Featurization Component + One Hot Encoder may not perform as estimated on unseen data.
Extra Trees Classifier w/ Imputer + DateTime Featurization Component + One Hot Encoder:
Starting cross validation
Finished cross validation - mean F1: 0.455
High coefficient of variation (cv >= 0.2) within cross validation scores.
Extra Trees Classifier w/ Imputer + DateTime Featurization Component + One Hot Encoder may not perform as estimated on unseen data.
CatBoost Classifier w/ Imputer + DateTime Featurization Component:
Starting cross validation
Finished cross validation - mean F1: 0.738
Random Forest Classifier w/ Imputer + DateTime Featurization Component + One Hot Encoder:
Starting cross validation
Finished cross validation - mean F1: 0.731
LightGBM Classifier w/ Imputer + DateTime Featurization Component + One Hot Encoder:
Starting cross validation
Finished cross validation - mean F1: 0.701
XGBoost Classifier w/ Imputer + DateTime Featurization Component + One Hot Encoder:
Starting cross validation
Finished cross validation - mean F1: 0.730
Elastic Net Classifier w/ Imputer + DateTime Featurization Component + One Hot Encoder + Standard Scaler:
Starting cross validation
Finished cross validation - mean F1: 0.248
Logistic Regression Classifier w/ Imputer + DateTime Featurization Component + One Hot Encoder + Standard Scaler:
Starting cross validation
Finished cross validation - mean F1: 0.319
High coefficient of variation (cv >= 0.2) within cross validation scores.
Logistic Regression Classifier w/ Imputer + DateTime Featurization Component + One Hot Encoder + Standard Scaler may not perform as estimated on unseen data.
Search finished after 00:21
Best pipeline: CatBoost Classifier w/ Imputer + DateTime Featurization Component
Best pipeline F1: 0.738349
After the search is finished we can view all of the pipelines searched, ranked by score. Internally, EvalML performs cross validation to score the pipelines. If it notices a high variance across cross validation folds, it will warn you. EvalML also provides additional data checks to analyze your data to assist you in producing the best performing pipeline.
[7]:
automl.rankings
[7]:
id | pipeline_name | mean_cv_score | standard_deviation_cv_score | validation_score | percent_better_than_baseline | high_variance_cv | parameters | |
---|---|---|---|---|---|---|---|---|
0 | 3 | CatBoost Classifier w/ Imputer + DateTime Feat... | 0.738349 | 0.017274 | 0.757576 | 73.834901 | False | {'Imputer': {'categorical_impute_strategy': 'm... |
1 | 4 | Random Forest Classifier w/ Imputer + DateTime... | 0.731328 | 0.039761 | 0.774194 | 73.132788 | False | {'Imputer': {'categorical_impute_strategy': 'm... |
2 | 6 | XGBoost Classifier w/ Imputer + DateTime Featu... | 0.730268 | 0.005309 | 0.733333 | 73.026820 | False | {'Imputer': {'categorical_impute_strategy': 'm... |
3 | 5 | LightGBM Classifier w/ Imputer + DateTime Feat... | 0.700767 | 0.019222 | 0.711864 | 70.076675 | False | {'Imputer': {'categorical_impute_strategy': 'm... |
4 | 2 | Extra Trees Classifier w/ Imputer + DateTime F... | 0.455416 | 0.181772 | 0.253521 | 45.541613 | True | {'Imputer': {'categorical_impute_strategy': 'm... |
5 | 1 | Decision Tree Classifier w/ Imputer + DateTime... | 0.393324 | 0.253968 | 0.686567 | 39.332397 | True | {'Imputer': {'categorical_impute_strategy': 'm... |
6 | 8 | Logistic Regression Classifier w/ Imputer + Da... | 0.318985 | 0.064165 | 0.385965 | 31.898487 | True | {'Imputer': {'categorical_impute_strategy': 'm... |
7 | 7 | Elastic Net Classifier w/ Imputer + DateTime F... | 0.247528 | 0.002861 | 0.249180 | 24.752836 | False | {'Imputer': {'categorical_impute_strategy': 'm... |
8 | 0 | Mode Baseline Binary Classification Pipeline | 0.000000 | 0.000000 | 0.000000 | 0.000000 | False | {'Baseline Classifier': {'strategy': 'mode'}} |
If we are interested in see more details about the pipeline, we can view a summary description using the id
from the rankings table:
[8]:
automl.describe_pipeline(3)
*********************************************************************
* CatBoost Classifier w/ Imputer + DateTime Featurization Component *
*********************************************************************
Problem Type: binary
Model Family: CatBoost
Pipeline Steps
==============
1. Imputer
* categorical_impute_strategy : most_frequent
* numeric_impute_strategy : mean
* categorical_fill_value : None
* numeric_fill_value : None
2. DateTime Featurization Component
* features_to_extract : ['year', 'month', 'day_of_week', 'hour']
* encode_as_categories : False
3. CatBoost Classifier
* n_estimators : 10
* eta : 0.03
* max_depth : 6
* bootstrap_type : None
* silent : True
* allow_writing_files : False
Training
========
Training for binary problems.
Objective to optimize binary classification pipeline thresholds for: <evalml.objectives.standard_metrics.F1 object at 0x7fa66f3e7880>
Total training time (including CV): 1.2 seconds
Cross Validation
----------------
F1 MCC Binary Log Loss Binary AUC Precision Balanced Accuracy Binary Accuracy Binary Sensitivity at Low Alert Rates # Training # Validation
0 0.758 0.735 0.569 0.882 0.893 0.822 0.940 0.000 375 267
1 0.733 0.736 0.561 0.782 1.000 0.789 0.940 0.000 375 267
2 0.724 0.728 0.573 0.790 1.000 0.784 0.940 0.000 380 266
mean 0.738 0.733 0.568 0.818 0.964 0.799 0.940 0.000 - -
std 0.017 0.004 0.006 0.055 0.062 0.021 0.000 0.000 - -
coef of var 0.023 0.006 0.011 0.068 0.064 0.026 0.000 inf - -
We can also view the pipeline parameters directly:
[9]:
pipeline = automl.get_pipeline(3)
print(pipeline.parameters)
{'Imputer': {'categorical_impute_strategy': 'most_frequent', 'numeric_impute_strategy': 'mean', 'categorical_fill_value': None, 'numeric_fill_value': None}, 'DateTime Featurization Component': {'features_to_extract': ['year', 'month', 'day_of_week', 'hour'], 'encode_as_categories': False}, 'CatBoost Classifier': {'n_estimators': 10, 'eta': 0.03, 'max_depth': 6, 'bootstrap_type': None, 'silent': True, 'allow_writing_files': False}}
We can now select the best pipeline and score it on our holdout data:
[10]:
pipeline = automl.best_pipeline
pipeline.score(X_holdout, y_holdout, ["f1"])
[10]:
OrderedDict([('F1', 0.7272727272727273)])
We can also visualize the structure of the components contained by the pipeline:
[11]:
pipeline.graph()
[11]: