0% found this document useful (0 votes)
28 views7 pages

Interpretable Machine Learning Assignment

This document discusses an assignment on interpretable machine learning. It contains three parts: 1) Training, validating and testing a logistic regression model on credit risk data, including default fitting, cross-validation to tune hyperparameters, and nested cross-validation. 2) Applying the Frisch–Waugh–Lovell theorem using machine learning on bike sharing data to verify that adjusting for confounding variables yields the same regression coefficient. 3) Examining tree-based models.

Uploaded by

bkiakisolako
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views7 pages

Interpretable Machine Learning Assignment

This document discusses an assignment on interpretable machine learning. It contains three parts: 1) Training, validating and testing a logistic regression model on credit risk data, including default fitting, cross-validation to tune hyperparameters, and nested cross-validation. 2) Applying the Frisch–Waugh–Lovell theorem using machine learning on bike sharing data to verify that adjusting for confounding variables yields the same regression coefficient. 3) Examining tree-based models.

Uploaded by

bkiakisolako
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Interpretable Machine Learning 20/03/2024, 8:34 in the evening

Interpretable Machine Learning


Assignment I

AUTHOR PUBLISHED
Munir Eberhardt Hiabu March 19, 2024

Part 1 (Training, Validating and


Testing)
We will work with the “credit-g” dataset. The dataset classifies people described
by a set of attributes as good or bad credit risks. See
[Link] for more
details. We will fetch the data from [Link] We will rely on
the mlr3 environment ([Link] As classifier, we
will use logistic regression with elastic net.

Load necessary packages.

library(mlr3)
library(mlr3learners )
library(mlr3tuning)
library(mlr3mbo)
library(glmnet)
library(OpenML)
library(mlr3pipelines)

### If parallelizationis wanted also:


library(future)
future::plan("multisession")

(a) (Default fitting)


Fetch the data and create a task.

credit_data = getOMLDataSet([Link] = 31)


task = as_task_classif(credit_data$data, target = "class")

Split your data into a training and test set.

Build a graph where

first: Dummy encode variables via po(“encode”),

[Link] Page 1 of 7
Interpretable Machine Learning 20/03/2024, 8:34 in the evening

second: Standardize via po(“scale”),


third: Logistic Regression with default settings is applied.

Train your model on the training set and evaluate it on the test set.

(b) (Cross Validation)


In this part we want to train a logistic regression with elastic net. The tuning
parameters are alpha and s (Here: s has the same function as the penalty
parameter lambda).

Build a new graph

First and second step as before in Exercise I


Third: Use learner [Link] with tunable parameters:

s = to_tune(0, 1)
alpha = to_tune(0, 1)

Note: Tuning s manually via cross-validation is not optimal with respect to


computational efficiency and a more efficient solution is implemented
directly in the [Link] learner. In this exercise, for learning purposes,
we will do cross-validation manually.

Tune your hyperparameters via the tune function with:

tuner: random search


resampling: 5-fold cross validation
measure: classification error
terminator: 50 evaluations

What is the CV error of the best configuration?

What is the test error of the best configuration?

It can be helpful to use

graph_learner_elastic_net$param_set$values =
instance$result_learner_param_vals
graph_learner_elastic_net$param_set$values$[Link]
mbda =
graph_learner_elastic_net$param_set$values$[Link].s

Here graph_learner_elastic_net is the name of my graph and instance is the


name of my tuned instance.

Print the beta values via

[Link] Page 2 of 7
Interpretable Machine Learning 20/03/2024, 8:34 in the evening

graph_learner_elastic_net$model$[Link]$model$beta

You may want to try out different tuning configurations


e.g. tuner: “mbo” or other measures.

(c) (Nested Cross Validation)


Try out nested cross-validation by
defining your graph as an auto_tuner with
tuner: random search,
resampling: 5-fold cross validation,
measure: classification error,
terminator: 50 evaluations.

Use resample to run 5-fold cross validation.


Print out the nested cross validation error.

Part 2 (Frisch–Waugh–Lovell
theorem)
In this part we will study the Frisch–Waugh–Lovell theorem. The implied
algorithm, but using machine learning instead of linear regression, has been
introduced a couple of years ago as Double Machine Learning. Since then it has
gained a lot of attention and popularity. Here, we want to verify the result via a
coding exercise.

Load necessary packages. ::: {.cell}

library(mlr3)
library(mlr3learners)
library(OpenML)
library(mlr3pipelines)

:::

Fetch and edit data.

bike_data = getOMLDataSet([Link] = 42713)


bike_data$data <- bike_data$data[,-c(7,13,14)] ## remove casual and registered

### convert dates to factors


bike_data$data$year <- factor(bike_data$data$year)
bike_data$data$month <- factor(bike_data$data$month)
bike_data$data$hour <- factor(bike_data$data$hour)
bike_data$data$weekday <- factor(bike_data$data$weekday)

[Link] Page 3 of 7
Interpretable Machine Learning 20/03/2024, 8:34 in the evening

a. Run simple least squares linear regression with response being count and
predictor equal windspeed . Report the coefficient you get.

b. Run least squares linear regression with response being count and predictor
being all remaining variables. Don’t forget to create a graph to dummy-
encode the factor variables. Report the coefficient you get for windspeed .

c. Do the following steps

Run least squares linear regression with response being count and predictor
being all remaining variables except windspeed . Calculate the residuals and
call that variable count_residuals .
Run least squares linear regression with response being windspeed and
predictor being all remaining variables except count . Calculate the residuals
and call that variable windpseed_residuals .
Run simple least squares linear regression with response being
count_residuals and predictor windpseed_residuals .
Report the regression coefficient you get.

d. Verify that the coefficients in Steps (b) and (c) are the same.

e. Replace the simple linear regression model in the second last step in part (c)
by an auto-tuned k-nearest neighbors. Visualize the fit (by plotting
windpseed_residuals against observed and predicted
count_residuals ) and compare it to the previous simple linear regression
fit. Discuss the result.

Part 3 (Tree based models)


Load necessary packages.

library(mlr3)
library(mlr3learners)
library(mlr3tuning)
library(OpenML)
library(mlr3pipelines)
library(future)
future::plan("multisession")

Fetch data. This is the same data is in Part 1.

# load credit-g data and define task


credit_data = getOMLDataSet([Link] = 31)
task = as_task_classif(credit_data$data, target = "class")

[Link] Page 4 of 7
Interpretable Machine Learning 20/03/2024, 8:34 in the evening

(a)
Use the learner [Link] with predict_type = "prob" and train it on
the task. Visualize the learned tree via

# load credit-g data and define task


full_tree_trained <- full_tree$model$[Link]$model
plot(full_tree_trained , compress = TRUE, margin = 0.1)
text(full_tree_trained , use.n = TRUE, cex = 0.8)

Here full_tree is the graph you trained.

(b)
We now aim to find a penalty parameter α that results in a pruned tree with
strong predictive power. To this end, we define a tree learner that runs the
weakest link algorithm and therea"er 5-fold cross validation to compare the
performance between different trees.

# load credit-g data and define task


my_cart_learner_cv = lrn("[Link]", xval = 5, predict_type = "prob")

You can run the following command on the rpart object in order to see the CV
result. Hint: If unsure how to extract the rpart object from your trained graph,
check how this was done in part (a) above.

# load credit-g data and define task


rpart::plotcp(cart_trained_cv)
rpart::printcp(cart_trained_cv)

(c)
Pick an α that is big enough and also has a low error. In the rpart package
vignette, the following advice is given:

A plot of α versus risk o"en has an initial sharp drop followed by a


relatively flat plateau and then a slow rise. The choice of α among those
models on the plateau can be essentially random. To avoid this, both an
estimate of the risk and its standard error are computed during the cross-
validation. Any risk within one standard error of the achieved minimum is
marked as being equivalent to the minimum ([Link] to be part of
the flat plateau). Then the simplest model, among all those “tied” on the
plateau, is chosen.

Train and then visualize the tree with the chosen α. (The relevant parameter is
called cp ).

[Link] Page 5 of 7
Interpretable Machine Learning 20/03/2024, 8:34 in the evening

(d)
Using the benchmark function, compare the predictive performance of the
following five algorithms

A baseline model that uses no features ( [Link] )


A non-pruned CART tree
A pruned CART tree with α as chosen in part (c).
An auto-tuned xgboost ( [Link] ). You could for example tune
parameters in the following way:
eta = to_tune(0, 0.5) ,
nrounds = to_tune(10, 5000) ,
max_depth = to_tune(1, 10) .

An auto-tuned random forest ( [Link] ). You could for example


tune parameters in the following way:
[Link] = to_tune(0.1, 1) ,
[Link] = to_tune(1, 50) .

You may want too look at more then just the classification error. You can for
example run.

# load credit-g data and define task


res$aggregate(list(msr("[Link]"),
msr("[Link]"),
msr("[Link]"),
msr("[Link]"),
msr("[Link]")))

Here res is the calculated benchmark object.

Remark
Note that we are not comparing how an optimally pruned decision tree compares to
other algorithms that are optimally tuned. While this is possible (one would just need to
decide on how to choose the optimal α explicitly and define an auto-tuner accordingly),
the purpose of this task is another. While we expect that a single decision tree will have
poorer performance than tree ensembles, we would like to know how big the
performance loss is if we choose to employ an interpretable decision tree. Here it is also
essential that the α we have chosen in (c) is big enough such that it leads to a small
enough tree.

(e)
The German Credit dataset comes with a cost matrix
[Link]

[Link] Page 6 of 7
Interpretable Machine Learning 20/03/2024, 8:34 in the evening

Good (predicted) Bad (predicted)

Good (actual) 0 1

Bad (actual) 5 0

Use [Link](costs = mycosts) , to define a measure with the given


cost. Here, mycosts is the transpose of the cost matrix. Use the calculated
benchmark object from (d) to see how the algorithms compare for this new
measure.

(f)
If time allows you can re-run part (d) where the auto-tuned object are optimized
via the measure defined in part (e) and see how much the results change.

[Link] Page 7 of 7

Common questions

Powered by AI

Double Machine Learning is a method that extends the Frisch–Waugh–Lovell theorem to a machine learning context, providing a framework for unbiased treatment effect estimation in the presence of high-dimensional controls. It is significant because it allows for the use of flexible machine learning models in econometric analysis to estimate causal effects, maintaining the interpretability and statistical properties of classical linear methods. This approach has gained attention for its ability to correctly specify models even when traditional assumptions might not hold due to algorithm flexibility .

Incorporating a cost matrix in model evaluation on the German Credit dataset is crucial due to the different misclassification costs associated with predicting credit as good or bad. This approach shifts the focus from overall accuracy to minimizing financial risks or losses associated with incorrect predictions. Models evaluated with a cost matrix aim to optimize for the most economically viable predictions, often prioritizing risk minimization over accuracy. This impacts model selection by favoring models with higher cost-efficiency in predictions, ensuring they align with business or economic goals despite potentially lower accuracy scores. This cost-sensitive approach ensures that model selection is aligned with real-world implications of decision-making .

Transforming categorical variables into dummy variables affects regression models by enabling them to handle non-numeric data as inputs. This process allows the model to interpret categorical predictors, essential for models like linear regression that require numeric input. In the bike rental data, converting date elements such as year, month, hour, and weekday into factors and then to dummy variables lets the model assess the impact of these temporal factors on the rental count. This transformation aids in capturing complex patterns and interactions that categorical data introduce, improving model interpretability and prediction accuracy .

Training, validating, and testing are crucial stages in a machine learning pipeline for evaluating models with datasets like the Statlog German Credit Data. Training involves using a portion of the data to build the model, validating tests the model's parameters to avoid overfitting through methods like cross-validation, and testing assesses the model's generalization on unseen data. The implementation with the Statlog German Credit Data involves creating a training and test split, using logistic regression with elastic net, and employing cross-validation to tune hyperparameters and evaluate model performance .

Interpretable models like CART trees offer simplicity and clarity, making them suitable for tasks where understanding the model's decision-making process is crucial. They are easier to visualize and communicate to non-technical stakeholders. However, this simplicity often comes at the cost of accuracy; CART models typically underperform on complex datasets due to their deterministic nature and susceptibility to overfitting. Conversely, complex models like xgboost and random forests provide superior predictive accuracy by utilizing ensemble techniques and capturing nonlinear interactions between variables, although they sacrifice interpretability. The trade-off involves deciding between the need for model transparency versus the requirement for high-performance and adaptability on complex datasets .

Cross-validation is used to optimize the tuning parameters for logistic regression with elastic net on the Statlog German Credit dataset by estimating the model's performance on different subsets of the data. It helps in selecting the optimal values of the elastic net parameters (s and alpha) by performing a series of 5-fold cross-validations, ensuring that model parameters generalize well to unseen data. This process involves using a random search with a classification error measure and a termination condition of 50 evaluations, thereby avoiding overfitting and underfitting .

Nested cross-validation provides a more robust evaluation of model performance by encompassing two layers of cross-validation. The inner loop selects the best hyperparameters, while the outer loop tests these parameters by resampling on a different data split, offering a less biased performance estimation. In contrast to simple cross-validation, which may lead to overly optimistic results because the same data is used for both tuning and validation, nested cross-validation on the Statlog German Credit Data separates these processes, ensuring that hyperparameter tuning does not inflate the model's reported performance .

Manually tuning hyperparameters through cross-validation in logistic regression models is computationally inefficient and often less effective compared to automated methods. Challenges include the time and computational resources required to evaluate multiple combinations of parameters, potential human error in parameter selection, and difficulties in finding the optimal parameter values within a reasonable timeframe. Automated methods, like those implemented in the classifier glmnet, streamline the process through algorithmic searches like random search, leading to quicker and often more accurate hyperparameter tuning .

Tree-based models like CART provide interpretability and simplicity by constructing decision trees. However, their predictive performance is often lower than ensemble methods such as random forests. In the context of the German Credit dataset, CART is easier to understand but susceptible to overfitting, especially if not pruned correctly. Random forests, on the other hand, offer better predictive accuracy by aggregating multiple decision trees, reducing variance, and improving generalization. The challenge lies in balancing interpretability with performance, with ensemble methods typically requiring more computational power and hyperparameter tuning .

The penalty parameter (cp) in a decision tree influences its complexity by determining how the tree learns the data patterns. A high cp value leads to stronger pruning, resulting in a simpler tree with fewer splits, which may enhance generalization but risks underfitting. Conversely, a low cp value results in a more complex tree that captures more details of the dataset, potentially leading to overfitting. When applying this to the German Credit dataset, choosing a cp value within the 'flat plateau' of cross-validated risk estimates allows for a balance between model complexity and predictive performance, ensuring that the tree is neither too simplistic nor overly complex .

You might also like