{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Tutorial 5: Logistic regression + Grid search for hyperparameter tuning\n", "[![View notebooks on Github](https://img.shields.io/static/v1.svg?logo=github&label=Repo&message=View%20On%20Github&color=lightgrey)](https://github.com/amonroym99/uva-applied-ml/blob/main/docs/notebooks/5_log_reg_gs.ipynb)\n", "\n", "**Author:** Alejandro Monroy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this tutorial we are going to explore a widely used classification algorithm: logistic regression. In addition, we will also learn about grid search, a powerful technique for hyperparameter tuning to optimize model performance." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Loading and preparing the data\n", "We will use the `breast_cancer` dataset from Sklearn, which contains 30 numerical features and a binary target." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ".. _breast_cancer_dataset:\n", "\n", "Breast cancer wisconsin (diagnostic) dataset\n", "--------------------------------------------\n", "\n", "**Data Set Characteristics:**\n", "\n", ":Number of Instances: 569\n", "\n", ":Number of Attributes: 30 numeric, predictive attributes and the class\n", "\n", ":Attribute Information:\n", " - radius (mean of distances from center to points on the perimeter)\n", " - texture (standard deviation of gray-scale values)\n", " - perimeter\n", " - area\n", " - smoothness (local variation in radius lengths)\n", " - compactness (perimeter^2 / area - 1.0)\n", " - concavity (severity of concave portions of the contour)\n", " - concave points (number of concave portions of the contour)\n", " - symmetry\n", " - fractal dimension (\"coastline approximation\" - 1)\n", "\n", " The mean, standard error, and \"worst\" or largest (mean of the three\n", " worst/largest values) of these features were computed for each image,\n", " resulting in 30 features. For instance, field 0 is Mean Radius, field\n", " 10 is Radius SE, field 20 is Worst Radius.\n", "\n", " - class:\n", " - WDBC-Malignant\n", " - WDBC-Benign\n", "\n", ":Summary Statistics:\n", "\n", "===================================== ====== ======\n", " Min Max\n", "===================================== ====== ======\n", "radius (mean): 6.981 28.11\n", "texture (mean): 9.71 39.28\n", "perimeter (mean): 43.79 188.5\n", "area (mean): 143.5 2501.0\n", "smoothness (mean): 0.053 0.163\n", "compactness (mean): 0.019 0.345\n", "concavity (mean): 0.0 0.427\n", "concave points (mean): 0.0 0.201\n", "symmetry (mean): 0.106 0.304\n", "fractal dimension (mean): 0.05 0.097\n", "radius (standard error): 0.112 2.873\n", "texture (standard error): 0.36 4.885\n", "perimeter (standard error): 0.757 21.98\n", "area (standard error): 6.802 542.2\n", "smoothness (standard error): 0.002 0.031\n", "compactness (standard error): 0.002 0.135\n", "concavity (standard error): 0.0 0.396\n", "concave points (standard error): 0.0 0.053\n", "symmetry (standard error): 0.008 0.079\n", "fractal dimension (standard error): 0.001 0.03\n", "radius (worst): 7.93 36.04\n", "texture (worst): 12.02 49.54\n", "perimeter (worst): 50.41 251.2\n", "area (worst): 185.2 4254.0\n", "smoothness (worst): 0.071 0.223\n", "compactness (worst): 0.027 1.058\n", "concavity (worst): 0.0 1.252\n", "concave points (worst): 0.0 0.291\n", "symmetry (worst): 0.156 0.664\n", "fractal dimension (worst): 0.055 0.208\n", "===================================== ====== ======\n", "\n", ":Missing Attribute Values: None\n", "\n", ":Class Distribution: 212 - Malignant, 357 - Benign\n", "\n", ":Creator: Dr. William H. Wolberg, W. Nick Street, Olvi L. Mangasarian\n", "\n", ":Donor: Nick Street\n", "\n", ":Date: November, 1995\n", "\n", "This is a copy of UCI ML Breast Cancer Wisconsin (Diagnostic) datasets.\n", "https://goo.gl/U2Uwz2\n", "\n", "Features are computed from a digitized image of a fine needle\n", "aspirate (FNA) of a breast mass. They describe\n", "characteristics of the cell nuclei present in the image.\n", "\n", "Separating plane described above was obtained using\n", "Multisurface Method-Tree (MSM-T) [K. P. Bennett, \"Decision Tree\n", "Construction Via Linear Programming.\" Proceedings of the 4th\n", "Midwest Artificial Intelligence and Cognitive Science Society,\n", "pp. 97-101, 1992], a classification method which uses linear\n", "programming to construct a decision tree. Relevant features\n", "were selected using an exhaustive search in the space of 1-4\n", "features and 1-3 separating planes.\n", "\n", "The actual linear program used to obtain the separating plane\n", "in the 3-dimensional space is that described in:\n", "[K. P. Bennett and O. L. Mangasarian: \"Robust Linear\n", "Programming Discrimination of Two Linearly Inseparable Sets\",\n", "Optimization Methods and Software 1, 1992, 23-34].\n", "\n", "This database is also available through the UW CS ftp server:\n", "\n", "ftp ftp.cs.wisc.edu\n", "cd math-prog/cpo-dataset/machine-learn/WDBC/\n", "\n", ".. dropdown:: References\n", "\n", " - W.N. Street, W.H. Wolberg and O.L. Mangasarian. Nuclear feature extraction\n", " for breast tumor diagnosis. IS&T/SPIE 1993 International Symposium on\n", " Electronic Imaging: Science and Technology, volume 1905, pages 861-870,\n", " San Jose, CA, 1993.\n", " - O.L. Mangasarian, W.N. Street and W.H. Wolberg. Breast cancer diagnosis and\n", " prognosis via linear programming. Operations Research, 43(4), pages 570-577,\n", " July-August 1995.\n", " - W.H. Wolberg, W.N. Street, and O.L. Mangasarian. Machine learning techniques\n", " to diagnose breast cancer from fine-needle aspirates. Cancer Letters 77 (1994)\n", " 163-171.\n", "\n" ] } ], "source": [ "from sklearn.datasets import load_breast_cancer\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.preprocessing import StandardScaler\n", "\n", "# Loading the dataset\n", "breast = load_breast_cancer()\n", "X, y = breast.data, breast.target\n", "\n", "print(breast.DESCR)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Training set size: (455, 30)\n", "Testing set size: (114, 30)\n" ] } ], "source": [ "# Train-test split\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", "\n", "# Standarization of the featues\n", "scaler = StandardScaler()\n", "X_train = scaler.fit_transform(X_train)\n", "X_test = scaler.transform(X_test)\n", "\n", "print(f\"Training set size: {X_train.shape}\")\n", "print(f\"Testing set size: {X_test.shape}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Logistic regression (binary case)\n", "\n", "Logistic regression is a statistical model for datasets in which there are one or more independent variables that determine and a binary outcome. \n", "\n", "The logistic function is defined as:\n", "\n", "$$\n", "\\sigma(z) = \\frac{1}{1 + e^{-z}}\n", "$$\n", "\n", "where ($z$) is the linear combination of the input features and their corresponding coefficients:\n", "\n", "$$\n", "z = \\beta_0 + \\beta_1 x_1 + \\beta_2 x_2 + \\cdots + \\beta_n x_n\n", "$$\n", "\n", "The probability of the outcome can be written as:\n", "\n", "$$\n", "P(Y=1|X) = \\sigma(z) = \\frac{1}{1 + e^{-(\\beta_0 + \\beta_1 x_1 + \\beta_2 x_2 + \\cdots + \\beta_n x_n)}}\n", "$$\n", "\n", "So, in short, what we are doing is to apply linear regression to compute the logit ($z$) that is fed into the logistic function ($\\sigma$) to get the probability of class $1$. We can then compare that probability with a threshold (usually $0.5$) to get the predicted class (so we predict class $1$ if the probability is above the threshold and $0$ otherwise).\n", "\n", "The coefficients ($\\beta_0, \\beta_1, \\ldots, \\beta_n$) are estimated using maximum likelihood estimation on the cross-entropy loss:\n", "\n", "$$\n", "\\text{Loss} = -\\frac{1}{N} \\sum_{i=1}^N \\left[ y_i \\log(p_i) + (1 - y_i) \\log(1 - p_i) \\right]\n", "$$\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The model is available in the `sklearn.linear_model` module:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.9737\n" ] } ], "source": [ "from sklearn.linear_model import LogisticRegression\n", "from sklearn.metrics import accuracy_score\n", "\n", "# Initialize the logistic regression model\n", "log_reg = LogisticRegression()\n", "\n", "# Fit the model on the training data\n", "log_reg.fit(X_train, y_train)\n", "\n", "# Predict on the test set\n", "y_pred = log_reg.predict(X_test)\n", "\n", "# Evaluate the model\n", "accuracy = accuracy_score(y_test, y_pred)\n", "print(f\"Accuracy: {accuracy:.4f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we did in linear regression, we can retrive the parameters of the model for interpretability purposes:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Coefficients: [[-0.43190368 -0.38732553 -0.39343248 -0.46521006 -0.07166728 0.54016395\n", " -0.8014581 -1.11980408 0.23611852 0.07592093 -1.26817815 0.18887738\n", " -0.61058302 -0.9071857 -0.31330675 0.68249145 0.17527452 -0.3112999\n", " 0.50042502 0.61622993 -0.87984024 -1.35060559 -0.58945273 -0.84184594\n", " -0.54416967 0.01611019 -0.94305313 -0.77821726 -1.20820031 -0.15741387]]\n", "Intercept: [0.44558453]\n" ] } ], "source": [ "print(\"Coefficients: \", log_reg.coef_)\n", "print(\"Intercept: \", log_reg.intercept_)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Cross validation and Grid Search for hyperparameter tuning\n", "Cross-validation is a technique used to evaluate the performance of a machine learning model by splitting the dataset into multiple subsets (folds). The model is trained on some folds and tested on the remaining fold(s). This process is repeated multiple times, and the results are averaged to provide a more reliable estimate of the model's performance. \n", "\n", "Grid Search is a method for hyperparameter tuning that systematically searches through a predefined set of hyperparameter values. It evaluates the model's performance for each combination of hyperparameters using cross-validation and selects the combination that yields the best performance. This ensures that the model is optimized for the given dataset.\n", "\n", "The diagram below illustrates the hyperparameter search procedure via 5-fold cross-validation:\n", "\n", "\n", "
\n", " \"Grid\n", "
Source: scikit-learn.org\n", "
\n", "\n", "The training set is divided into 5 folds, and the model is trained and validated 5 times—each time using a different fold as the validation set and the remaining 4 folds as the training set. This process is repeated for each combination of hyperparameters under consideration.\n", "\n", "The average validation performance across these 5 splits is used to select the best set of hyperparameters. Once the best parameters are identified, a final model is trained on the entire training set (i.e., all 5 folds), and this final model is then evaluated on the held-out test set, which was never seen during training or validation.\n", "\n", "Let's use grid search to find the best parameters of a random forest model for breast cancer prediction. First, we define our grid as a dictionary where keys are the names of the parameters and the values are the list of values to test for each parameter:\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "rf_param_grid = {\n", " 'n_estimators': [25, 50, 75, 100, 200],\n", " 'max_depth': [None, 5, 10, 20],\n", " 'min_samples_split': [None, 2, 5, 10]\n", "}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then, we just need to initialize our model and a `GridSearchCV` object and fit it to the training data. The `cv` parameter indicates the number of folds used for cross-validation, and `scoring` is the evaluation metric." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
GridSearchCV(cv=5, estimator=RandomForestClassifier(),\n",
       "             param_grid={'max_depth': [None, 5, 10, 20],\n",
       "                         'min_samples_split': [2, 5, 10],\n",
       "                         'n_estimators': [25, 50, 75, 100, 200, 300]},\n",
       "             scoring='accuracy')
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
" ], "text/plain": [ "GridSearchCV(cv=5, estimator=RandomForestClassifier(),\n", " param_grid={'max_depth': [None, 5, 10, 20],\n", " 'min_samples_split': [2, 5, 10],\n", " 'n_estimators': [25, 50, 75, 100, 200, 300]},\n", " scoring='accuracy')" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from sklearn.ensemble import RandomForestClassifier\n", "from sklearn.model_selection import GridSearchCV\n", "\n", "# Define parameter grid for Random Forest\n", "rf_param_grid = {\n", " 'n_estimators': [25, 50, 75, 100, 200, 300],\n", " 'max_depth': [None, 5, 10, 20],\n", " 'min_samples_split': [2, 5, 10]\n", "}\n", "\n", "rf = RandomForestClassifier()\n", "\n", "grid_search = GridSearchCV(rf, rf_param_grid, cv=5, scoring='accuracy')\n", "grid_search.fit(X_train, y_train)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "After fitting the grid search, we can access the best parameters and the best validation score:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Best parameters: {'max_depth': None, 'min_samples_split': 2, 'n_estimators': 75}\n", "Best cross-validation accuracy: 0.9626\n" ] } ], "source": [ "best_params = grid_search.best_params_\n", "best_validation_accuracy = grid_search.best_score_\n", "\n", "print(\"Best parameters:\", best_params)\n", "print(f\"Best cross-validation accuracy: {best_validation_accuracy:.4f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we can compute the score of the best model on the test set:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Best model test accuracy: 0.9649\n" ] } ], "source": [ "best_model = grid_search.best_estimator_\n", "\n", "y_pred = best_model.predict(X_test)\n", "accuracy = accuracy_score(y_test, y_pred)\n", "\n", "print(f\"Best model test accuracy: {accuracy:.4f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "🤔 **Food for thought:** Pay special attention to the difference between the validation and test accuracy for the best model. The validation accuracy is computed on data used during model selection (cross-validation on the training set), while the test accuracy is evaluated on completely unseen data, and therefore is a better metric to report the performance of our model." ] } ], "metadata": { "kernelspec": { "display_name": "tml_25", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.9" } }, "nbformat": 4, "nbformat_minor": 2 }