Skip to content
ImagineWorld

Interpretation Challenges

node_idnode-book_interpretable-machine-learning-with-python-second-edition_chapter-03-interpretation-challenges
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleInterpretation Challenges
pillar_membershipJ — architecture_design_craft
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In this chapter, we will discuss the traditional methods used for machine learning interpretation for both regression and classification. This includes model performance evaluation methods such as RMSE, R-squared, AUC, ROC curves, and the many metrics derived from confusion matrices. We will then examine the limitations of these performance metrics and explain what exactly makes “white-box” models intrinsically interpretable and why we cannot always use white-box models. To answer these questions, we’ll consider the trade-off between prediction performance and model interpretability. Finally, we will discover some new “glass-box” models such as Explainable Boosting Machines (EBMs) and GAMI-Net that attempt to not compromise on this trade-off between predictive performance and interpretability.

The following are the main topics that will be covered in this chapter:

  • Reviewing traditional model interpretation methods
  • Understanding the limitations of traditional model interpretation methods
  • Studying intrinsically interpretable (white-box) models
  • Recognizing the trade-off between performance and interpretability
  • Discovering newer interpretable (glass-box) models

From Chapter 2, Key Concepts of Interpretability, onward, we are using a custom mldatasets library to load our datasets. Instructions on how to install this library can be found in the Preface. In addition to mldatasets, this chapter’s examples also use the pandas, numpy, sklearn, rulefit, interpret, statsmodels, matplotlib, and gaminet libraries.

The code for this chapter is located here: packt.link/swCyB.

Picture yourself, a data science consultant, in a conference room in Fort Worth, Texas, during early January 2019. In this conference room, executives for one of the world’s largest airlines, American Airlines (AA), are briefing you on their On-Time Performance (OTP). OTP is a widely accepted Key Performance Indicator (KPI) for flight punctuality. It is measured as the percentage of flights that arrived within 15 minutes of the scheduled arrival. It turns out that AA has achieved an OTP of just over 80% for 3 years in a row, which is acceptable, and a significant improvement, but they are still ninth in the world and fifth in North America. To brag about it next year in their advertising, they aspire to achieve, at least, number one in North America for 2019, besting their biggest rivals.

On the financial front, it is estimated that delays cost the airline close to $2 billion, so reducing this by 25–35% to be on parity with their competitors could produce sizable savings. And it is estimated that it costs passengers just as much due to tens of millions of lost hours. A reduction in delays would result in happier customers, which could lead to an increase in ticket sales.

Your task is to create models that can accurately predict delays for domestic flights only. What they hope to gain from the models is the following:

  • To understand what factors impacted domestic arrival delays the most in 2018
  • To anticipate a delay caused by the airline in midair with enough accuracy to mitigate some of these factors in 2019

But not all delays are made equal. The International Air Transport Association (IATA) has over 80 delay codes ranging from 14 (oversales booking errors) to 75 (de-icing of aircraft, removal of ice/snow, frost prevention). Some are preventable, and others unavoidable.

The airline executives told you that the airline is not, for now, interested in predicting delays caused by events out of their control, such as extreme weather, security events, and air traffic control issues. They are also not interested in delays caused by late arrivals from previous flights using the same aircraft because this was not the root cause. Nevertheless, they would like to know the effect of a busy hub on avoidable delays even if this has to do with congestion because, after all, perhaps there’s something they can do with flight scheduling or flight speed, or even gate selection. And while they understand that international flights occasionally impact domestic flights, they hope to tackle the sizeable local market first.

Executives have provided you with a dataset from the United States Department of Transportation Bureau of Transportation Statistics with all 2018 AA domestic flights.

Upon careful consideration, you have decided to approach this both as a regression problem and a classification problem. Therefore, you will produce models that predict minutes delayed as well as models that classify whether flights were delayed by more than 15 minutes. For interpretation, using both will enable you to use a wider variety of methods and expand your interpretation accordingly. So we will approach this example by taking the following steps:

  1. Predicting minutes delayed with various regression methods
  2. Classifying flights as delayed or not delayed with various classification methods

These steps in the Reviewing traditional model interpretation methods section are followed by conclusions spread out in the rest of the sections of this chapter.

You will find the code for this example here: https://github.com/PacktPublishing/Interpretable-Machine-Learning-with-Python-2E/blob/main/03/FlightDelays.ipynb.

To run this example, you need to install the following libraries:

  • mldatasets to load the dataset
  • pandas and numpy to manipulate it
  • sklearn (scikit-learn), rulefit, statsmodels, interpret, tf, and gaminet to fit models and calculate performance metrics
  • matplotlib to create visualizations

Load these libraries as seen in the following snippet:

import math
import mldatasets
import pandas as pd
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler,\
MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn import metrics, linear_model, tree, naive_bayes,\
neighbors, ensemble, neural_network, svm
from rulefit import RuleFit
import statsmodels.api as sm
from interpret.glassbox import ExplainableBoostingClassifier
from interpret import show
from interpret.perf import ROC
import tensorflow as tf
from gaminet import GAMINet
from gaminet.utils import plot_trajectory, plot_regularization,\
local_visualize, global_visualize_density,\
feature_importance_visualize
import matplotlib.pyplot as plt

We then load the data as shown:

aad18_df = mldatasets.load("aa-domestic-delays-2018")

There should be nearly 900,000 records and 23 columns. We can take a peek at what was loaded like this:

print(aad18_df.info())

The following is the output:

RangeIndex: 899527 entries, 0 to 899526Data columns (total 23 columns):

FL_NUM 899527 non-null int64 ORIGIN 899527 non-null object DEST 899527 non-null object PLANNED_DEP_DATETIME 899527 non-null object CRS_DEP_TIME 899527 non-null int64 DEP_TIME 899527 non-null float64 DEP_DELAY 899527 non-null float64 DEP_AFPH 899527 non-null float64 DEP_RFPH 899527 non-null float64 TAXI_OUT 899527 non-null float64 WHEELS_OFF 899527 non-null float64 : : : : WEATHER_DELAY 899527 non-null float64 NAS_DELAY 899527 non-null float64 SECURITY_DELAY 899527 non-null float64 LATE_AIRCRAFT_DELAY 899527 non-null float64 dtypes: float64(17), int64(3), object(3)

Everything seems to be in order because all columns are there and there are no null values.

Let’s examine the data dictionary.

General features are as follows:

  • FL_NUM: Flight number.
  • ORIGIN: Starting airport code (IATA).
  • DEST: Destination airport code (IATA).

Departure features are as follows:

  • PLANNED_DEP_DATETIME: The planned date and time of the flight.
  • CRS_DEP_TIME: The planned departure time.
  • DEP_TIME: The actual departure time.
  • DEP_AFPH: The number of actual flights per hour occurring during the interval in between the planned and actual departure from the origin airport (factoring in 30 minutes of padding). The feature tells you how busy the origin airport was during takeoff.
  • DEP_RFPH: The departure relative flights per hour is the ratio of actual flights per hour over the median number of flights per hour that occur at the origin airport at that time of day, day of the week, and month of the year. The feature tells you how relatively busy the origin airport was during takeoff.
  • TAXI_OUT: The time duration elapsed between the departure from the origin airport gate and wheels off.
  • WHEELS_OFF: The point in time that the aircraft’s wheels leave the ground.

In-flight features are as follows:

  • CRS_ELAPSED_TIME: The planned amount of time needed for the flight trip.
  • PCT_ELAPSED_TIME: The ratio of actual flight time over planned flight time to gauge the plane’s relative speed.
  • DISTANCE: The distance between two airports.

Arrival features are as follows:

  • CRS_ARR_TIME: The planned arrival time.
  • ARR_AFPH: The number of actual flights per hour occurring during the interval between the planned and actual arrival time at the destination airport (factoring in 30 minutes of padding). The feature tells you how busy the destination airport was during landing.
  • ARR_RFPH: The arrival relative flights per hour is the ratio of actual flights per hour over the median number of flights per hour that occur at the destination airport at that time of day, day of the week, and month of the year. The feature tells you how relatively busy the destination airport was during landing.

Delay features are as follows:

  • DEP_DELAY: The total delay on departure in minutes.
  • ARR_DELAY: The total delay on arrival in minutes can be subdivided into any or all of the following:
    1. CARRIER_DELAY: The delay in minutes caused by circumstances within the airline’s control (for example, maintenance or crew problems, aircraft cleaning, baggage loading, fueling, and so on). 2. WEATHER_DELAY: The delay in minutes caused by significant meteorological conditions (actual or forecasted). 3. NAS_DELAY: The delay in minutes mandated by a national aviation system such as non-extreme weather conditions, airport operations, heavy traffic volume, and air traffic control. 4. SECURITY_DELAY: The delay in minutes caused by the evacuation of a terminal or concourse, re-boarding of an aircraft because of a security breach, faulty screening equipment, or long lines above 29 minutes in screening areas. 5. LATE_AIRCRAFT_DELAY: The delay in minutes caused by a previous flight with the same aircraft that arrived late.

For starters, PLANNED_DEP_DATETIME must be a datetime data type:

aad18_df['PLANNED_DEP_DATETIME'] =\
pd.to_datetime(aad18_df['PLANNED_DEP_DATETIME'])

The exact day and time of a flight don’t matter, but maybe the month and day of the week do because of weather and seasonal patterns that can only be appreciated at this level of granularity. Also, the executives mentioned weekends and winters being especially bad for delays. Therefore, we will create features for the month and day of the week:

aad18_df['DEP_MONTH'] = aad18_df['PLANNED_DEP_DATETIME'].dt.month
aad18_df['DEP_DOW'] = aad18_df['PLANNED_DEP_DATETIME'].dt.dayofweek

We don’t need the PLANNED_DEP_DATETIME column so let’s drop it like this:

aad18_df = aad18_df.drop(['PLANNED_DEP_DATETIME'], axis=1)

It is essential to record whether the arrival or destination airport is a hub. AA, in 2019, had 10 hubs: Charlotte, Chicago–O’Hare, Dallas/Fort Worth, Los Angeles, Miami, New York–JFK, New York–LaGuardia, Philadelphia, Phoenix–Sky Harbor, and Washington–National. Therefore, we can encode which ORIGIN and DEST airports are AA hubs using their IATA codes, and get rid of columns with codes since they are too specific (FL_NUM, ORIGIN, and DEST):

#Create list with 10 hubs (with their IATA codes)

hubs = ['CLT', 'ORD', 'DFW', 'LAX', 'MIA', 'JFK', 'LGA', 'PHL',
'PHX', 'DCA']

#Boolean series for if ORIGIN or DEST are hubsis_origin_hub =

aad18_df[‘ORIGIN’].isin(hubs) is_dest_hub = aad18_df[‘DEST’].isin(hubs) #Use boolean series to set ORIGIN_HUB and DEST_HUB aad18_df[‘ORIGIN_HUB’] = 0 aad18_df.loc[is_origin_hub, ‘ORIGIN_HUB’] = 1 aad18_df[‘DEST_HUB’] = 0 aad18_df.loc[is_dest_hub, ‘DEST_HUB’] = 1 #Drop columns with codes aad18_df = aad18_df.drop([‘FL_NUM’, ‘ORIGIN’, ‘DEST’], axis=1)

After all these operations, we have a fair number of useful features, but we are yet to determine the target feature. There are two columns that could serve this purpose. We have ARR_DELAY, which is the total number of minutes delayed regardless of the reason, and then there’s CARRIER_DELAY, which is just the total number of those minutes that can be attributed to the airline. For instance, look at the following sample of flights delayed over 15 minutes (which is considered late according to the airline’s definition):

aad18_df.loc[aad18_df[‘ARR_DELAY’] > 15,
[‘ARR_DELAY’,‘CARRIER_DELAY’]].head(10)

The preceding code outputs Figure 3.1:

![Table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_01.png)

Figure 3.1: Sample observations with arrival delays over 15 minutes

Of all the delays in Figure 3.1, one of them (#26) wasn’t at all the responsibility of the airline because only 0 minutes could be attributed to the airline. Four of them were partially the responsibility of the airline (#8, #16, #33, and #40), two of which were over 15 minutes late due to the airline (#8 and #40). The rest of them were entirely the airline’s fault. We can tell that although the total delay is useful information, the airline executives were only interested in delays caused by the airline so ARR_DELAY can be discarded. Furthermore, there’s another more important reason it should be discarded, and it’s that if the task at hand is to predict a delay, we cannot use pretty much the very same delay (minus the portions not due to the airline) to predict it. For this very same reason, it is best to remove ARR_DELAY:

aad18_df = aad18_df.drop(['ARR_DELAY'], axis=1)

Finally, we can put the target feature alone as y and all the rest as X. After this, we split y and X into train and test datasets. Please note that the target feature (y) stays the same for regression, so we split it into y_train_reg and y_test_reg. However, for classification, we must make binary versions of these labels denoting whether it’s more than 15 minutes late or not, called y_train_class and y_test_class. Please note that we are setting a fixed random_state for reproducibility:

rand = 9
np.random.seed(rand)
y = aad18_df['CARRIER_DELAY']
X = aad18_df.drop(['CARRIER_DELAY'], axis=1).copy()
X_train, X_test, y_train_reg, y_test_reg = train_test_split(
X, y, test_size=0.15, random_state=rand
)
y_train_class = y_train_reg.apply(lambda x: 1 if x > 15 else 0)
y_test_class = y_test_reg.apply(lambda x: 1 if x > 15 else 0)

To examine how linearly correlated the features are to the target CARRIER_DELAY, we can compute Pearson’s correlation coefficient, turn coefficients to absolute values (because we aren’t interested in whether they are positively or negatively correlated), and sort them in descending order:

corr = aad18_df.corr()
abs(corr['CARRIER_DELAY']).sort_values(ascending=False)

As you can tell from the output, only one feature (DEP_DELAY) is highly correlated. The others aren’t:

CARRIER_DELAY 1.000000 DEP_DELAY 0.703935 ARR_RFPH 0.101742 LATE_AIRCRAFT_DELAY 0.083166 DEP_RFPH 0.058659 ARR_AFPH 0.035135 DEP_TIME 0.030941 NAS_DELAY 0.026792 : :

WEATHER_DELAY 0.003002 SECURITY_DELAY 0.000460

However, this is only linearly correlated and on a one-by-one basis. It doesn’t mean that they don’t have a non-linear relationship, or that several features interacting together wouldn’t impact the target. In the next section, we will discuss this further.

Reviewing traditional model interpretation methods

Section titled “Reviewing traditional model interpretation methods”

To explore as many model classes and interpretation methods as possible, we will fit the data into regression and classification models.

Predicting minutes delayed with various regression methods

Section titled “Predicting minutes delayed with various regression methods”

To compare and contrast regression methods, we will first create a dictionary named reg_models. Each model is its own dictionary and the function that creates it is the model attribute. This structure will be used later to neatly store the fitted model and its metrics. Model classes in this dictionary have been chosen to represent several model families and to illustrate important concepts that we will discuss later:

reg_models = {
#Generalized Linear Models (GLMs)
'linear':{'model': linear_model.LinearRegression()},
'linear_poly':{
'model':make_pipeline(
PolynomialFeatures(degree=2),
linear_model.LinearRegression(fit_intercept=False)
)
},
'linear_interact':{
'model':make_pipeline(
PolynomialFeatures(interaction_only=True),
linear_model.LinearRegression(fit_intercept=False)
)
},
'ridge':{
'model': linear_model.RidgeCV(
alphas=[1e-3, 1e-2, 1e-1, 1])
},
#Trees
'decision_tree':{
'model': tree.DecisionTreeRegressor(
max_depth=7, random_state=rand
)
},
#RuleFit
'rulefit':{
'model': RuleFit(
max_rules=150,
rfmode='regress',
random_state=rand
)
},
#Nearest Neighbors
'knn':{'model': neighbors.KNeighborsRegressor(n_neighbors=7)},
#Ensemble Methods
'random_forest':{
'model':ensemble.RandomForestRegressor(
max_depth=7, random_state=rand)
},
#Neural Networks
'mlp':{
'model':neural_network.MLPRegressor(
hidden_layer_sizes=(21,),
max_iter=500,
early_stopping=True,
random_state=rand
)
}
}

Before we start fitting the data to these models, we will briefly explain them one by one:

  • linear: Linear regression was the first model class we discussed. For better or for worse, it makes several assumptions about the data. Chief among them is the assumption that the prediction must be a linear combination of X features. This, naturally, limits the capacity to discover non-linear relationships and interactions among the features.
  • linear_poly: Polynomial regression extends linear regression by adding polynomial features. In this case, as indicated by degree=2, the polynomial degree is two, so it’s quadratic. This means, in addition to having all features in their monomial form (for example, DEP_FPH), it also has them in a quadratic form (for example, DEP_FPH²), plus the many interaction terms for all of the 21 features. In other words, for DEP_FPH, there would be interaction terms such as DEP_FPH DISTANCE, DEP_FPH DELAY, and so on for the rest of the features.
  • linear_interact: This is just like the polynomial regression model but without the quadratic terms – in other words, only the interactions, as interaction_only=True would suggest. It’s useful because there is no reason to believe any of our features have a relationship that is better fitted with quadratic terms. Still, perhaps it’s the interaction with other features that makes an impact.
  • ridge: Ridge regression is a variation of linear regression. However, even though the method behind linear regression, called ordinary least squares (OLS), does a pretty good job of reducing the error and fitting the model to the features, it does it without considering overfitting. The problem here is that OLS treats all features equally, so the model becomes more complex as each variable is added. As the word overfitting suggests, the resulting model fits the training data too well, resulting in the lowest bias but the highest variance. There’s a sweet spot in this trade-off between bias and variance, and one way of getting to this spot is by reducing the complexity added by the introduction of too many features. Linear regression is not equipped to do so on its own.

This is where ridge regression comes along, with our friend regularization. It does this by shrinking coefficients that don’t contribute to the outcome with a penalty term called the L2 norm. It penalizes complexity, thus constraining the algorithm from overfitting. In this example, we use a cross-validated version of ridge (RidgeCV) that tests several regularization strengths (alphas).

  • decision_tree: A decision tree is precisely as the name suggests. Imagine a tree-like structure where at every point that branches subdivide to form more branches, there is a “test” performed on a feature, partitioning the datasets into each branch. When branches stop subdividing, they become leaves, and at every leaf, there’s a decision, be it to assign a class for classification or a fixed value for regression. We are limiting this tree to max_depth=7 to prevent overfitting because the larger the tree, the better it will fit our training data, and the less likely the tree will generalize to non-training data.
  • rule_fit: RuleFit is a regularized linear regression expanded to include feature interactions in the form of rules. The rules are formed by traversing a decision tree, except it discards the leaves and keeps the feature interactions found traversing the branches toward these leaves. It uses LASSO Regression, which, like ridge, uses regularization, but instead of using the L2 norm, it uses the L1 norm. The result is that useless features end up with a coefficient of zero and do not just converge to zero, as they do with L2, which makes it easy for the algorithm to filter them out. We are limiting the rules to 150 (max_rules=150) and the attribute rfmode='regress' tells RuleFit that this is a regression problem, since it can also be used for classification. Unlike all other models used here, this isn’t a scikit-learn one but was created by Christoph Molnar adapting a paper called Predictive learning via rule ensembles.
  • knn: k-Nearest Neighbors (k-NN) is a simple method based on the locality assumption, which is that data points that are close to each other are similar. In other words, they must have similar predicted values, and, in practice, this isn’t a bad guess, so it takes data points nearest to the point you want to predict and derives a prediction based on that. In this case, n_neighbors=7 so k = 7. It’s an instance-based machine learning model, also known as a lazy learner because it simply stores the training data. During inference, it employs training data to calculate the similarity with points and generate a prediction based on that. This is opposed to what model-based machine learning techniques, or eager learners, do, which is to use training data to learn formulas, parameters, coefficients, or bias/weights, which they then leverages to make a prediction during inference.
  • random_forest: Imagine not one but hundreds of decision trees trained on random combinations of the features and random samples of data. Random forest takes an average of these randomly generated decision trees to create the best tree. This concept of training less effective models in parallel and combining them using an averaging process is called bagging. It is an ensemble method because it combines more than one model (usually called weak learners) into a strong learner. In addition to bagging, there are two other ensemble techniques, called boosting and stacking. For bagging deeper, trees are better because they reduce variance, so this is why we are using max_depth=7.
  • mlp: A multi-layer perceptron is a “vanilla” feedforward (sequential) neural network, so it uses non-linear activation functions (MLPRegressor uses ReLU by default), stochastic gradient descent, and backpropagation. In this case, we are using 21 neurons in the first and only hidden layer, hence hidden_layer_sizes=(21,), running training for 500 epochs (max_iter=500), and terminating training when the validation score is not improving (early_stopping=True).

If you are unfamiliar with some of these models, don’t fret! We will cover them in more detail later in this chapter and the book. Also, please note that some of these models have a random process somewhere. To ensure reproducibility, we have set random_state. It is best to always set this; otherwise, it will randomly set it every single time, which will make your results hard to reproduce.

Now, let’s iterate over our dictionary of models (reg_models), fit them to the training data, and predict and compute two metrics based on the quality of these predictions. We’ll then save the fitted model, test predictions, and metrics in the dictionary for later use. Note that rulefit only accepts numpy arrays, so we can’t fit it in the same way. Also, note that rulefit and mlp take longer than the rest to train, so this can take a few minutes to run:

for model_name in reg_models.keys():
if model_name != 'rulefit':
fitted_model = reg_models[model_name]\
['model'].fit(X_train, y_train_reg)
else :
fitted_model = reg_models[model_name]['model'].\
fit(X_train.values, y_train_reg.values, X_test.columns
)
y_train_pred = fitted_model.predict(X_train.values)
y_test_pred = fitted_model.predict(X_test.values)
reg_models[model_name]['fitted'] = fitted_model
reg_models[model_name]['preds'] = y_test_pred
reg_models[model_name]['RMSE_train'] =\
math.sqrt(
metrics.mean_squared_error(y_train_reg, y_train_pred)
)
reg_models[model_name]['RMSE_test'] =\
math.sqrt(metrics.mean_squared_error(y_test_reg, y_test_pred)
)
reg_models[model_name]['R2_test'] =\
metrics.r2_score(y_test_reg, y_test_pred)

We can now convert the dictionary to a DataFrame and display the metrics in a sorted and color-coded fashion:

reg_metrics = pd.DataFrame.from_dict(
reg_models, 'index')[['RMSE_train', 'RMSE_test', 'R2_test']
]
reg_metrics.sort_values(by='RMSE_test').style.format(
{'RMSE_train': '{:.2f}', 'RMSE_test': '{:.2f}',
'R2_test': '{:.3f}'}

).background_gradient(

cmap='viridis_r', low=0.1, high=1,
subset=['RMSE_train', 'RMSE_test']

).background_gradient(

cmap='plasma', low=0.3, high=1, subset=['R2_test']
)

The preceding code outputs Figure 3.2. Please note that color-coding doesn’t work in all Jupyter Notebook implementations:

![Table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_02.png)

Figure 3.2: Regression metrics for our models

To interpret the metrics in Figure 3.2, we ought to first understand what they mean, both in general and in the context of this regression exercise:

  • RMSE: Root Mean Square Error is defined as the standard deviation of the residuals. It’s the square root of the squared residuals divided by the number of observations – in this case, flights. It tells you, on average, how far apart the predictions are from the actuals, and as you can probably tell from the color-coding, less is better because you want your predictions to be as close as possible to the actuals in the test (hold-out) dataset. We have also included this metric for the train dataset to see how well it’s generalizing. You expect the test error to be higher than the training error, but not by much. If it is, like it is for random_forest, you need to tune some of the parameters to reduce overfitting. In this case, reducing the trees’ maximum depth, increasing the number of trees (also called estimators), and reducing the maximum number of features to use should do the trick. On the other hand, with knn, you can adjust the number of neighbors, but it is expected, because of its lazy learner nature, to overperform on the training data. In any case, these numbers are pretty good because even our worst performing model is below a test RMSE of 10 minutes, and about half of them have a test RMSE of less than 7.5, quite possibly predicting a delay effectively, on average, since the threshold for a delay is 15 minutes. Note that linear_poly is the second and linear_interact is the fourth most performant model, significantly ahead of linear, suggesting that non-linearity and interactivity are important factors to produce better predictive performance.
  • R2: R-squared is also known as the coefficient of determination. It’s defined as the proportion of the variance in the y (outcome) target that can be explained by the X (predictors) features in the model. It answers the question of what proportion of the model variability is explainable? And as you can probably tell from the color-coding, more is better. And our models appear to include significant X features, as evidenced by our Pearson’s correlation coefficients. So if this R2 value was low, perhaps adding additional features would help, such as flight logs, terminal conditions, and even those things airline executives said they weren’t interested in exploring right now, such as knock-off effects and international flights. These could fill in the gaps in the unexplained variance.

Let’s see if we can get good metrics with classification.

Classifying flights as delayed or not delayed with various classification methods

Section titled “Classifying flights as delayed or not delayed with various classification methods”

Just as we did with regression, to compare and contrast classification methods, we will first create a dictionary for them named class_models. Each model is its own dictionary and the function that creates it is the model attribute. This structure will be used later to store the fitted model and its metrics. Model classes in this dictionary have been chosen to represent several model families and to illustrate important concepts that we will discuss later. Some of these will look familiar because they are the same methods used in regression but applied to classification:

class_models = {
#Generalized Linear Models (GLMs)
'logistic':{'model': linear_model.LogisticRegression()},
'ridge':{
'model': linear_model.RidgeClassifierCV(
cv=5, alphas=[1e-3, 1e-2, 1e-1, 1],
class_weight='balanced'
)
},
#Tree
'decision_tree':{
'model': tree. DecisionTreeClassifier(max_depth=7,
random_state=rand)
},
#Nearest Neighbors
'knn':{'model': neighbors.KNeighborsClassifier(n_neighbors=7)},
#Naive Bayes
'naive_bayes':{'model': naive_bayes.GaussianNB()},
#Ensemble Methods
'gradient_boosting':{
'model':ensemble.
GradientBoostingClassifier(n_estimators=210)
},
'random_forest':{
'model':ensemble.RandomForestClassifier(
max_depth=11,class_weight='balanced', random_state=rand
)
},
#Neural Networks
'mlp':{
'model': make_pipeline(
StandardScaler(),
neural_network.MLPClassifier(
hidden_layer_sizes=(7,),
max_iter=500,
early_stopping=True,
random_state=rand
)
)
}
}

Before we start fitting the data to these models, we will briefly explain them one by one:

  • logistic: logistic regression was introduced in Chapter 2, Key Concepts of Interpretability. It has many of the same pros and cons as linear regression. For instance, feature interactions must be added manually. Like other classification models, it returns a probability between 0 and 1, which, when closer to 1, denotes a probable match to a positive class while, when closer to 0, it denotes an improbable match to the positive class, and therefore a probable match to the negative class. Naturally, 0.5 is the threshold used to decide between classes, but it doesn’t have to be. As we will examine later in the book, there are interpretation and performance reasons to adjust the threshold. Note that this is a binary classification problem, so we are only choosing between delayed (positive) and not delayed (negative), but this method could be extended to multi-class classification. It would then be called multinomial classification.
  • ridge: Ridge classification leverages the same regularization technique used in ridge regression but applied to classification. It does this by converting the target values to -1 (for a negative class) and keeping 1 for a positive class and then performing ridge regression. At its heart, its regression in disguise will predict values between -1 and 1, and then convert them back to a 0–1 scale. Like with RidgeCV for regression, RidgeClassifierCV uses leave-one-out cross-validation, which means it first splits the data into different equal-size sets – in this case, we are using five sets (cv=5) – and then removes features one at a time to see how well the model performs without them, on average in all the five sets. Those features that don’t make much of a difference are penalized by testing several regularization strengths (alphas) to find the optimal strength. As with all regularization techniques, the point is to discourage learning from unnecessary complexity, minimizing the impact of less salient features.
  • decision_tree: A standard decision tree, such as this one, is also known as a CART (classification and regression tree) because it can be used for regression or classification tasks. It has the same algorithm for both tasks but functions slightly differently, like the algorithm used to decide where to “split” a branch. In this case, we are only allowing our trees to have a depth of 7.
  • knn: k-NN can also be applied to classification tasks, except instead of averaging what the nearest neighbors’ target features (or labels) are, it chooses the most frequent one (also known as the mode). We are also using a k-value of 7 for classification (n_neighbors).
  • naive_bayes: Gaussian Naïve Bayes is part of the family of Naïve Bayes classifiers, which are called naïve because they make the assumption that the features are independent of each other, which is usually not the case. This dramatically impedes its capacity to predict unless the assumption is correct. It’s called Bayes because it’s based on Bayes’ theorem of conditional probabilities, which is that the conditional probability of a class is the class probability times the feature probability given the class. Gaussian Naïve Bayes makes an additional assumption, which is that continuous values have a normal distribution, also known as a Gaussian distribution.
  • gradient_boosting: Like random forest, gradient-boosted trees are also an ensemble method, but that leverages boosting instead of bagging. Boosting doesn’t work in parallel but in sequence, iteratively training weak learners and incorporating their strengths into a stronger learner, while adapting another weak learner to tackle their weaknesses. Although ensembles and boosting, in particular, can be done with a model class, this method uses decision trees. We have limited the number of trees to 210 (n_estimators=210).
  • random_forest: The same random forest as with regression except it generates classification decision trees and not regression trees.
  • mlp: The same multi-layer perceptron as with regression, but the output layer, by default, uses a logistic function in the output layer to yield probabilities, which it then converts to 1 or 0, based on the 0.5 threshold. Another difference is that we are using seven neurons in the first and only hidden layer (hidden_layer_sizes=(7,)) because binary classification tends to require fewer of them to achieve an optimal result.

Please note that some of these models use balanced weights for the classes (class_weight='balanced'), which is very important because this happens to be an imbalanced classification task. By that, we mean that negative classes vastly outnumber positive classes. We can find out what this looks like for our training data:

print(y_train_class[y_train_class==1].shape[0] y_train_class.shape[0])

As you can see, the output in our training data’s positive classes represents only 6% of the total. Models that account for this will achieve more balanced results. There are different ways of accounting for class imbalance, which we will discuss in further detail in Chapter 11, Bias Mitigation and Causal Inference Methods, but class_weight='balanced' applies a weight inversely proportional to class frequencies, giving the outnumbered positive class a leg up.

Training and evaluating the classification models

Section titled “Training and evaluating the classification models”

Now, let’s iterate over our dictionary of models (class_models), fit them to the training data, and predict both probabilities and the class except for ridge, which doesn’t output probabilities. We’ll then compute five metrics based on the quality of these predictions. Lastly, we’ll save the fitted model, test predictions, and metrics in the dictionary for later use. You can go get a coffee while you run the next snippet of code because gradient_boosting of sklearn takes longer than the rest to train, so this can take a few minutes to run:

for model_name in class_models.keys():
fitted_model = class_models[model_name]
['model'].fit(X_train,y_train_class)
y_train_pred = fitted_model.predict(X_train.values)
if model_name == 'ridge':
y_test_pred = fitted_model.predict(X_test.values)
else:
y_test_prob = fitted_model.predict_proba(X_test.values)[:,1]
y_test_pred = np.where(y_test_prob > 0.5, 1, 0)
class_models[model_name]['fitted'] = fitted_model
class_models[model_name]['probs'] = y_test_prob
class_models[model_name]['preds'] = y_test_pred
class_models[model_name]['Accuracy_train'] =\
metrics.accuracy_score(y_train_class, y_train_pred
)
class_models[model_name]['Accuracy_test'] =\
metrics.accuracy_score(y_test_class, y_test_pred
)
class_models[model_name]['Recall_train'] =\
metrics.recall_score(y_train_class, y_train_pred
)
class_models[model_name]['Recall_test'] =\
metrics.recall_score(y_test_class, y_test_pred
)
if model_name != 'ridge':
class_models[model_name]['ROC_AUC_test'] =\
metrics.roc_auc_score(y_test_class, y_test_prob)
else:
class_models[model_name]['ROC_AUC_test'] = np.nan
class_models[model_name]['F1_test'] =\
metrics.f1_score(y_test_class, y_test_pred
)
class_models[model_name]['MCC_test'] =\
metrics.matthews_corrcoef(y_test_class, y_test_pred
)

We can now convert the dictionary to a DataFrame and display the metrics in a sorted and color-coded fashion:

class_metrics = pd.DataFrame.from_dict(
class_models,'index')[['Accuracy_train', 'Accuracy_test',
'Recall_train', 'Recall_test',
'ROC_AUC_test', 'F1_test', 'MCC_test']
]
class_metrics.sort_values(
by='ROC_AUC_test', ascending=False).
style.format(dict(zip(class_metrics.columns, ['{:.3f}']*7))

).background_gradient(

cmap='plasma', low=1, high=0.1, subset=['Accuracy_train',
'Accuracy_test']

).background_gradient(

cmap='viridis',
low=1,
high=0.1,
subset=['Recall_train', 'Recall_test',
'ROC_AUC_test', 'F1_test', 'MCC_test']
)

The preceding code outputs Figure 3.3:

![Table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_03.png)

Figure 3.3: Classification metrics for our models

To interpret the metrics in Figure 3.3, we ought to first understand what they mean, both in general and in the context of this classification exercise:

  • Accuracy: Accuracy is the simplest way to measure the effectiveness of a classification task, and it’s the percentage of correct predictions over all predictions. In other words, in a binary classification task, you can calculate this by adding the number of True Positives (TPs) and True Negatives (TNs) and dividing them by a tally of all predictions made. As with regression metrics, you can measure accuracy for both train and test to gauge overfitting.

  • Recall: Even though accuracy sounds like a great metric, recall is much better in this case and the reason is you could have an accuracy of 94%, which sounds pretty good, but it turns out you are always predicting no delay! In other words, even if you get high accuracy, it is meaningless unless you are predicting accurately for the least represented class, delays. We can find this number with recall (also known as sensitivity or true positive rate), which is , and it can be interpreted as how much of the relevant results were returned – in other words, in this case, what percentage of the actual delays were predicted. Another good measure involving true positives is precision, which is how much our predicted samples are relevant, which is . In this case, that would be what percentage of predicted delays were actual delays. For imbalanced classes, it is recommended to use both, but depending on your preference for FN over FP, you will prefer recall over precision or vice versa.

  • ROC-AUC: ROC is an acronym for Receiver Operating Characteristic and was designed to separate signal from noise. What it does is plot the proportion of true positive rate (recall) on the x axis and the false positive rate on the y axis. AUC stands for area under the curve, which is a number between 0 and 1 that assesses the prediction ability of the classifier 1 being perfect, 0.5 being as good as a random coin toss, and anything lower meaning that if we inverted the results of our prediction, we would have a better prediction. To illustrate this, let’s generate a ROC curve for our worst-performing model, Naïve Bayes, according to the AUC metric:

    plt.tick_params(axis = 'both', which = 'major')
    fpr, tpr, _ = metrics.roc_curve(
    y_test_class, class_models['naive_bayes']['probs'])
    plt.plot(
    fpr,
    tpr,
    label='ROC curve (area = %0.2f)'
    % class_models['naive_bayes']['ROC_AUC_test']
    )
    plt.plot([0, 1], [0, 1], 'k–') #random coin toss line
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.0])
    plt.legend(loc="lower right")

    The preceding code outputs Figure 3.4. Note that the diagonal line signifies half the area. In other words, the point where it has a coin-toss-like prediction quality: A picture containing polygon
Description automatically generated Figure 3.4: ROC curve for Naïve Bayes

  • F1: The F1-score is also called the harmonic average of precision and recall because it’s calculated like this: . Since it includes both precision and recall metrics, which pertain to the proportion of true positives, it’s a good metric choice to use when your dataset is imbalanced, and you don’t prefer either precision or recall.

  • MCC: The Matthews correlation coefficient is a metric drawn from biostatistics. It’s gaining popularity in the broader data science community because it has the ability to produce high scores considering TP, FN, TN, and FP fairly, because it takes into account the proportions of classes. This makes it optimal for imbalanced classification tasks. Unlike all other metrics used so far, it doesn’t range from 0 to 1 but from -1, complete disagreement, to 1, a total agreement between predictions and actuals. The mid-point, 0, is equivalent to a random prediction:

Our classification metrics are mostly very good, exceeding 96% accuracy and 75% recall. However, even recall isn’t everything. For instance, RandomForest, due to its class balancing with weights, got the highest recall but did poorly in F1 and MCC, which suggests that precision is not very good.

Ridge classification also had the same setting and had such a poor F1 score that the precision must have been dismal. This doesn’t mean this weighting technique is inherently wrong, but it often requires more control. This book will cover techniques to achieve the right balance between fairness and accuracy, accuracy and reliability, reliability and validity, and so on. This is a balancing act that requires many metrics and visualizations. A key takeaway from this exercise should be that a single metric will not tell you the whole story, and interpretation is about telling the most relevant and sufficiently complete story.

Understanding limitations of traditional model interpretation methods

Section titled “Understanding limitations of traditional model interpretation methods”

In a nutshell, traditional interpretation methods only cover high-level questions about your models such as the following:

  • In aggregate, do they perform well?
  • What changes in hyperparameters may impact predictive performance?
  • What latent patterns can you find between the features and their predictive performance?

These questions are very limiting if you are trying to understand not only whether your model works but why and how?

This gap in understanding can lead to unexpected issues with your model that won’t necessarily be immediately apparent. Let’s consider that models, once deployed, are not static but dynamic. They face different challenges than they did in the “lab” when you were training them. They may face not only performance issues but issues with bias, such as imbalance with underrepresented classes, or security vulnerabilities with adversarial attacks. Realizing that the features have changed in the real-world environment, we might have to add new features instead of merely retraining with the same feature set. And if there are some troubling assumptions made by your model, you might have to re-examine the whole pipeline. But how do you recognize that these problems exist in the first place? That’s when you will need a whole new set of interpretation tools that can help you dig deeper and answer more specific questions about your model. These tools provide interpretations that can truly account for Fairness, Accountability, and Transparency (FAT), which we discussed in Chapter 1, Interpretation, Interpretability, and Explainability; and Why Does It All Matter?

Studying intrinsically interpretable (white-box) models

Section titled “Studying intrinsically interpretable (white-box) models”

So far, in this chapter, we have already fitted our training data to model classes representing each of these “white-box” model families. The purpose of this section is to show you exactly why they are intrinsically interpretable. We’ll do so by employing the models that were previously fitted.

GLMs are a large family of model classes that have a model for every statistical distribution. Just like linear regression assumes your target feature and residuals have a normal distribution, logistic regression assumes the Bernoulli distribution. There are GLMs for every distribution, such as Poisson regression for Poisson distribution and multinomial response for multinomial distribution. You choose which GLM to use based on the distribution of your target variable and whether your data meets the other assumptions of the GLM (they vary). In addition to an underlying distribution, what ties GLMs together into a single family is the fact that they all have a linear predictor. In other words, the target variable (or predictor) can be expressed mathematically as a weighted sum of X features, where weights are called b coefficients. This is the simple formula, the linear predictor function, that all GLMs share:

However, although they share this same formula, they each have a different link function, which provides a link between the linear predictor function and the mean of the statistical distribution of the GLM. This can add some non-linearity to the resulting model formula while retaining the linear combination between the b coefficients and the X input data, which can be a source of confusion. Still, it’s linear because of the linear combination.

There are also many variations for specific GLMs. For instance, Polynomial regression is linear regression with polynomials of its features, and ridge regression is linear regression with L2 regularization. We won’t cover all GLMs in this section because they aren’t needed for the example in this chapter, but all have plausible use cases.

Incidentally, there’s also a similar concept called Generalized Additive Models (GAMs), which are GLMs that don’t require linear combinations of features and coefficients and instead retain the addition part, but of arbitrary functions applied to the features. GAMs are also interpretable, but they are not as common, and are usually tailored to specific use cases ad hoc.

In Chapter 1, Interpretation, Interpretability, and Explainability, and Why Does It All Matter?, we covered the formula of simple linear regression, which only has a single X feature. Multiple linear regression extends this to have any number of features, so instead of being:

it can be:

with *n* features, and where ![](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_011.png) is the intercept, and thanks to linear algebra this can be a simple matrix multiplication:

The method used to arrive at the optimal b coefficients, OLS, is well-studied and understood. Also, in addition to the coefficients, you can extract confidence intervals for each. The model’s correctness depends on whether the input data meets the assumptions: linearity, normality, independence, a lack of multicollinearity, and homoscedasticity. We’ve discussed linearity, so far, quite a bit so we will briefly explain the rest:

  • Normality is the property that each feature is normally distributed. This can be tested with a Q-Q plot, histogram, or Kolmogorov-Smirnov test, and non-normality can be corrected with non-linear transformations. If a feature isn’t normally distributed, it will make its coefficient confidence intervals invalid.
  • Independence is when your observations (the rows in your dataset) are independent of each other, like different and unrelated events. If your observations aren’t independent, it could affect your interpretation of the results. In this chapter’s example, if you had multiple rows about the same flight, that could violate this assumption and make results hard to understand. This can be tested by looking for duplicate flight numbers.
  • Multicollinearity occurs when the features are highly correlated with each other. Lack of multicollinearity is desirable because otherwise, you’d have inaccurate coefficients. This can be tested with a correlation matrix, tolerance measure, or Variance Inflation Factor (VIF), and it can be fixed by removing one of each highly correlated feature.
  • Homoscedasticity was briefly discussed in Chapter 1, Interpretation, Interpretability, and Explainability; and Why Does It All Matter? and it’s when the residuals (the errors) are more or less equal across the regression line. This can be tested with the Goldfeld–Quandt test, and heteroscedasticity (the lack of homoscedasticity) can be corrected with non-linear transformations. This assumption is often violated in practice.

Even though we haven’t done it for this chapter’s example, if you are going to rely on linear regression heavily, it’s always good to test these assumptions before you even begin to fit your data to a linear regression model. This book won’t detail how this is done because it’s more about model-agnostic and deep-learning interpretation methods than delving into how to meet the assumptions of a specific class of models, such as normality and homoscedasticity. However, we covered the characteristics that trump interpretation the most in Chapter 2, Key Concepts of Interpretability, and we will continue to look for these characteristics: non-linearity, non-monotonicity, and interactivity. We will do this mainly because the linearity and correlation of and between features are still relevant, regardless of the modeling class used to make predictions. And these are characteristics that can be easily tested in the methods used for linear regression.

So how do we interpret a linear regression model? Easy! Just get the coefficients and the intercept. Our scikit-learn models have these attributes embedded in the fitted model:

coefs_lm = reg_models['linear']['fitted'].coef_
intercept_lm = reg_models['linear']['fitted'].intercept_
print('coefficients:%s' % coefs_lm)
print('intercept:%s' % intercept_lm)

The preceding code outputs the following:

coefficients: [ 0.0045 -0.0053 0.8941 0.0152 …]

intercept: -37.86

So now you know the formula, which looks something like this:

This formula should provide some intuition on how the model can be interpreted globally. Interpreting each coefficient in the model can be done for multiple linear regression, just as we did with the simple linear regression example in Chapter 1, Interpretation, Interpretability, and Explainability; and Why Does It All Matter?. The coefficients act as weights, but they also tell a story that varies depending on the kind of feature. To make interpretation more manageable, let’s put our coefficients in a DataFrame alongside the names of each feature:

pd.DataFrame({‘feature’: X_train.columns.tolist(),
‘coef’: coefs_lm.tolist()})

The preceding code produces the DataFrame in Figure 3.5:

![Table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_05.png)

Figure 3.5: Coefficients of linear regression features

Here’s how to interpret a feature using the coefficients in Figure 3.5:

  • Continuous: Like ARR_RFPH, you know that for every one-unit increase (relative flights per hour), it increases the predicted delay by 0.373844 minutes, if all other features stay the same.
  • Binary: Like ORIGIN_HUB, you know the difference between the origin airport being a hub or not is expressed by the coefficient -1.029088. In other words, since it’s a negative number, the origin airport is a hub. It reduces the delay by just over 1 minute if all other features stay the same.
  • Categorical: We don’t have categorical features, but we have ordinal features that could have been, and actually should have been, categorical features. For instance, DEP_MONTH and DEP_DOW are integers from 1–12 and 0–6, respectively. If they are treated as ordinals, we are assuming because of the linear nature of linear regression that an increase or decrease in months has an impact on the outcome. It’s the same with the day of the week. But the impact is tiny. Had we treated them as dummy or one-hot encoded features, we could measure whether Fridays are more prone to carrier delays than Saturdays and Wednesdays, or Julys more than Octobers and Junes. This couldn’t possibly be modeled with them in order, because they have no relation to this order (yep – it’s non-linear!). So, say we had a feature called DEP_FRIDAY and another called DEP_JULY. They are treated like binary features and can tell you precisely what effect a departure being on a Friday or in July has on the model. Some features were kept as ordinal or continuous on purpose, despite being good candidates for being categorical, to demonstrate how not making the right adjustments to your features can impact the expressive power of model interpretation. It would have been good to tell airline executives more about how the day and time of a departure impacted delays. Also, in some cases – not in this one – an oversight like this can grossly affect a linear regression model’s performance.

The intercept (-37.86) is not a feature, but it does have a meaning, which is, if all features were at 0, what would the prediction be? In practice, this doesn’t happen unless your features happen to all have a plausible reason to be 0. Just as in Chapter 1, Interpretation, Interpretability, and Explainability; and Why Does It All Matter? you wouldn’t have expected anyone to have a height of 0, in this example, you wouldn’t expect a flight to have a distance of 0. However, if you standardized the features so that they had a mean of 0, then you would change the interpretation of the intercept to be the prediction you expect if all features are their mean value.

The coefficients can also be leveraged to calculate feature importance. Unfortunately, scikit-learn’s linear regressor is ill-equipped to do this because it doesn’t output the standard error of the coefficients. According to their importance, all it takes to rank features is to divide the s by their corresponding standard errors. This result is something called the t-statistic:

And then you take an absolute value of this and sort them from high to low. It’s easy enough to calculate, but you need the standard error. You could reverse-engineer the linear algebra involved to retrieve it using the intercept, and the coefficients returned by scikit-learn. However, it’s probably a lot easier to fit the linear regression model again, but this time using the statsmodels library, which has a summary with all the statistics included! By the way, statsmodels names its linear regressor OLS, which makes sense because OLS is the name of the mathematical method that fits the data:

linreg_mdl = sm.OLS(y_train_reg, sm.add_constant(X_train))
linreg_mdl = linreg_mdl.fit()
print(linreg_mdl.summary())

There’s quite a bit to unpack in the regression summary. This book won’t address everything except that the t-statistic can tell you how important features are in relation to each other. There’s another more pertinent statistical interpretation, which is that if you were to hypothesize that the b coefficient is 0 – in other words, that the feature has no impact on the model – the distance of the t-statistic from 0 helps reject that null hypothesis. This is what the p-value to the right of the t-statistic does. It’s no coincidence that the closest t to 0 (for ARR_AFPH) has the only p-value above 0.05. This puts this feature at a level of insignificance since everything below 0.05 is statistically significant according to this method of hypothesis testing.

So to rank our features, let’s extract the DataFrame from the statsmodels summary. Then, we drop the const (the intercept) because this is not a feature. Then, we make a new column with the absolute value of the t-statistic and sort it accordingly. To demonstrate how the absolute value of the t-statistic and p-value are inversely related, we are also color-coding these columns:

summary_df = linreg_mdl.summary2().tables[1]
summary_df = summary_df.drop(
['const']).reset_index().rename(columns={'index':'feature'}
)
summary_df['t_abs'] = abs(summary_df['t'])
summary_df.sort_values(by='t_abs', ascending=False).
style.format(
dict(zip(summary_df.columns[1:], ['{:.4f}']*7)
)
).background_gradient(cmap='plasma_r', low=0, high=0.1,\
subset=['P>|t|', 't_abs'])

The preceding code outputs Figure 3.6:

![Table, Excel

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_06.png)

Figure 3.6: Linear regression summary table sorted by the absolute value of the t-statistic

Something particularly interesting about the feature importance in Figure 3.6 is that different kinds of delays occupy five out of the top six positions. Of course, this could be because linear regression is confounding the different non-linear effects these have, or perhaps there’s something here we should look further into – especially since the statsmodels summary in the “Warnings” section cautions:

[2] The condition number is large, 5.69e+04. This might indicate that there are strong multicollinearity or other numerical problems.

This is odd. Hold that thought. We will examine this further later.

Ridge regression is part of a sub-family of penalized or regularized regression along with the likes of LASSO and ElasticNet because, as explained earlier in this chapter, it penalizes using the L2 norm. This sub-family is also called sparse linear models because, thanks to the regularization, it cuts out some of the noise by making irrelevant features less relevant. Sparsity in this context means less is more because reduced complexity will lead to lower variance and improved generalization.

To illustrate this concept, look at the feature importance table (Figure 3.6) we output for linear regression. Something that should be immediately apparent is how the t_abs column starts with every row a different color, and then a whole bunch of them are the same shade of yellow. Because of the variation in confidence intervals, the absolute t-value is not something you can take proportionally and say that your top feature is hundreds of times more relevant than every one of your bottom 10 features. However, it should indicate that there are significantly more important features than others to the point of irrelevance, and possibly confoundment, hence creating noise. There’s ample research on how there’s a tendency for a small subset of features to have the most substantial effects on the outcome of the model. This is called the bet on sparsity principle. Whether it’s true or not for your data, it’s always good to test the theory by applying regularization, especially in cases where data is very wide (many features) or exhibits multicollinearity. These regularized regression techniques can be incorporated into feature selection processes or to inform your understanding of what features are essential.

There is a technique to adapt ridge regression to classification problems. It was briefly discussed before. It converts the labels to a -1 to 1 scale for training to predict values between -1 and 1, and then turns them back to a 0–1 scale. However, it uses regularized linear regression to fit the data and can be interpreted in the same way.

Ridge regression can be interpreted in the same way as linear regression, both globally and locally, because once the model has been fitted, there’s no difference. The formula is the same:

Except coefficients are different because they were penalized with a parameter, which controls how much shrinkage to apply.

We can quickly compare coefficients by extracting the ridge coefficients from their fitted model and placing them side by side in a DataFrame with the coefficients of the linear regression:

coefs_ridge = reg_models['ridge']['fitted'].coef_
coef_ridge_df =pd.DataFrame(
{
'feature':X_train.columns.values.tolist(),
'coef_linear': coefs_lm,\
'coef_ridge': coefs_ridge
}
)
coef_ridge_df['coef_regularization'] =\
coef_ridge_df['coef_linear'] - coef_ridge_df['coef_ridge']
coef_ridge_df.style.background_gradient(
cmap='plasma_r', low=0, high=0.1 , subset=['coef_regularization']
)

As you can tell in the Figure 3.7 output of the preceding code, the coefficients are always slightly different, but sometimes they are lower and sometimes higher:

![Table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_07.png)

Figure 3.7: Linear regression coefficients compared to ridge regression coefficients

We didn’t save the parameter (which scikit-learn calls alpha) that the ridge regression cross-validation deemed optimal. However, we can run a little experiment of our own to figure out which parameter was the best. We do this by iterating through 100 possible alphas values between 100 (1) and 1013 (100,000,000,000,000), fitting the data to the ridge model, and then appending the coefficients to an array. We exclude the eight coefficient in the array because it’s so much larger than the rest, and it will make it harder to visualize the effects of shrinkage:

num_alphas = 100
alphas = np.logspace(0, 13, num_alphas)
alphas_coefs = []
for alpha in alphas:
ridge = linear_model.Ridge(alpha=alpha).fit(
X_train, y_train_reg)
alphas_coefs.append(np.concatenate((ridge.coef_[:8],
ridge.coef_[9:])))

Now that we have an array of coefficients, we can plot the progression of coefficients:

plt.gca().invert_xaxis()
plt.tick_params(axis = 'both', which = 'major')
plt.plot(alphas, alphas_coefs)
plt.xscale("log")
plt.xlabel('Alpha')
plt.ylabel('Ridge coefficients')
plt.grid()
plt.show()

The preceding code generates Figure 3.8:

![Chart, line chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_08.png)

Figure 3.8: Value of alpha hyperparameters versus the value of ridge regression coefficients

Something to note in Figure 3.8 is that the higher the alpha, the higher the regularization. This is why when alpha is 1012, all coefficients have converged to 0, and as the alpha becomes smaller, they get to a point where they have all diverged and more or less stabilized. In this case, this point is reached at about 102. Another way of seeing it is when all coefficients are around 0, it means that the regularization is so strong that all features are irrelevant. When they have sufficiently diverged and stabilized, the regularization makes them all relevant, which defeats the purpose.

Now on that note, if we go back to our code, we will find that this is what we chose for alphas in our RidgeCV: alphas=[1e-3, 1e-2, 1e-1, 1]. As you can tell from the preceding plot, by the time the alphas have reached 1 and below, the coefficients have already stabilized even though they are still fluctuating slightly. This can explain why our ridge was not better performing than linear regression. Usually, you would expect a regularized model to perform better than one that isn’t – unless your hyperparameters are not right.

Interpretation and hyperparameters

Well-tuned regularization can help cut out the noise and thus increase interpretability, but the alphas chosen for RidgeCV were selected on purpose to be able to convey this point: regularization can only work if you chose hyperparameters correctly, or, when regularization hyperparameter tuning is automatic, the method must be optimal for your dataset.

This is precisely the same as with linear regression, but again we need the standard error of the coefficients, which is something that cannot be extracted from the scikit-learn model. You can use the statsmodels fit_regularized method to this effect.

Polynomial regression is a special case of linear or logistic regression where the features have been expanded to have higher degree terms. We have only performed polynomial linear regression in this chapter’s exercise, so we will only discuss this variation. However, it is applied similarly.

A two-feature multiple linear regression would look like this:

However, in polynomial regression, every feature is expanded to have higher degree terms and interactions between all the features. So, if this two-feature example was expanded to a second-degree polynomial, the linear regression formula would look like this:

It’s still linear regression in every way except it has extra features, higher-degree terms, and interactions. While you can limit polynomial expansion to only one or a few features, we used PolynomialFeatures, which does this to all features. Therefore, 21 features were likely multiplied many times over. We can extract the coefficients from our fitted model and, using the shape property of the numpy array, return how many coefficients were generated. This amount corresponds to the number of features generated:

reg_models[‘linear_poly’][‘fitted’].
get_params()[‘linearregression’].coef_.shape[0]

It outputs 253. We can do the same with the version of polynomial regression, which was with interaction terms only:

reg_models[‘linear_interact’][‘fitted’].
get_params()[‘linearregression’].coef_.shape[0]

The above code outputs 232. The reality is that most terms in a polynomial generated like this are interactions between all the features.

Polynomial regression can be interpreted, both globally and locally, in precisely the same way as linear regression. In this case, it’s not practical to understand a formula with 253 linearly combined terms, so it loses what we defined in Chapter 2, Key Concepts of Interpretability, as global holistic interpretation. However, it still can be interpreted in all other scopes and retains many of the properties of linear regression. For instance, since the model is additive, it is easy to separate the effects of the features. You can also use the same many peer-reviewed tried and tested statistical methods that are used for linear regression. For instance, you can use the t-statistic, p-value, confidence bounds, R-squared, as well as the many tests used to assess goodness of fit, residual analysis, linear correlation, and analysis of variance. This wealth of statistically proven methods to test and interpret models isn’t something most model classes can count on. Unfortunately, many of them are model-specific to linear regression and its special cases.

Also, we won’t do it here because there are so many terms. Still, you could undoubtedly rank features for polynomial regression in the same way we have for linear regression using the statsmodels library. The challenge is figuring out the order of the features generated by PolynomialFeatures to name them accordingly in the feature name column. Once this is done, you can tell if some second-degree terms or interactions are important. This could tell you if these features have a non-linear nature or highly depend on other features.

We discussed logistic regression as well as its interpretation and feature importance in Chapter 2, Key Concepts of Interpretability. We will only expand on that a bit here in the context of this chapter’s classification exercise and to underpin why exactly it is interpretable. The fitted logistic regression model has coefficients and intercepts just as the linear regression model does:

coefs_log = class_models['logistic']['fitted'].coef_
intercept_log = class_models['logistic']['fitted'].intercept_
print('coefficients:%s' % coefs_log)
print('intercept:%s' % intercept_log)

The preceding code outputs this:

coefficients: [[-6.31114061e-04 -1.48979793e-04 2.01484473e-01 1.32897749e-01 1.31740116e-05 -3.83761619e-04 -7.60281290e-02 ..]]

intercept: [-0.20139626]

However, the way these coefficients appear in the formula for a specific prediction is entirely different:

In other words, the probability that (is a positive case) is expressed by a logistic function that involves exponentials of the linear combination of coefficients and the x features. The presence of the exponentials explains why the coefficients extracted from the model are log odds because to isolate the coefficients, you should apply a logarithm to both sides of the equation.

To interpret each coefficient, you do it in precisely the same way as with linear regression, except with each unit increase in the features, you increase the odds of getting the positive case by a factor expressed by the exponential of the coefficient – all things being equal (remember the ceteris paribus assumption discussed in Chapter 2, Key Concepts of Interpretability). An exponential () has to be applied to each coefficient because they express an increase in log odds and not odds. Besides incorporating the log odds into the interpretation, the same that was said about continuous, binary, and categorical in linear regression interpretation applies to logistic regression.

Frustrating as it is, there isn’t consensus yet from the statistical community on how to best get feature importance for logistic regression. There’s a standardize-all-features-first method, a pseudo R2 method, a one feature at a time ROC AUC method, a partial chi-squared statistic method, and then the simplest one, which is multiplying the standard deviations of each feature times the coefficients. We won’t cover all these methods, but it has to be noted that computing feature importance consistently and reliably is a problem for most model classes, even white-box ones. We will dig deeper into this in Chapter 4, Global Model-Agnostic Interpretation Methods. For logistic regression, perhaps the most popular method is achieved by standardizing all the features before training – that is, making sure they are centered at zero and divided by their standard deviation. But we didn’t do this because although it has other benefits, it makes the interpretation of coefficients more difficult, so here we are using the rather crude method leveraged in Chapter 2, Key Concepts of Interpretability, which is to multiply the standard deviations of each feature times the coefficients:

stdv = np.std(X_train, 0)
abs(coefs_log.reshape(21,) * stdv).sort_values(ascending=False)

The preceding code yields the following output:

DEP_DELAY 8.92 CRS_ELAPSED_TIME 6.03

DISTANCE 5.31

LATE_AIRCRAFT_DELAY 4.99 NAS_DELAY 2.39 WEATHER_DELAY 2.16 TAXI_OUT 1.31 SECURITY_DELAY 0.38 ARR_AFPH 0.32 WHEELS_OFF 0.01 PCT_ELAPSED_TIME 0.003

It can still approximate the importance of features quite well. And just like with linear regression, you can tell that delay features are ranking quite high. All five of them are among the top eight features. Indeed, it’s something we should look into. We will discuss more on that as we discuss some other white-box methods.

Decision trees have been used for the longest time, even before they were turned into algorithms. They hardly require any mathematical abilities to understand them, and this low barrier to comprehensibility makes them extremely interpretable in their simplest representations. However, in practice, there are many types of decision tree learning, and most of them are not very interpretable because they use ensemble methods (boosting, bagging, and stacking), or even leverage PCA or some other embedder. Even non-ensembled decision trees can get extremely complicated as they become deeper. Regardless of the complexity of a decision tree, they can always be mined for important insights about your data and expected predictions, and they can be fitted to both regression and classification tasks.

The Classification and Regression Trees (CART) algorithm is the “vanilla” no-frills decision tree of choice in most use cases. And as noted, most decision trees aren’t white-box models, but this one is because it is expressed as a mathematical formula, visualized, and printed as a set of rules that subdivides the tree into branches and eventually the leaves.

The mathematical formula:

And what this means is that if according to the identity function I, x is in the subset Rm, then it returns a 1, otherwise a 0. This binary term is multiplicated by the averages of all elements in the subset Rm denoted as . So if xi is in the subset belonging to the leaf node Rk then the prediction . In other words, the prediction is the average of all elements in the subsetRk. This is what happens to regression tasks, and in binary classification, there is simply no to multiply the I identify function.

At the heart of every decision tree algorithm, there’s a method to generate the Rm subsets. For CART, this is achieved using something called the Gini index, recursively splitting on where the two branches are as different as possible. This concept will be explained in greater detail in Chapter 4, Global Model-Agnostic Interpretation Methods.

A decision tree can be globally and locally interpreted visually. Here, we have established a maximum depth of 2 (max_depth=2) because we could generate all 7 layers, but the text would be too small to appreciate. One of the limitations of this method is that it can get complicated to visualize with depths above 3 or 4. However, you can always programmatically traverse the branches of the tree and visualize only some branches at a time:

fig, axes = plt.subplots(
nrows = 1, ncols = 1, figsize = (16,8), dpi=600)
tree.plot_tree(
class_models['decision_tree']['fitted'],
feature_names=X_train.columns.values.tolist(),
filled = True, max_depth=2
)
fig.show()

The preceding code prints out the tree in Figure 3.9. From the tree, you can tell that the very first branch splits the decision tree based on the value of DEP_DELAY being equal to or smaller than 20.5. It tells you the Gini index that informed that decision and the number of samples (just another way of saying observations, data points, or rows) present. You can traverse these branches till they reach a leaf. There is one leaf node in this tree, and it is on the far left. This is a classification tree, so you can tell by the value =[629167, 0] that all 629,167 samples left in this node have been classified as a 0 (not delayed):

Figure 3.9: Our models’ plotted decision tree

Another way the tree can be better visualized but with fewer details, such as the Gini index and sample size, is by printing out the decisions made in every branch and the class in every node:

text_tree = tree.export_text(
class_models['decision_tree']['fitted'],
feature_names=X_train.columns.values.tolist()
)
print(text_tree)

And the preceding code outputs the following:

![A close-up of a document

Description automatically generated with medium confidence](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_10.png)

Figure 3.10: Our decision tree’s structure

There’s a lot more that can be done with a decision tree, and scikit-learn provides an API to explore the tree.

Calculating feature importance in a CART decision tree is reasonably straightforward. As you can appreciate from the visualizations, some features appear more often in the decisions, but their appearances are weighted by how much they contributed to the overall reduction in the Gini index compared to the previous node. All the sum of the relative decrease in the Gini index throughout the tree is tallied, and the contribution of each feature is a percentage of this reduction:

dt_imp_df = pd.DataFrame(
{
'feature':X_train.columns.values.tolist(),
'importance': class_models['decision_tree']['fitted'].\
feature_importances_
}
).sort_values(by='importance', ascending=False)

dt_imp_df

The dt_imp_df DataFrame output by the preceding code can be appreciated in Figure 3.11:

![Table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_11.png)

Figure 3.11: Our decision tree’s feature importance

This last feature importance table, Figure 3.11, increases suspicions about the delay features. They occupy, yet again, five of the top six positions. Is it possible that all five of them have such an outsized effect on the model?

Interpretation and domain expertise

The target CARRIER_DELAY is also called a dependent variable because it’s dependent on all the other features, the independent variables. Even though a statistical relationship doesn’t imply causation, we want to inform our feature selection based on our understanding of what independent variables could plausibly affect a dependent one.

It makes sense that a departure delay (DEPARTURE_DELAY) affects the arrival delay (which we removed), and therefore, CARRIER_DELAY. Similarly, LATE_AIRCRAFT_DELAY makes sense as a predictor because it is known before the flight takes off if a previous aircraft was several minutes late, causing this flight to be at risk of arriving late, but not as a cause of the current flight (ruling this option out). However, even though the Bureau of Transportation Statistics website defines delays in such a way that they appear to be discrete categories, some may be determined well after a flight has departed. For instance, in predicting a delay mid-flight, could we use WEATHER_DELAY if the bad weather hasn’t yet happened? And could we use SECURITY_DELAY if the security breach hasn’t yet occurred? The answers to these questions are that we probably shouldn’t because the rationale for including them is they could serve to rule out CARRIER_DELAY, but this only works if they are discrete categories that pre-date the dependent variable! If they don’t they would be producing what is known as data leakage. Before coming to further conclusions, what you would need to do is talk to the airline executives to determine the timeline on which each delay category gets consistently set and (hypothetically) is accessible from the cockpit or the airline’s command center. Even if you are forced to remove them from the models, maybe other data can fill the void in a meaningful way, such as the first 30 minutes of flight logs and/or historical weather patterns.

Interpretation is not always directly inferred from the data and the machine learning models, but by working closely with domain experts. But sometimes domain experts can mislead you too. In fact, another insight is with all the time-based metrics and categorical features we engineered at the beginning of the chapter (DEP_DOW, DEST_HUB, ORIGIN_HUB, and so on). It turns out they have consistently had little to no effect on the models. Despite the airline executives hinting at the importance of days of the week, hubs, and congestion, we should have explored the data further, looking for correlations before engineering the data. But even if we do engineer some useless features, it also helps to use a white-box model to assess their impact, as we have. In data science, practitioners often will learn the same way that the most performant machine learning models do – by trial and error!

RuleFit is a model-class family that is a hybrid between a LASSO linear regression to get regularized coefficients for every feature and decision rules, which also uses LASSO to regularize. These decision rules are extracted by traversing a decision tree, finding interaction effects between features, and assigning coefficients to them based on their impact on the model. The implementation used in this chapter uses gradient-boosted decision trees to perform this task.

We haven’t covered decision rules explicitly in this chapter, but they are yet another family of intrinsically interpretable models. They weren’t included because, at the time of writing, the only Python library that supports decision rules, called Bayesian Rule List (BRL) by Skater, is still at an experimental stage. In any case, the concept behind decision rules is very similar. They extract the feature interactions from a decision tree but don’t discard the leaf node, and instead of assigning coefficients, they use the predictions in the leaf node to construct the rules. The last rule is a catch-all, like an ELSE statement. Unlike RuleFit, it can only be understood sequentially because it’s so similar to any IF-THEN-ELSE statement, but that’s its main advantage.

You can put everything you need to know about RuleFit into a single DataFrame (rulefit_df). Then you remove the rules that have a coefficient of 0. It has these because in LASSO, unlike ridge, coefficient estimates converge to zero. You can sort the DataFrame by importance in a descending manner to see what features or feature interactions (in the form of rules) are most important:

rulefit_df = reg_models['rulefit']['fitted'].get_rules()
rulefit_df = rulefit_df[rulefit_df.coef !=0].\
sort_values(
by="importance", ascending=False
)

rulefit_df

The rules in the rulefit_df DataFrame can be seen in Figure 3.12:

![Table

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_12.png)

Figure 3.12: RuleFit’s rules

There’s a type for every RuleFit feature in Figure 3.12. Those that are linear are interpreted as you would any linear regression coefficient. Those that are type=rule are also to be treated like binary features in a linear regression model. For instance, if the rule LATE_AIRCRAFT_DELAY <= 333.5 & DEP_DELAY > 477.5 is true, then the coefficient 172.103034 is applied to the prediction. The rules capture the interaction effects, so you don’t have to add interaction terms to the model manually or use some non-linear method to find them. Furthermore, it does this in an easy-to-understand manner. You can use RuleFit to guide your understanding of feature interactions even if you choose to productionize other models.

Nearest neighbors is a family of models that even includes unsupervised methods. All of them use the closeness between data points to inform their predictions. Of all these methods, only the supervised k-NN and its cousin Radius Nearest Neighbors are somewhat interpretable.

The idea behind k-NN is straightforward. It takes the k closest points to a data point in the training data and uses their labels (y_train) to inform the predictions. If it’s a classification task, it’s the mode of all the labels, and if it’s a regression task, it’s the mean. It’s a lazy learner because the “fitted model” is not much more than the training data and the parameters, such as k and the list of classes (if it’s a classification). It doesn’t do much till inference. That’s when it leverages the training data, tapping into it directly rather than extracting parameters, weights/biases, or coefficients learned by the model as eager learners do.

k-NN only has local interpretability because since there’s no fitted model, you don’t have global modular or global holistic interpretability. For classification tasks, you could attempt to get a sense of this using the decision boundaries and regions we studied in Chapter 2, Key Concepts of Interpretability. Still, it’s always based on local instances.

To interpret a local point from our test dataset, we query the pandas DataFrame using its index. We will be using flight #721043:

print(X_test.loc[721043,:])

The preceding code outputs the following pandas series:

CRS_DEP_TIME 655.00 DEP_TIME 1055.00 DEP_DELAY 240.00 TAXI_OUT 35.00 WHEELS_OFF 1130.00 CRS_ARR_TIME 914.00 CRS_ELAPSED_TIME 259.00 DISTANCE 1660.00WEATHER_DELAY 0.00 NAS_DELAY 22.00 SECURITY_DELAY 0.00 LATE_AIRCRAFT_DELAY 221.00 DEP_AFPH 90.80 ARR_AFPH 40.43 DEP_MONTH 10.00 DEP_DOW 4.00 DEP_RFPH 0.89 ARR_RFPH 1.06 ORIGIN_HUB 1.0 DEST_HUB 0.00 PCT_ELAPSED_TIME 1.084942 Name: 721043, dtype: float64

In the y_test_class labels for flight #721043, we can tell that it was delayed because this code outputs 1:

print(y_test_class[721043])

However, our k-NN model predicted that it was not because this code outputs 0:

print(class_models['knn']['preds'][X_test.index.get_loc(721043)])

Please note that the predictions are output as a numpy array, so we can’t access the prediction for flight #721043 using its pandas index (721043). We have to use the sequential location of this index in the test dataset using get_loc to retrieve it.

To find out why this was the case, we can use kneighbors on our model to find the seven nearest neighbors of this point. To this end, we have to reshape our data because kneighbors will only accept it in the same shape found in the training set, which is (n, 21) where n is the number of observations (rows). In this case, n=1 because we only want the nearest neighbors for a single data point. And as you can tell from what was output by X_test.loc[721043,:], the pandas series has a shape of (21,1), so we have to reverse this shape:

print(class_models['knn']['fitted'].\
kneighbors(X_test.loc[721043,:].values.reshape(1,21), 7))

kneighbors outputs two arrays:

(array([[143.3160128 , 173.90740076, 192.66705727, 211.57109221, 243.57211853, 259.61593993, 259.77507391]]), array([​[105172, 571912, 73409, 89450, 77474, 705972, 706911]​]))

The first is the distance of each of the seven closest training points to our test data point. And the second is the location of these data points in the training data:

print(y_train_class.iloc[[105172, 571912, 73409, 89450, 77474,\
705972, 706911]])

The preceding code outputs the following pandas series:

3813 0 229062 1 283316 0 385831 0 581905 1 726784 1 179364 0 Name: CARRIER_DELAY, dtype: int64

We can tell that the prediction reflects the mode because the most common class in the seven nearest points was 0 (not delayed). You can increase or decrease the k to see if this holds. Incidentally, when using binary classification, it’s recommended to choose an odd-numbered k so that there are no ties. Another important aspect is the distance metric that was used to select the closest data points. You can easily find out which one it is using:

print(class_models['knn']['fitted'].effective_metric_)

The output is Euclidean, which makes sense for this example. After all, Euclidean is optimal for a real-valued vector space because most features are continuous. You could also test alternative distance metrics such as minkowski, seuclidean, or mahalanobis. When most of your features are binary and categorical, you have an integer-valued vector space. So your distances ought to be calculated with algorithms suited for this space such as hamming or canberra.

Feature importance is, after all, a global model interpretation method and k-NN has a hyper-local nature, so there’s no way of deriving feature importance from a k-NN model.

Like GLMs, Naïve Bayes is a family of model classes with a model tailored to different statistical distributions. However, unlike GLMs’ assumption that the target y feature has the chosen distribution, all Naïve Bayes models assume that your X features have this distribution. More importantly, they were based on Bayes’ theorem of conditional probability, so they output a probability and are, therefore, exclusively classifiers. But they treat the probability of each feature impacting the model independently, which is a strong assumption. This is why they are called naïve. There’s one for Bernoulli called Bernoulli Naïve Bayes, one for multinomial called Multinomial Naïve Bayes, and, of course, one for Gaussian, which is the most common.

Bayes’ theorem is defined by this formula:

In other words, to find the probability of A happening given that B is true, you take the conditional probability of B given A is true times the probability of A occurring, divided by the probability of B. In the context of a machine learning classifier, this formula can be rewritten as follows:

This is because what we want is the probability of y given X is true. But our X has more than one feature, so this can be expanded like this:

To compute predictions, we have to consider that we have to calculate and compare probabilities for each Ck class (the probability of a delay versus the probability of no delay) and choose the class with the highest probability:

Calculating the probability of each class (also known as the class prior) is relatively trivial. In fact, the fitted model has stored this in an attribute called class_prior_:

print(class_models['naive_bayes']['fitted'].class_prior_)

This outputs the following:

array([0.93871674, 0.06128326])

Naturally, since delays caused by the carrier only occur 6% of the time, there is a marginal probability of this occurring.

Then the formula has a product of conditional probabilities that each feature belongs to a class . Since this is binary there’s no need to calculate the probabilities of multiple classes because they are inversely proportional. Therefore, we can drop Ck and replace it with a 1 like this:

This is because what we are trying to predict is the probability of a delay. Also, is its own formula, which differs according to the assumed distribution of the model – in this case, Gaussian:

This formula is called the probability density of the Gaussian distribution.

So what are these sigmas () and thetas () in the formula? They are, respectively, the variance and mean of the xi feature when . The concept behind this is that features have a different variance and mean in one class versus another, which can inform the classification. This is a binary classification task, but you could calculate and for both classes. Fortunately, the fitted model has this stored:

print(class_models['naive_bayes']['fitted'].sigma_)

There are two arrays output, the first one corresponding to the negative class and the second to the positive. The arrays contain the sigma (variance) for each of the 21 features given the class:

array([[2.50123026e+05, 2.61324730e+05, ..., 1.13475535e-02],
[2.60629652e+05, 2.96009867e+05, ..., 1.38936741e-02]])

You can also extract the thetas (means) from the model:

print(class_models['naive_bayes']['fitted'].theta_)

The preceding code also outputs two arrays, one for each class:

array([[1.30740577e+03, 1.31006271e+03, ..., 9.71131781e-01],
[1.41305545e+03, 1.48087887e+03, ..., 9.83974416e-01]])

These two arrays are all you need to debug and interpret Naïve Bayes results because you can use them to compute the conditional probability that the xi feature is given a positive class . You could use this probability to rank the features by importance on a global level, or interpret a specific prediction on a local level.

Naïve Bayes is a fast algorithm with some good use cases, such as spam filtering and recommendation systems, but the independence assumption hinders its performance in most situations. Speaking of performance, let’s discuss this topic in the context of interpretability.

Recognizing the trade-off between performance and interpretability

Section titled “Recognizing the trade-off between performance and interpretability”

We have briefly touched on this topic before, but high performance often requires complexity, and complexity inhibits interpretability. As studied in Chapter 2, Key Concepts of Interpretability, this complexity comes from primarily three sources: non-linearity, non-monotonicity, and interactivity. If the model adds any complexity, it is compounded by the number and nature of features in your dataset, which by itself is a source of complexity.

These special properties can help make a model more interpretable.

In Chapter 1, Interpretation, Interpretability, and Explainability; and Why Does It All Matter?, we discussed why being able to look under the hood of the model and intuitively understand how all its moving parts derive its predictions in a consistent manner is, mostly, what separates explainability from interpretability. This property is also called transparency or translucency. A model can be interpretable without this, but in the same way as interpreting a person’s decisions because we can’t understand what is going on “under the hood.” This is often called post-hoc interpretability and this is the kind of interpretability this book primarily focuses on, with a few exceptions. That being said, we ought to recognize that if a model is understood by leveraging its mathematical formula (grounded in statistical and probability theory), as we’ve done with linear regression and Naïve Bayes, or by visualizing a human-interpretable structure, as with decision trees, or a set of rules as with RuleFit, it is much more interpretable than machine learning model classes where none of this is practically possible.

White-box models will always have the upper hand in this regard, and as listed in Chapter 1, Interpretation, Interpretability, and Explainability; and Why Does It All Matter?, there are many use cases in which a white-box model is a must-have. But even if you don’t productionize white-box models, they can always serve a purpose in assisting with interpretation, if data dimensionality allows. Transparency is a key property because it wouldn’t matter if it didn’t comply with the other properties as long as it had explainability; it would still be more interpretable than those without it.

In this chapter, we’ve learned that regularization limits the complexity added by the introduction of too many features, and this can make the model more interpretable, not to mention more performant. Some models incorporate regularization into the training algorithm, such as RuleFit and gradient-boosted trees; others have the ability to integrate it, such as multi-layer perceptron, or linear regression, and some cannot include it, such as k-NN. Regularization comes in many forms. Decision trees have a method called pruning, which can help reduce complexity by removing non-significant branches. Neural networks have a technique called dropout, which randomly drops neural network nodes from layers during training. Regularization is a remedial property because it can help even the least interpretable models lessen complexity and thus improve interpretability.

By now, in this chapter, you have already assessed performance on all of the white-box models reviewed in the last section as well as a few black-box models. Maybe you’ve already noticed that black-box models have topped most metrics, and for most use cases, this is generally the case.

Figuring out which model classes are more interpretable is not an exact science, but the following table (Figure 3.17) is sorted by those models with the most desirable properties – that is, they don’t introduce non-linearity, non-monotonicity, and interactivity. Of course, explainability on its own is a property that is a game-changer, regardless, and regularization can help. There are also cases in which it’s hard to assess properties. For instance, polynomial (linear) regression implements a linear model, but it fits non-linear relationships, which is why it is color-coded differently. As you will learn in Chapter 12, Monotonic Constraints and Model Tuning for Interpretability, some libraries support adding monotonic constraints to gradient-boosted trees and neural networks, which means it’s possible to make these monotonic. However, the black-box methods we used in this chapter do not support monotonic constraints.

The task columns tell you whether they can be used for regression or classification. And the Performance Rank columns show you how well these models ranked in RMSE (for regression) and ROC AUC (for classification), where lower ranks are better. Please note that even though we have used only one metric to assess performance for this chart for simplicity’s sake, the discussion about performance should be more nuanced than that. Another thing to note is that ridge regression did poorly, but this is because we used the wrong hyperparameters, as explained in the previous section:

![A picture containing chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_13.png)

Figure 3.13: A table assessing the interpretability and performance of several white-hat and black-box models we have explored in this chapter

Because it’s compliant with all five properties, it’s easy to tell why linear regression is the gold standard for interpretability. Also, while recognizing that this is anecdotal evidence, it should be immediately apparent that most of the best ranks are with black-box models. This is no accident! The math behind neural networks and gradient-boosted trees is brutally efficient in achieving the best metrics. Still, as the red dots suggest, they have all the properties that make a model less interpretable, making their biggest strength (complexity) a potential weakness.

This is precisely why black-box models are our primary interest in this book, although many of the methods you will learn to apply to white-box models. In Part 2, which comprises Chapters 4 to 9, we will learn model-agnostic and deep-learning-specific methods that assist with interpretation. And in Part 3, which includes Chapters 10 to 14, we will learn how to tune models and datasets to increase interpretability:

![Chart, funnel chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_14.png)

Figure 3.14: A table comparing white-box, black-box, and glass-box models, or at least what is known so far about them

Discovering newer interpretable (glass-box) models

Section titled “Discovering newer interpretable (glass-box) models”

In the last decade, there have been significant efforts in both industry and in academia to create new models that can have enough complexity to find the sweet spot between underfitting and overfitting, known as the bias-variance trade-off, but retain an adequate level of explainability.

Many models fit this description, but most of them are meant for specific use cases, haven’t been properly tested yet, or have released a library or open-sourced code. However, two general-purpose ones are already gaining traction, which we will look at now.

EBM is part of Microsoft’s InterpretML framework, which includes many of the model-agnostic methods we will use later in the book.

EBM leverages the GAMs we mentioned earlier, which are like linear models but look like this:

Individual functions f1 through fp are fitted to each feature using spline functions. Then a link function g adapts the GAM to perform different tasks such as classification or regression, or adjust predictions to different statistical distributions. GAMs are white-box models, so what makes EBM a glass-box model? It incorporates bagging and gradient boosting, which tend to make models more performant. The boosting is done one feature at a time using a low learning rate so as not to confound them. It also finds practical interaction terms automatically, which improves performance while maintaining interpretability:

Once fitted, this formula is made up of complicated non-linear formulas, so a global holistic interpretation isn’t likely feasible. However, since the effects of each feature or pairwise interaction terms are additive, they are easily separable, and global modular interpretation is entirely possible. Local interpretation is equally easy, given that a mathematical formula can assist in debugging any prediction.

One drawback is that EBM can be much slower than gradient-boosted trees and neural networks because of the one feature at a time approach, a low learning rate not impacting the feature order, and spline fitting methods. However, it is parallelizable, so in environments with ample resources and multiple cores or machines, it will be much quicker. To avoid waiting for results for an hour or two, it is best to create abbreviated versions of X_train and X_test – that is, with fewer columns representing only the eight features white-box models found to be most important: DEP_DELAY, LATE_AIRCRAFT_DELAY, PCT_ELAPSED_TIME, WEATHER_DELAY, NAS_DELAY, SECURITY_DELAY, DISTANCE, CRS_ELAPSED_TIME, and TAXI_OUT. These are placed in a feature_samp array, and then the X_train and X_test DataFrames are subset to only include this feature. We are setting the sample2_size to 10%, but if you feel you have enough resources to handle it, adjust accordingly:

#Make new abbreviated versions of datasets

feature_samp = [
'DEP_DELAY',
'LATE_AIRCRAFT_DELAY',
'PCT_ELAPSED_TIME',
'DISTANCE',
'WEATHER_DELAY',
'NAS_DELAY',
'SECURITY_DELAY',
'CRS_ELAPSED_TIME'
]
X_train_abbrev2 = X_train[feature_samp]
X_test_abbrev2 = X_test[feature_samp]

#For sampling among observations

np.random.seed(rand)
sample2_size = 0.1
sample2_idx = np.random.choice(
X_train.shape[0], math.ceil(
X_train.shape[0]*sample2_size), replace=False
)

To train your EBM, all you have to do is instantiate an ExplainableBoostingClassifier() and then fit your model to your training data. Note that we are using sample_idx to sample a portion of the data so that it takes less time:

ebm_mdl = ExplainableBoostingClassifier()
ebm_mdl.fit(X_train_abbrev2.iloc[sample2_idx], y_train_class.iloc[sample2_idx])

Global interpretation is dead simple. It comes with an explain_global dashboard you can explore. It loads with the feature importance plot first, and you can select individual features to graph what was learned from each one:

show(ebm_mdl.explain_global())

The preceding code generates a dashboard that looks like Figure 3.15:

![Chart, bar chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_15.png)

Figure 3.15: EBM’s global interpretation dashboard

Local interpretation uses a dashboard like global does, except you choose specific predictions to interpret with explain_local. In this case, we are selecting #76, which, as you can tell, was incorrectly predicted. But the LIME-like plot we will study in Chapter 5, Local Model-Agnostic Interpretation Methods, helps us make sense of it:

ebm_lcl = ebm_mdl.explain_local(
X_test_abbrev2.iloc[76:77], y_test_class[76:77], name='EBM'
)
show(ebm_lcl)

Similar to the global dashboard, the preceding code generates another one, depicted in Figure 3.16:

![Chart, bar chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_16.png)

Figure 3.16: EBM’s local interpretation dashboard

EBM performance, at least measured with the ROC AUC, is not far from what was achieved by the top two classification models, and we can only expect it to get better with 10 times more training and testing data!

ebm_perf = ROC(ebm_mdl.predict_proba).explain_perf(
X_test_abbrev2.iloc[sample_idx],y_test_class.iloc[sample_idx],
name='EBM'
)
show(ebm_perf)

You can appreciate the performance dashboard produced by the preceding code in Figure 3.17.

![Chart, line chart

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_17.png)

Figure 3.17: One of EBM’s performance dashboards

The performance dashboard can also compare several models at a time since its explainers are model-agnostic. And there’s even a fourth dashboard that can be used for data exploration. Next, we will cover another GAM-based model.

There’s also a newer GAM-based method with similar properties to EBM but trained with neural networks. At the time of writing, this method has yet to get commercial traction but yields good interpretability and performance.

As we have previously discussed, interpretability is decreased by each additional feature, especially those that don’t significantly impact model performance. In addition to too many features, it’s also trumped by the added complexity of non-linearities, non-monotonicity, and interactions. GAMI-Net tackles all these problems by fitting non-linear subnetworks for each feature in the main effects network first. Then, fitting a pairwise interaction network with subnetworks for each combination of features. The user provides a maximum number of interactions to keep, which are then fitted to the residuals of the main effects network. See Figure 3.18 for a diagram.

Figure 3.18: Diagram of the GAMI-Net model

GAMI-Net has three interpretability constraints built in:

  • Sparsity: Only the top features and interactions are kept.
  • Heredity: A pairwise interaction can be included if at least one of its parent features is included.
  • Marginal clarity: Non-orthogonality in interactions is penalized to approximate better marginal clarity.

The GAMI-Net implementation can also enforce monotonic constraints, which we will cover in more detail in Chapter 12, Monotonic Constraints and Model Tuning for Interpretability.

Before we start, we must create a dictionary called meta_info with details about each feature and target, such as the type (continuous, categorical, and target) and the scaler used to scale each feature — since the library expects each feature to be scaled independently. All the features in the abbreviated dataset are continuous so we can leverage dictionary comprehension to this easily:

meta_info = {col:{"type":"continuous"} for col in\
X_train_abbrev.columns}

Next, we will create a copy of X_train_abbrev and X_train_abbrev and then scale them and store the scalers in the dictionary. Then, we will append information about the target variable to the dictionary. And lastly, we will convert all the data to numpy format:

X_train_abbrev2 = X_train_abbrev.copy()
X_test_abbrev2 = X_test_abbrev.copy()
for key in meta_info.keys():
scaler = MinMaxScaler()
X_train_abbrev2[[key]] =scaler.fit_transform(
X_train_abbrev2[[key]])
X_test_abbrev2[[key]] = scaler.transform(X_test_abbrev2[[key]])
meta_info[key]["scaler"] = scaler
meta_info["CARRIER_DELAY"] = {"type":"target", "values":["no", "yes"]}
X_train_abbrev2 = X_train_abbrev2.to_numpy().astype(np.float32)
X_test_abbrev2 = X_test_abbrev2.to_numpy().astype(np.float32)
y_train_class2 = y_train_class.to_numpy().reshape(-1,1)
y_test_class2 = y_test_class.to_numpy().reshape(-1,1)

Now that we have a meta_info dictionary and the dataset is ready, we can initialize and fit GAMI-Net to the training data. In addition to meta_info, it has a lot of parameters: interact_num defines how many top interactions it should consider, and task_type defines whether it’s a classification or regression task. Note that GAMI-Net trains three neural networks, so there are three epoch parameters to fill in (main_effect_epochs, interaction_epochs, and tuning_epochs). The learning rate (lr_bp) and early stopping thresholds (early_stop_thres) are entered as a list for each of the epoch parameters. You will also find lists for the architecture of the networks, where each item corresponds to a number of nodes per layer (interact_arch and subnet_arch). Furthermore, there are additional parameters for batch size, activation function, whether to enforce heredity constraint, a loss threshold for early stopping, and what percentage of the training data to use for validation (val_ratio). Finally, there are two optional parameters for monotonic constraints (mono_increasing_list, mono_decreasing_list):

gami_mdl = GAMINet(
meta_info=meta_info,
interact_num=8,
task_type="Classification",
main_effect_epochs=80,
interaction_epochs=60,
tuning_epochs=40,
lr_bp=[0.0001] * 3,
early_stop_thres=[10] * 3,
interact_arch=[20] * 5,
subnet_arch=[20] * 5,
batch_size=200,
activation_func=tf.nn.relu,
heredity=True,
loss_threshold=0.01,
val_ratio=0.2,
verbose=True,
reg_clarity=1,
random_state=rand
)
gami_mdl.fit(X_train_abbrev2, y_train_class2)

We can plot the training loss for each epoch across all three trainings with plot_trajectory. Then, with plot_regularization, we can plot the outcome for the regularization of both the main effects and interaction networks. Both plotting functions can save the image in a folder but will do so in a folder called results by default, unless you change the path with the folder parameter:

data_dict_logs = gami_mdl.summary_logs(save_dict=False)
plot_trajectory(data_dict_logs)
plot_regularization(data_dict_logs)

The preceding snippet generates the plots in Figure 3.19:

![Graphical user interface

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_19.png)

Figure 3.19: The trajectory and regularization plots for the GAMI-net training process

Figure 3.19 tells the story of how the three stages sequentially reduce loss while regularizing to only keep the fewest features and interactions as possible.

Global explanations can be extracted in a dictionary with the global_explain function and then turned into a feature importance plot with feature_importance_visualize, like in the following snippet:

data_dict_global = gami_mdl.global_explain(save_dict=True)
feature_importance_visualize(data_dict_global)
plt.show()

The preceding snippet outputs the following plot:

![Histogram

Description automatically generated with medium confidence](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_20.png)

Figure 3.20: A global explanation plot

As you can tell by Figure 3.20, the most important feature is, by far, DEP_DELAY and one interaction is among the top six features in the plot. We can also use the global_visualize_density plot to output partial dependence plots, which we will cover in Chapter 4, Global Model-Agnostic Interpretation Methods.

Let’s examine an explanation for a single prediction using local_explain, followed by local_visualize. We are selecting test case #73:

data_dict_local = gami_mdl.local_explain(
X_test_abbrev2[[73]], y_test_class2[[73]], save_dict=False
)
local_visualize(data_dict_local[0])
plt.tight_layout()
plt.show()

The preceding code generates the plot in Figure 3.21:

![Graphical user interface, application, Teams

Description automatically generated](https://static.packt-cdn.com/products/9781803235424/graphics/Images/B18406_03_21.png)

Figure 3.21: A local explanation plot for test case #73

Figure 3.21 tells the story of how each feature weighs in the outcome. Note that DEP_DELAY is over 50 but that there’s an intercept that almost cancels it out. The intercept is a counterbalance – after all, the dataset is unbalanced toward it being less likely to be a CARRIER_DELAY. But all the subsequent features after the intercept are not enough to push the outcome positively.

To determine the predictive performance of the GAMI-Net model, all we need to do is get the scores (y_test_prob) and predictions (y_test_pred) for the test dataset and then use scikit-learn’s metrics functions to compute them:

y_test_prob = gami_mdl.predict(X_test_abbrev2)
y_test_pred = np.where(y_test_prob > 0.5, 1, 0)
print(
'accuracy: %.3g, recall: %.3g, roc auc: %.3g, f1: %.3g,
mcc: %.3g'

% (

metrics.accuracy_score(y_test_class2, y_test_pred),
metrics.recall_score(y_test_class2, y_test_pred),
metrics.roc_auc_score(y_test_class2, y_test_prob),
metrics.f1_score(y_test_class2, y_test_pred),
metrics.matthews_corrcoef(y_test_class2, y_test_pred)
)

)

The preceding code yields the following metrics:

accuracy: 0.991, recall: 0.934, roc auc: 0.998, f1: 0.924, mcc: 0.919 The performance was not bad considering it was trained on 10% of the training data and evaluated on only 10% of the test data – especially the recall score, which was among the top three places.

The mission was to train models that could predict preventable delays with enough accuracy to be useful, and then, to understand the factors that impacted these delays, according to these models, to improve OTP. The resulting regression models all predicted delays, on average, well below the 15-minute threshold according to the RMSE. And most of the classification models achieved an F1 score well above 50% – one of them reached 98.8%! We also managed to find factors that impacted delays for all white-box models, some of which performed reasonably well. So, it seems like it was a resounding success!

Don’t celebrate just yet! Despite the high metrics, this mission was a failure. Through interpretation methods, we realized that the models were accurate mostly for the wrong reasons. This realization helps underpin the mission-critical lesson that a model can easily be right for the wrong reasons, so the question “why?” is not a question to be asked only when it performs poorly but always. And using interpretation methods is how we ask that question.

But if the mission failed, why is this section called Mission accomplished? Good question!

It turns out there was a secret mission. Hint: it’s the title of this chapter. The point of it was to learn about common interpretation challenges through the failure of the overt mission. In case you missed them, here are the interpretation challenges we stumbled upon:

  • Traditional model interpretation methods only cover surface-level questions about your models. Note that we had to resort to model-specific global interpretation methods to discover that the models were right for the wrong reasons.
  • Assumptions can derail any machine learning project since this is information that you suppose without evidence. Note that it is crucial to work closely with domain experts to inform decisions throughout the machine learning workflow, but sometimes they can also mislead you. Ensure you check for inconsistencies between the data and what you assume to be the truth about that data. Finding and correcting these problems is at the heart of what interpretability is about.
  • Many model classes, even white-box models, have issues with computing feature importance consistently and reliably.
  • Incorrect model tuning can lead to a model that performs well enough but is less interpretable. Note that a regularized model overfits less but is also more interpretable. We will cover methods to address this challenge in Chapter 12, Monotonic Constraints and Model Tuning for Interpretability. Feature selection and engineering can also have the same effect, which you can read about in Chapter 10, Feature Selection and Engineering for Interpretability.
  • There’s a trade-off between predictive performance and interpretability. And this trade-off extends to execution speed. For these reasons, this book primarily focuses on black-box models, which have the predictive performance we want and a reasonable execution speed but could use some help on the interpretability side.

If you learned about these challenges, then congratulations! Mission accomplished!

After reading this chapter, we covered some traditional methods for interpretability and what their limitations are. We learned about intrinsically interpretable models and how to both use them and interpret them, for both regression and classification. We also studied the performance versus interpretability trade-off and some models that attempt not to compromise in this trade-off. We also discovered many practical interpretation challenges involving the roles of feature selection and engineering, hyperparameters, domain experts, and execution speed.

In the next chapter, we will learn more about different interpretation methods to measure the effect of a feature on a model.

United States Department of Transportation Bureau of Transportation Statistics. (2018). Airline On-Time Performance Data. Originally retrieved from https://www.transtats.bts.gov.

  • Friedman, J. and Popescu, B, 2008, Predictive Learning via Rule Ensembles. The Annals of Applied Statistics, 2(3), 916-954. http://doi.org/10.1214/07-AOAS148
  • Hastie, T., Tibshirani, R., and Wainwright, M., 2015, Statistical Learning with Sparsity: The Lasso and Generalizations. Chapman & Hall/Crc Monographs on Statistics & Applied Probability, Taylor & Francis
  • Thomas, D.R., Hughes, E., and Zumbo, B.D., 1998, On Variable Importance in Linear Regression. Social Indicators Research 45, 253–275: https://doi.org/10.1023/A:1006954016433
  • Nori, H., Jenkins, S., Koch, P., and Caruana, R., 2019, InterpretML: A Unified Framework for Machine Learning Interpretability. arXiv preprint: https://arxiv.org/pdf/1909.09223.pdf
  • Hastie, T., and Tibshirani, R., 1987, Generalized Additive Models: Some Applications. Journal of the American Statistical Association, 82(398):371–386: http://doi.org/10.2307%2F2289439