Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

🏋️ Exercises

Please fill the missing code pieces as indicated by the .... The imports are always provided at the top of the code chunks. This should give you a hint for which functions/classes to use.

Exercise 1: Model Selection

Today we are working with the California Housing dataset, which you are already familiar with, as we previously used it while exploring resampling method. This dataset is based on the 1990 U.S. Census and includes features describing California districts.

  1. Familiarize yourself with the data

    • What kind of features are in the dataset? What is the target?

  1. Baseline model

    • Create a baseline linear regression model using all features and then fit and evaluate the model with the cross_val_score() function, using 5-fold cross validation and R2R² as the performance metric

    • Print the individual and average R²

  1. Apply a forward stepwise selection to find a simpler suitable model.

    • Split the data into 80% training data and 20% testing data (print the shape to confirm it was sucessful)

    • Perform a forward stepwise selection with a linear regression model, 5-fold CV, R² score, and parsimonious feature selection (refer to documentation for further information)

    • Print the best CV R² as well as the chosen features

  1. Evaluate the model on the test set

Exercise 2: LASSO

Please implement a Lasso regression model similar to the Ridge model in the Regularization section.

Exercise 3: GAMs (1)

Objective: Understand how the number of basis functions (df) and the polynomial degree (degree) affect the flexibility of a spline and the resulting fit in a Generalized Additive Model.

  1. Use the diabetes dataset and focus on the relationship between bmi and target.

  2. We want to test different combinations of parameters. For the dfs, please use 4, 6, 12. For the degree, please use 2 and 3 (quadratic and cubic).

  3. Fit the GAMs for each parameter combination. The resulting models will be plotted automatically for visual comparison.

Exercise 4: GAMs (2)

We now use the wage dataset, which contains income information for a group of workers, along with demographic and employment-related features such as age, education, marital status, and job class.

  1. Explore the dataset

    • Which variables are numeric?

    • Which ones are categorical?

  2. Fit a GAM predicting wage from age, year, education, jobclass, and maritl

Note: For categorical features we use a one-hot encoding with pd.get_dummies()

Exercise 5: KNN

You will implement a K-Nearest Neighbours (KNN) classifier to predict whether a patient is likely to have malignant or benign breast cancer based on several features. The data is already loaded for you, but please have a look a the documentation to quickly refresh you memory about the dataset.

Please implement the following:

  1. Subset the dataframe to use mean area, mean radius, and mean smoothness as features (X), and target as the target (y)

  2. Split the data into a training and a testing set (70/30)

  3. Scale the predictors to mean 0 and variance 1

  4. Train a kNN classifier with k=5k=5

  5. Evaluate the performance for the testing set. Please use the accuracy_score() as well as the classification_report() function.

The classification model from the previous step has two main limitations:

  1. It is trained and evaluated on a single data split

  2. It uses a single kk even though we do not know if it is optimal

Please do the following:

  1. Implement 5-fold cross validation

  2. Train models for kk ranging from 1 to 200 and plot the mean accuracy over all folds

Discuss the results. How is the performance in general? Which kk would you chose?

Exercise 6: LDA, QDA & Naïve Bayes

Once again, we will use the Iris dataset for classificationa analysis. Your task is to compare the performance of LDA, QDA, and Gaussian Naïve Bayes!

  1. Load the iris dataset from sklearn.datasets. We will use only the first two features (sepal length and width)

  2. TODO: Split the data into training and test sets (use stratification!)

  3. TODO: Fit LDA, QDA, and Naïve Bayes classifiers to the training data and orint the classification report for all models on the test data

  4. Plot the decision boundaries for both models

Once you have trained all three models, you can simply run the following code to plot the decision boundaries:

Exercise 7: SVC

For the SVC exercise we will use the fmri dataset from seaborn, which contains measurements of brain activity (signal) in two brain regions (frontal and parietal) under two event types (stim vs. cue).

We will try to answer a very simple research question:

Can we distinguish between cue and stim events based on the fMRI signal in the parietal and frontal brain regions?

To do this, we need to turn the long‐format data into a classic “feature matrix” (one row = one sample, two columns = our two brain‐region signals) plus a corresponding label vector (cue/stim):

With the features and target in the correct form, please perform the following tasks:

  1. Split the data into a train and test set

  2. Scale the predictors to mean 0 and std 1

  3. Fit a linear as well as a rbf SVC and discuss the classification reports

After fitting both models, you can run the code chunk below to plot the decision boundary:

Training a SVC on more complex datasets usually requires a parameter search to find the optimal hyperparameters. Please implement a grid search with the following options:

  • Kernel: rbf

  • C: np.logspace(-2,2,5)

  • gamma: np.logspace(-3,1,5)

  • cv: 5-fold

  • scoring: accuracy

Print the optimal parameters and the corresponding accuracies for taining and testing.

Exercise 8: Trees

  1. Inspect the data

    • How many features are there and what are they?

    • What is the target?

  2. Split the data into a train and test set, and make sure the classes are equally distributed (stratify=y)

  3. Fit the DecisionTreeClassifier(max_depth=3) and report train vs. test accuracy.

  4. Tree inspection (discuss in group)

    • After fitting the model, the tree will be plotted automatically

    • What is the very first split (feature name and threshold)?

    • Which leaf nodes are pure, and which have mixed classes?

Let’s see if we can improve the classification performance with a random forest classifier and hyperparameter tuning!

  1. Set up the clasifier + a parameter grid for grid search with 5-fold CV

    • n_estimators: 50, 100, 200

    • max_depth: None, 10, 20

    • min_samples_split: 2, 5, 10

    • max_features: “sqrt”, “log2”, 0.5

  2. Fit the model with the grid search

  3. Print the best hyperparameters

  4. Evaluate the best model on the test set

Finally, let’s see how a boosting model compares. Fit a GradientBoostingClassifier on the same diabetes split and check whether it beats the tuned random forest.

  1. Fit a GradientBoostingClassifier with n_estimators=100, learning_rate=0.1, max_depth=3, and random_state=0

  2. Evaluate it on the test set and print the classification report

  3. Compare its test accuracy to the random forest above

Exercise 9: Neural Networks

In this exercise, you will use tensorflow to create a single layer neural network to classify handwritten numbers from 0 to 9 from the MNIST dataset.

Hint: Tensorflow is one of the most widely used machine learning learning libraries. It was initially developed by Google, but is open source and available for everyone. Tensorflow requires Python <=3.12. If you have an environment with Python 3.13, you either need to create a new one or simply use Google Colab for this exercise.

We can then create the network with the following characteristics:

  • Input: A flattened version of the MNIST image (a vector of size 784)

  • Architecture: A single dense (fully connected) layer with 10 neurons (one for each class)

  • Activation function: softmax(outputs probabilities summing to 1)

  • Output: A probability distribution over digits 0–9; the highest is chosen

  • Learning rule: categorical_crossentropy loss and stochastic gradient descent (SGD) optimiser

  • Evaluation metric: accuracy, measuring the percentage of correctly classified images

Tasks:

  1. Explore the code and try to understand what it does (change things and see how they affect the result!)

  2. Improve the model to achieve a better predicion accuracy (>97%). Potential change you can make:

    • Change the number of epochs or batch size (the number of training examples processed at once before the model weights are updated)

    • Change the learning rate or optimiser (use e.g. Adam, which uses an adaptive learning rate and is faster)

    • Change the model structure by e.g. adding a hidden layer with e.g. 64 or 128 neurons and a ReLu activation function

  3. Compare your model with other students. Who managed to get the highest testing accuracy?

Exercise 10: Principal Component Analysis

For today’s practical session, we will work with the Diabetes dataset built into scikit-learn. This dataset contains medical information from 442 diabetes patients:

  • Features (X): 10 baseline variables (age, sex, BMI, average blood pressure, and six blood serum measures).

  • Target (y): a quantitative measure of disease progression one year after baseline.

You can read more here: https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_diabetes.html

Tasks:

  1. Inspect & clean (already implemented)

    • Display summary statistics (df.describe()) for all 10 features.

    • Check for missing values. (Hint: this dataset has none, but verify.)

  2. Standardize

    • Use StandardScaler() to transform each feature to mean 0, variance 1.

  3. PCA & scree plot

    • Fit PCA() to the standardized feature matrix.

    • Plot the explained variance ratio for each principal component (a scree plot).

    • Decide how many components to retain (e.g.\ cumulative variance ≥ 80%).

  4. Interpret loadings

    • Examine pca.components_.

    • For the first two retained PCs, list the top 3 features by absolute loading.

    • Infer what physiological patterns these components might represent.

  5. Project the data for visualization

    • Compute the PCA projection: X_pca = pca.transform(X_std).

  6. Plot the results (already implemented)

    • Create a 2D scatter of PC1 vs. PC2, coloring points by whether the target is above or below the median progression value.

    • Do patients with more rapid progression cluster differently?