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.

🧮 Solutions: Modelling

Exercise 1: Model Selection¶

We are working with the California Housing dataset again, which you already know from the resampling session. It is based on the 1990 U.S. Census and contains features describing districts in California.

  1. Load the data and extract the features (X) and the target (y)

  2. Baseline model

    • Split the data into 80% training and 20% test data (print the shapes to confirm that it was successful)

    • Evaluate a linear regression with all features on the training data, using 5-fold cross-validation and R² as the performance metric. Remember what you learned about shuffling in the resampling session!

    • Print the individual and the average R²

  3. Apply forward stepwise selection to find a simpler model

    • Use a linear regression model, the same cross-validation folds as for the baseline, R² as the score, and k_features="parsimonious". This option picks the smallest subset whose CV score is within one standard error of the best subset (see the documentation)

    • Print the best CV R² as well as the chosen features. How does the CV R² compare to the baseline?

  4. Evaluate both the baseline model and the selected model on the test set. Is the simpler model worse?

(16512, 8) (4128, 8)
(16512,) (4128,)
R² scores from each fold: [0.61  0.604 0.635 0.601 0.607]
Average R² score: 0.611
>> Forward SFS:
   Best CV R²      : 0.611
   Optimal # feats : 6
   Feature names   : ('MedInc', 'HouseAge', 'AveRooms', 'AveBedrms', 'Latitude', 'Longitude')
Test R² (all features):      0.5758
Test R² (selected features): 0.5750

1. The dataset contains 8 features describing the districts (e.g. median income, house age, average number of rooms, location). The target is the median house value (MedHouseVal) in units of $100,000.

2. The baseline model with all 8 features reaches an average cross-validated R² of 0.61 on the training data.

3. Forward selection keeps 6 of the 8 features and removes Population and AveOccup. Its CV R² of 0.611 is the same as the baseline: the two removed features hardly contribute to the predictions.

4. On the test set, both models perform practically the same (R² of 0.576 and 0.575). The selected model is simpler, but not worse. As in the session, subset selection mainly gives us a simpler model, not better predictions.

Exercise 2: Lasso¶

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

  1. Prepare the data: drop the highly correlated features and rows with missing data, split the data into training and test set, and scale the predictors

  2. Use LassoCV with 5-fold cross-validation to find the optimal Ī». Test 100 values between 0.01 and 1000, evenly spaced on a log scale (np.logspace())

  3. Print the optimal λ, the training and test R², and the coefficients. Which predictors does Lasso remove?

  4. Is the optimal Ī» at the edge of the range you tested? Why would that be a problem?

Optimal lambda: 24.20
Training R²:    0.477
Test R²:        0.315

   Predictor        Beta
3      CHits  174.867319
6       Hits  100.437862
7      HmRun   50.347168
10     Walks   39.872138
2        RBI    0.000000
0      AtBat    0.000000
1       Runs    0.000000
5    Assists   -0.000000
4     CWalks    0.000000
8      Years    0.000000
9     Errors   -0.000000

2. and 3. The optimal λ is about 24. Lasso keeps only 4 of the 11 predictors (CHits, Hits, HmRun, and Walks) and sets all other coefficients to exactly zero. The test R² is 0.315.

4. The optimal Ī» lies well inside the tested range (0.01 to 1000), so this is fine. If the optimum were at the edge of the range, the best Ī» might lie outside of it, and you should extend the range. For example, with values only up to 20, LassoCV would pick exactly 20.

Exercise 3: Principal Component Analysis¶

In this exercise, we work with the Diabetes dataset from scikit-learn. It contains 10 baseline measurements of 442 diabetes patients: age, sex, body mass index (bmi), average blood pressure (bp), and six blood serum measurements (s1 to s6). The target is a measure of disease progression one year after baseline. You can read more in the documentation or with print(diabetes.DESCR).

  1. Inspect the data

    • Use .describe() and .isna().sum() to get summary statistics and to check for missing values

    • Look at the mean and the standard deviation of the features. What do you notice? (Hint: print(diabetes.DESCR))

0 missing values
Loading...
  1. Fit a PCA

    • Standardize the features with StandardScaler() and fit a PCA() with all components

    • Plot the explained variance ratio of each component (scree plot, e.g. as bars) and the cumulative explained variance (line) next to each other

    • How many components do you need to explain at least 80% of the variance? Is there a clear elbow?

Explained variance ratio: [0.402 0.149 0.121 0.096 0.066 0.06  0.054 0.043 0.008 0.001]
Cumulative:               [0.402 0.552 0.672 0.768 0.834 0.894 0.948 0.991 0.999 1.   ]
<Figure size 1200x400 with 2 Axes>
  1. Interpret the loadings

    • Create a DataFrame with the loadings of the first three components (one row per component, one column per feature)

    • Plot it with sns.heatmap() (useful arguments: annot=True, cmap="coolwarm", center=0)

    • Which features have the largest absolute loadings on PC1 and PC2? What could these components represent? The serum measurements are: s1 total cholesterol, s2 LDL (ā€œbadā€ cholesterol), s3 HDL (ā€œgoodā€ cholesterol), s4 ratio of total cholesterol to HDL, s5 triglycerides (log), s6 blood sugar

<Figure size 1000x300 with 2 Axes>
  1. Project the data

    • Transform the standardized data into the PCA space

    • Create a scatter plot of PC1 against PC2 and color the points by disease progression (y)

    • Along which component does the disease progression change? Remember that the PCA never saw y!

<Figure size 640x480 with 2 Axes>

1. There are no missing values. All features have a mean of 0 and the same standard deviation (0.048). The version of the dataset in scikit-learn is already preprocessed: each feature was centered and divided by its standard deviation times the square root of the number of samples. Standardizing therefore does not change the PCA here, but it is still a good habit.

2. PC1 explains 40% of the variance, PC2 15%, and PC3 12%. You need 5 components to explain at least 80% of the variance (83%). Apart from the drop after PC1, there is no clear elbow: the variance is spread over many components. The last component explains almost nothing (0.1%), because some serum measurements are nearly linear combinations of the others (e.g. total cholesterol contains LDL and HDL).

3. Note that the sign of a component is arbitrary: flipping all loadings of a component describes the same direction.

  • PC1: All features load in the same direction, except s3 (HDL, the ā€œgoodā€ cholesterol), which has the opposite sign. The largest loadings belong to s4, s5, and s2. PC1 could therefore be read as a general ā€œmetabolic riskā€ component: high BMI, blood pressure, blood lipids, and blood sugar, together with low HDL.

  • PC2: Dominated by s1, s3, and s2 (total, HDL, and LDL cholesterol), all with the same sign, and sex with the opposite sign. PC2 mostly describes the overall cholesterol level.

4. The disease progression mainly changes along PC1: patients with high PC1 scores tend to have a faster progression. Along PC2, there is hardly any pattern. Even though the PCA never saw y, the direction of largest variance is related to disease progression in this dataset.

Exercise 3.2: PCR and PLS¶

Now we use the components to predict disease progression. We continue with the same data (X and y) as in the previous exercise.

  1. Visualize the correlations between the predictors with a heatmap. Which predictors are strongly correlated? Why could this be a problem for a linear regression?

<Figure size 640x480 with 2 Axes>
  1. PCR with a range of components

    • Split the data into 80% training and 20% test data (random_state=42)

    • Set up a 10-fold cross-validation with shuffling (random_state=42)

    • For 1 to 10 components, create a PCR pipeline with make_pipeline() (StandardScaler, PCA, LinearRegression) and evaluate it on the training data with cross_val_score(). Store the mean R² of each model

PCR CV R²: [0.276 0.305 0.368 0.466 0.465 0.479 0.484 0.476 0.474 0.478]
  1. PLS and comparison

    • Do the same with PLSRegression (it standardizes the predictors by itself)

    • As a baseline, also compute the cross-validated R² of a plain linear regression with all predictors

    • Plot the R² of PCR and PLS over the number of components, and add the baseline as a horizontal line (ax.axhline())

    • How does PLS compare to PCR?

PLS CV R²: [0.381 0.476 0.477 0.476 0.475 0.469 0.473 0.477 0.479 0.478]
Linear regression CV R²: 0.478
<Figure size 640x480 with 1 Axes>
  1. Why does the PCR performance jump at 4 components?

    • Fit the first two steps of a PCR pipeline (scaler and PCA with all components) on the training data and compute the scores of the training data

    • Compute the correlation of each component with y_train (np.corrcoef()) and compare it to the explained variance ratio of the component

    • What do you notice? How does this relate to the example in the session?

Loading...
  1. Test set evaluation

    • For PCR and PLS, choose the smallest number of components after which the CV R² hardly improves

    • Fit both models and the linear regression baseline on the full training data and print their test R²

    • Was the dimension reduction worth it in this dataset?

Test R² PCR (4 components): 0.458
Test R² PLS (2 components): 0.441
Test R² linear regression:  0.453

1. The dataset has 10 predictors. The strongest correlations are between s1 and s2 (0.90), s3 and s4 (āˆ’0.74), s2 and s4 (0.66), and s4 and s5 (0.62). As we saw with AtBat and Hits in the regularization session, strongly correlated predictors make the coefficients of a linear regression unstable.

2. and 3. PCR starts with a CV R² of 0.28 for one component, improves slowly, and jumps to 0.47 at 4 components. After that, it stays at about the level of the linear regression baseline (0.48). PLS reaches 0.38 with one component and already 0.48 with two. It needs fewer components than PCR, because it builds its components with the target in mind.

4. PC4 explains only 10% of the variance in X, but it is the component with the second-strongest correlation with y (āˆ’0.32). PC2 explains more variance (15%) but is less related to y (āˆ’0.18). PCR adds the components in the order of their variance, so it only profits from PC4 once PC2 and PC3 are included. This is the same problem as in the simulated example in the session: a component with little variance can still be important for predicting y.

5. Based on the CV curves, we choose 4 components for PCR and 2 for PLS. On the test set, PCR reaches an R² of 0.46, PLS 0.44, and the linear regression with all predictors 0.45. All three models perform about equally well. With 353 training observations and only 10 predictors, linear regression does not overfit much, so there is little variance that dimension reduction could remove. As in the regularization session, the main benefit here is a more compact model (2 PLS components instead of 10 predictors), not better predictions.

Exercise 4: Logistic Regression¶

For today’s exercise we will use the Breast Cancer Wisconsin (Diagnostic). It is a collection of data used for predicting whether a breast tumor is malignant (cancerous) or benign (non-cancerous), containing information derived from images of breast mass samples obtained through fine needle aspirates.

The dataset consists of 569 samples with 30 features that measure various characteristics of cell nuclei, such as radius, texture, perimeter, and area. Each sample is labeled as either malignant (1) or benign (0).

  1. Please visit the documentation and familiarize yourself with the dataset

  2. Take an initial look at the features (predictors) and targets (outcomes)

Loading...
Loading...
Loading...
array(['M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'B', 'B', 'B', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'B', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'M', 'M', 'B', 'M', 'M', 'B', 'B', 'B', 'B', 'M', 'B', 'M', 'M', 'B', 'B', 'B', 'B', 'M', 'B', 'M', 'M', 'B', 'M', 'B', 'M', 'M', 'B', 'B', 'B', 'M', 'M', 'B', 'M', 'M', 'M', 'B', 'B', 'B', 'M', 'B', 'B', 'M', 'M', 'B', 'B', 'B', 'M', 'M', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'M', 'M', 'B', 'M', 'M', 'B', 'B', 'B', 'M', 'M', 'B', 'M', 'B', 'M', 'M', 'B', 'M', 'M', 'B', 'B', 'M', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'M', 'M', 'B', 'M', 'B', 'B', 'M', 'M', 'B', 'B', 'M', 'M', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'M', 'M', 'M', 'B', 'M', 'B', 'M', 'B', 'B', 'B', 'M', 'B', 'B', 'M', 'M', 'B', 'M', 'M', 'M', 'M', 'B', 'M', 'M', 'M', 'B', 'M', 'B', 'M', 'B', 'B', 'M', 'B', 'M', 'M', 'M', 'M', 'B', 'B', 'M', 'M', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'M', 'M', 'B', 'B', 'M', 'B', 'B', 'M', 'M', 'B', 'M', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'M', 'B', 'B', 'M', 'B', 'B', 'M', 'B', 'M', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'M', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'M', 'B', 'M', 'B', 'B', 'B', 'B', 'M', 'M', 'M', 'B', 'B', 'B', 'B', 'M', 'B', 'M', 'B', 'M', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'M', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'M', 'B', 'M', 'M', 'M', 'B', 'M', 'M', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'M', 'B', 'B', 'M', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'M', 'M', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'M', 'B', 'M', 'B', 'B', 'M', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'M', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'M', 'M', 'B', 'M', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'B', 'M', 'B', 'M', 'B', 'M', 'M', 'B', 'B', 'B', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'B', 'M', 'M', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'M', 'M', 'M', 'M', 'M', 'M', 'B'], dtype=object)
  1. Split the data into training and test sets (stratify y)

  2. Create and fit a baseline model using only 2-3 interpretable predictors of your choice

    • Print the model coefficients

  3. Evaluate on the test set:

    • Accuracy

    • Confusion matrix

    • Classification report

    • Compare test accuracy to train accuracy. Is there a big gap?

Hint: If you get a warning about convergence, try setting max_iter=10000 in the logistic regression class.

Intercept: [-10.51351325]
Coefficients: [[-0.22529272  0.21197004  0.01417093]]
Test accuracy (baseline): 0.8508771929824561
Confusion matrix (test):
 [[68  4]
 [13 29]]
              precision    recall  f1-score   support

      Benign       0.84      0.94      0.89        72
   Malignant       0.88      0.69      0.77        42

    accuracy                           0.85       114
   macro avg       0.86      0.82      0.83       114
weighted avg       0.85      0.85      0.85       114

  1. Use all predictors and build a pipeline with standardisation

  2. Evaluate on the test set

  3. Compare:

    • Baseline model vs full model (test accuracy, precision, recall for malignant)

    • Is the full model clearly better?

    • Is there any sign of overfitting (train vs test)?

Test accuracy: 0.9649122807017544
Confusion matrix:
 [[71  1]
 [ 3 39]]
              precision    recall  f1-score   support

      Benign       0.96      0.99      0.97        72
   Malignant       0.97      0.93      0.95        42

    accuracy                           0.96       114
   macro avg       0.97      0.96      0.96       114
weighted avg       0.97      0.96      0.96       114

  1. Create a custom plot which visualizes the confusion matrix It should contain:

    • The four squares of the matrix (color coded)

    • Labels of the actual values in the middle of each square

    • Labels for all squares

    • A colorbar

    • A title

  2. Use scikit-learn to do the same

<Figure size 800x800 with 2 Axes>
<Figure size 600x600 with 2 Axes>

Exercise 5: 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

              precision    recall  f1-score   support

           0       1.00      1.00      1.00        15
           1       0.69      0.60      0.64        15
           2       0.65      0.73      0.69        15

    accuracy                           0.78        45
   macro avg       0.78      0.78      0.78        45
weighted avg       0.78      0.78      0.78        45

              precision    recall  f1-score   support

           0       1.00      1.00      1.00        15
           1       0.73      0.53      0.62        15
           2       0.63      0.80      0.71        15

    accuracy                           0.78        45
   macro avg       0.79      0.78      0.77        45
weighted avg       0.79      0.78      0.77        45

              precision    recall  f1-score   support

           0       1.00      1.00      1.00        15
           1       0.71      0.67      0.69        15
           2       0.69      0.73      0.71        15

    accuracy                           0.80        45
   macro avg       0.80      0.80      0.80        45
weighted avg       0.80      0.80      0.80        45

<Figure size 1200x400 with 3 Axes>

Exercise 6: Polynomial and Flexible Regression¶

In this exercise, we analyse the relationship between wage and age using four flexible regression approaches:

  • Polynomial regression

  • Stepwise functions (degree-0 splines)

  • Spline regression

  • Local regression (LOWESS)

We will use the Wage dataset for the following exercises. Please briefly visit the documentation for further information: https://rdrr.io/cran/ISLR/man/Wage.html

Loading...
<Figure size 640x480 with 1 Axes>

Please predict Wage from Age using four different models:

  1. A polynomial regression model of degree 3

  2. A stepwise model with cut points at 30, 50, and 65 years

  3. A third order spline regression model with df=6

  4. A lowes local regression model with frac=0.4

Plot the resulting model fits in a single figure.

Plot the models:

<Figure size 640x480 with 1 Axes>

Exercise 7: Generalized Additive Models¶

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.

<Figure size 1500x1000 with 6 Axes>

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()

                 Generalized Linear Model Regression Results                  
==============================================================================
Dep. Variable:                   wage   No. Observations:                 3000
Model:                         GLMGam   Df Residuals:                     2981
Model Family:                Gaussian   Df Model:                        18.00
Link Function:               Identity   Scale:                          1230.5
Method:                         PIRLS   Log-Likelihood:                -14920.
Date:                Sun, 14 Dec 2025   Deviance:                   3.6680e+06
Time:                        09:20:03   Pearson chi2:                 3.67e+06
No. Iterations:                     3   Pseudo R-squ. (CS):             0.3436
Covariance Type:            nonrobust                                         
================================================================================================
                                   coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------------------------
education_2. HS Grad            16.2973      2.337      6.975      0.000      11.718      20.877
education_3. Some College       27.8392      2.505     11.114      0.000      22.930      32.749
education_4. College Grad       41.0763      2.533     16.219      0.000      36.113      46.040
education_5. Advanced Degree    63.9348      2.792     22.897      0.000      58.462      69.408
jobclass_2. Information          4.8618      1.355      3.589      0.000       2.206       7.517
maritl_2. Married               13.3632      1.875      7.128      0.000       9.689      17.038
maritl_3. Widowed               -0.2441      8.279     -0.029      0.976     -16.470      15.982
maritl_4. Divorced              -0.1040      3.039     -0.034      0.973      -6.059       5.851
maritl_5. Separated              7.0577      5.046      1.399      0.162      -2.832      16.947
age_s0                          63.8878      5.262     12.142      0.000      53.575      74.200
age_s1                          63.1018      4.154     15.191      0.000      54.960      71.243
age_s2                          74.8020      5.531     13.524      0.000      63.961      85.643
age_s3                          56.5913      8.534      6.631      0.000      39.865      73.318
age_s4                          47.4594     12.372      3.836      0.000      23.211      71.708
year_s0                          4.3025      4.127      1.043      0.297      -3.786      12.391
year_s1                          7.1829      4.559      1.575      0.115      -1.753      16.119
year_s2                         10.0632      4.781      2.105      0.035       0.692      19.435
year_s3                          7.1947      4.284      1.679      0.093      -1.202      15.591
year_s4                         10.7707      2.344      4.595      0.000       6.176      15.365
================================================================================================

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?

   preg  plas  pres  skin  insu  mass   pedi  age
0     6   148    72    35     0  33.6  0.627   50
1     1    85    66    29     0  26.6  0.351   31
2     8   183    64     0     0  23.3  0.672   32
3     1    89    66    23    94  28.1  0.167   21
4     0   137    40    35   168  43.1  2.288   33 

0    tested_positive
1    tested_negative
2    tested_positive
3    tested_negative
4    tested_positive
Name: class, dtype: category
Categories (2, object): ['tested_negative', 'tested_positive']

Train accuracy: 0.7635009310986964
Test accuracy:  0.7445887445887446
<Figure size 1400x700 with 1 Axes>

See if you 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. For example, you can usee:

    • 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

Fitting 5 folds for each of 81 candidates, totalling 405 fits
Best parameters: {'max_depth': 10, 'max_features': 'sqrt', 'min_samples_split': 2, 'n_estimators': 50}
CV accuracy: 0.773

Test accuracy: 0.788

Classification Report:
              precision    recall  f1-score   support

         neg       0.83      0.85      0.84       150
         pos       0.71      0.67      0.69        81

    accuracy                           0.79       231
   macro avg       0.77      0.76      0.76       231
weighted avg       0.79      0.79      0.79       231

Exercise 9: Gradient Boosting¶

Your goal is to manually implement a gradient boosting algorithm and compare it with scikit-learn’s GradientBoostingRegressor. You should complete this exercise without any new libraries.

  • Complete the custom_gb_mse() and predict_gb() functions

    1. Start with constant prediction equal to the mean of y

    2. Compute residuals

    3. Fit weak learners to residuals

    4. Update the model using a learning rate

  • Compare your custom implementation with sklearn

<Figure size 640x480 with 1 Axes>
<Figure size 640x480 with 1 Axes>

Exercise 10: SVMs¶

For the SVM 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).

Loading...

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):


Features:
    frontal  parietal
0  0.007766 -0.006899
1 -0.021452 -0.039327
2  0.016440  0.000300
3 -0.021054 -0.035735
4  0.024296  0.033220

Target:
0    0
1    1
2    0
3    1
4    0
Name: event, dtype: int64

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

Linear SVC
               precision    recall  f1-score   support

           0       0.55      0.99      0.71        80
           1       0.94      0.20      0.33        80

    accuracy                           0.59       160
   macro avg       0.75      0.59      0.52       160
weighted avg       0.75      0.59      0.52       160

RBF SVC
               precision    recall  f1-score   support

           0       0.67      0.85      0.75        80
           1       0.79      0.57      0.67        80

    accuracy                           0.71       160
   macro avg       0.73      0.71      0.71       160
weighted avg       0.73      0.71      0.71       160

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

<Figure size 1200x600 with 2 Axes>

Training a Support Vector Classifier (SVC) on more complex datasets often requires a systematic hyperparameter search to identify optimal model settings.

Implement a grid search that explores multiple kernels and their corresponding hyperparameters using the following configuration:

  • Kernels: rbf, linear

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

  • gamma: np.logspace(-3, 1, 10) (for rbf)

Further use:

  • Cross-validation: 5-fold

  • Scoring metric: accuracy

Note: Usually you would use a finer grid, but we keep it simpler for the sake of the exercise.

After fitting the model:

  1. Print the optimal hyperparameters

  2. Print the best cross-validation accuracy

  3. Print the test accuracy

Best params: {'C': np.float64(0.21544346900318834), 'gamma': np.float64(3.593813663804626), 'kernel': 'rbf'}
CV accuracy: 0.7605765765765765
Test accuracy: 0.74375