2431 lines
83 KiB
Plaintext
2431 lines
83 KiB
Plaintext
{
|
||
"cells": [
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3a65fcc4",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"<!-- HTML file automatically generated from DocOnce source (https://github.com/doconce/doconce/)\n",
|
||
"doconce format html week39.do.txt --no_mako -->\n",
|
||
"<!-- dom:TITLE: Week 39: Resampling methods and logistic regression -->"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "284ac98b",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"# Week 39: Resampling methods and logistic regression\n",
|
||
"**Morten Hjorth-Jensen**, Department of Physics, University of Oslo\n",
|
||
"\n",
|
||
"Date: **Week 39**"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "582e0b32",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Plan for week 39, September 22-26, 2025\n",
|
||
"\n",
|
||
"**Material for the lecture on Monday September 22.**\n",
|
||
"\n",
|
||
"1. Resampling techniques, Bootstrap and cross validation and bias-variance tradeoff\n",
|
||
"\n",
|
||
"2. Logistic regression, our first classification encounter and a stepping stone towards neural networks\n",
|
||
"\n",
|
||
"3. [Video of lecture](https://youtu.be/OVouJyhoksY)\n",
|
||
"\n",
|
||
"4. [Whiteboard notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/2024/FYSSTKweek39.pdf)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "08ea52de",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Readings and Videos, resampling methods\n",
|
||
"1. Raschka et al, pages 175-192\n",
|
||
"\n",
|
||
"2. Hastie et al Chapter 7, here we recommend 7.1-7.5 and 7.10 (cross-validation) and 7.11 (bootstrap). See <https://link.springer.com/book/10.1007/978-0-387-84858-7>.\n",
|
||
"\n",
|
||
"3. [Video on bias-variance tradeoff](https://www.youtube.com/watch?v=EuBBz3bI-aA)\n",
|
||
"\n",
|
||
"4. [Video on Bootstrapping](https://www.youtube.com/watch?v=Xz0x-8-cgaQ)\n",
|
||
"\n",
|
||
"5. [Video on cross validation](https://www.youtube.com/watch?v=fSytzGwwBVw)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a8d5878f",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Readings and Videos, logistic regression\n",
|
||
"1. Hastie et al 4.1, 4.2 and 4.3 on logistic regression\n",
|
||
"\n",
|
||
"2. Raschka et al, pages 53-76 on Logistic regression and pages 37-52 on gradient optimization\n",
|
||
"\n",
|
||
"3. [Video on Logistic regression](https://www.youtube.com/watch?v=C5268D9t9Ak)\n",
|
||
"\n",
|
||
"4. [Yet another video on logistic regression](https://www.youtube.com/watch?v=yIYKR4sgzI8)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e93210f9",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Lab sessions week 39\n",
|
||
"\n",
|
||
"**Material for the lab sessions on Tuesday and Wednesday.**\n",
|
||
"\n",
|
||
"1. Discussions on how to structure your report for the first project\n",
|
||
"\n",
|
||
"2. Exercise for week 39 on how to write the abstract and the introduction of the report and how to include references. \n",
|
||
"\n",
|
||
"3. Work on project 1, in particular resampling methods like cross-validation and bootstrap. **For more discussions of project 1, chapter 5 of Goodfellow et al is a good read, in particular sections 5.1-5.5 and 5.7-5.11**.\n",
|
||
"\n",
|
||
"4. [Video on how to write scientific reports recorded during one of the lab sessions](https://youtu.be/tVW1ZDmZnwM)\n",
|
||
"\n",
|
||
"5. A general guideline can be found at <https://github.com/CompPhysics/MachineLearning/blob/master/doc/Projects/EvaluationGrading/EvaluationForm.md>."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c319a504",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Lecture material"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "5f29284a",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Resampling methods\n",
|
||
"Resampling methods are an indispensable tool in modern\n",
|
||
"statistics. They involve repeatedly drawing samples from a training\n",
|
||
"set and refitting a model of interest on each sample in order to\n",
|
||
"obtain additional information about the fitted model. For example, in\n",
|
||
"order to estimate the variability of a linear regression fit, we can\n",
|
||
"repeatedly draw different samples from the training data, fit a linear\n",
|
||
"regression to each new sample, and then examine the extent to which\n",
|
||
"the resulting fits differ. Such an approach may allow us to obtain\n",
|
||
"information that would not be available from fitting the model only\n",
|
||
"once using the original training sample.\n",
|
||
"\n",
|
||
"Two resampling methods are often used in Machine Learning analyses,\n",
|
||
"1. The **bootstrap method**\n",
|
||
"\n",
|
||
"2. and **Cross-Validation**\n",
|
||
"\n",
|
||
"In addition there are several other methods such as the Jackknife and the Blocking methods. This week will repeat some of the elements of the bootstrap method and focus more on cross-validation."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4a774608",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Resampling approaches can be computationally expensive\n",
|
||
"\n",
|
||
"Resampling approaches can be computationally expensive, because they\n",
|
||
"involve fitting the same statistical method multiple times using\n",
|
||
"different subsets of the training data. However, due to recent\n",
|
||
"advances in computing power, the computational requirements of\n",
|
||
"resampling methods generally are not prohibitive. In this chapter, we\n",
|
||
"discuss two of the most commonly used resampling methods,\n",
|
||
"cross-validation and the bootstrap. Both methods are important tools\n",
|
||
"in the practical application of many statistical learning\n",
|
||
"procedures. For example, cross-validation can be used to estimate the\n",
|
||
"test error associated with a given statistical learning method in\n",
|
||
"order to evaluate its performance, or to select the appropriate level\n",
|
||
"of flexibility. The process of evaluating a model’s performance is\n",
|
||
"known as model assessment, whereas the process of selecting the proper\n",
|
||
"level of flexibility for a model is known as model selection. The\n",
|
||
"bootstrap is widely used."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "5e62c381",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Why resampling methods ?\n",
|
||
"**Statistical analysis.**\n",
|
||
"\n",
|
||
"* Our simulations can be treated as *computer experiments*. This is particularly the case for Monte Carlo methods which are widely used in statistical analyses.\n",
|
||
"\n",
|
||
"* The results can be analysed with the same statistical tools as we would use when analysing experimental data.\n",
|
||
"\n",
|
||
"* As in all experiments, we are looking for expectation values and an estimate of how accurate they are, i.e., possible sources for errors."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "96896342",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Statistical analysis\n",
|
||
"\n",
|
||
"* As in other experiments, many numerical experiments have two classes of errors:\n",
|
||
"\n",
|
||
" * Statistical errors\n",
|
||
"\n",
|
||
" * Systematical errors\n",
|
||
"\n",
|
||
"* Statistical errors can be estimated using standard tools from statistics\n",
|
||
"\n",
|
||
"* Systematical errors are method specific and must be treated differently from case to case."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d5318be7",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Resampling methods\n",
|
||
"\n",
|
||
"With all these analytical equations for both the OLS and Ridge\n",
|
||
"regression, we will now outline how to assess a given model. This will\n",
|
||
"lead to a discussion of the so-called bias-variance tradeoff (see\n",
|
||
"below) and so-called resampling methods.\n",
|
||
"\n",
|
||
"One of the quantities we have discussed as a way to measure errors is\n",
|
||
"the mean-squared error (MSE), mainly used for fitting of continuous\n",
|
||
"functions. Another choice is the absolute error.\n",
|
||
"\n",
|
||
"In the discussions below we will focus on the MSE and in particular since we will split the data into test and training data,\n",
|
||
"we discuss the\n",
|
||
"1. prediction error or simply the **test error** $\\mathrm{Err_{Test}}$, where we have a fixed training set and the test error is the MSE arising from the data reserved for testing. We discuss also the \n",
|
||
"\n",
|
||
"2. training error $\\mathrm{Err_{Train}}$, which is the average loss over the training data.\n",
|
||
"\n",
|
||
"As our model becomes more and more complex, more of the training data tends to used. The training may thence adapt to more complicated structures in the data. This may lead to a decrease in the bias (see below for code example) and a slight increase of the variance for the test error.\n",
|
||
"For a certain level of complexity the test error will reach minimum, before starting to increase again. The\n",
|
||
"training error reaches a saturation."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7597015e",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Resampling methods: Bootstrap\n",
|
||
"Bootstrapping is a [non-parametric approach](https://en.wikipedia.org/wiki/Nonparametric_statistics) to statistical inference\n",
|
||
"that substitutes computation for more traditional distributional\n",
|
||
"assumptions and asymptotic results. Bootstrapping offers a number of\n",
|
||
"advantages: \n",
|
||
"1. The bootstrap is quite general, although there are some cases in which it fails. \n",
|
||
"\n",
|
||
"2. Because it does not require distributional assumptions (such as normally distributed errors), the bootstrap can provide more accurate inferences when the data are not well behaved or when the sample size is small. \n",
|
||
"\n",
|
||
"3. It is possible to apply the bootstrap to statistics with sampling distributions that are difficult to derive, even asymptotically. \n",
|
||
"\n",
|
||
"4. It is relatively simple to apply the bootstrap to complex data-collection plans (such as stratified and clustered samples).\n",
|
||
"\n",
|
||
"The textbook by [Davison on the Bootstrap Methods and their Applications](https://www.cambridge.org/core/books/bootstrap-methods-and-their-application/ED2FD043579F27952363566DC09CBD6A) provides many more insights and proofs. In this course we will take a more practical approach and use the results and theorems provided in the literature. For those interested in reading more about the bootstrap methods, we recommend the above text and the one by [Efron and Tibshirani](https://www.routledge.com/An-Introduction-to-the-Bootstrap/Efron-Tibshirani/p/book/9780412042317)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "fbf69230",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## The bias-variance tradeoff\n",
|
||
"\n",
|
||
"We will discuss the bias-variance tradeoff in the context of\n",
|
||
"continuous predictions such as regression. However, many of the\n",
|
||
"intuitions and ideas discussed here also carry over to classification\n",
|
||
"tasks. Consider a dataset $\\mathcal{D}$ consisting of the data\n",
|
||
"$\\mathbf{X}_\\mathcal{D}=\\{(y_j, \\boldsymbol{x}_j), j=0\\ldots n-1\\}$. \n",
|
||
"\n",
|
||
"Let us assume that the true data is generated from a noisy model"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "358f7872",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{y}=f(\\boldsymbol{x}) + \\boldsymbol{\\epsilon}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "6a4aceef",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"where $\\epsilon$ is normally distributed with mean zero and standard deviation $\\sigma^2$.\n",
|
||
"\n",
|
||
"In our derivation of the ordinary least squares method we defined then\n",
|
||
"an approximation to the function $f$ in terms of the parameters\n",
|
||
"$\\boldsymbol{\\theta}$ and the design matrix $\\boldsymbol{X}$ which embody our model,\n",
|
||
"that is $\\boldsymbol{\\tilde{y}}=\\boldsymbol{X}\\boldsymbol{\\theta}$. \n",
|
||
"\n",
|
||
"Thereafter we found the parameters $\\boldsymbol{\\theta}$ by optimizing the means squared error via the so-called cost function"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "84416669",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"C(\\boldsymbol{X},\\boldsymbol{\\theta}) =\\frac{1}{n}\\sum_{i=0}^{n-1}(y_i-\\tilde{y}_i)^2=\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right].\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "0036358e",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"We can rewrite this as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d712d2d7",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\frac{1}{n}\\sum_i(f_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\frac{1}{n}\\sum_i(\\tilde{y}_i-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2+\\sigma^2.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b71e48ac",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"The three terms represent the square of the bias of the learning\n",
|
||
"method, which can be thought of as the error caused by the simplifying\n",
|
||
"assumptions built into the method. The second term represents the\n",
|
||
"variance of the chosen model and finally the last terms is variance of\n",
|
||
"the error $\\boldsymbol{\\epsilon}$.\n",
|
||
"\n",
|
||
"To derive this equation, we need to recall that the variance of $\\boldsymbol{y}$ and $\\boldsymbol{\\epsilon}$ are both equal to $\\sigma^2$. The mean value of $\\boldsymbol{\\epsilon}$ is by definition equal to zero. Furthermore, the function $f$ is not a stochastics variable, idem for $\\boldsymbol{\\tilde{y}}$.\n",
|
||
"We use a more compact notation in terms of the expectation value"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c78ceafe",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}})^2\\right],\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "74aae5bc",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"and adding and subtracting $\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]$ we get"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1f2313f1",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{f}+\\boldsymbol{\\epsilon}-\\boldsymbol{\\tilde{y}}+\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right]-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right],\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a29b174f",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"which, using the abovementioned expectation values can be rewritten as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3bc08002",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathbb{E}\\left[(\\boldsymbol{y}-\\boldsymbol{\\tilde{y}})^2\\right]=\\mathbb{E}\\left[(\\boldsymbol{y}-\\mathbb{E}\\left[\\boldsymbol{\\tilde{y}}\\right])^2\\right]+\\mathrm{Var}\\left[\\boldsymbol{\\tilde{y}}\\right]+\\sigma^2,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7b7d24e8",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"that is the rewriting in terms of the so-called bias, the variance of the model $\\boldsymbol{\\tilde{y}}$ and the variance of $\\boldsymbol{\\epsilon}$.\n",
|
||
"\n",
|
||
"**Note that in order to derive these equations we have assumed we can replace the unknown function $\\boldsymbol{f}$ with the target/output data $\\boldsymbol{y}$.**"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f2118d82",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## A way to Read the Bias-Variance Tradeoff\n",
|
||
"\n",
|
||
"<!-- dom:FIGURE: [figures/BiasVariance.png, width=600 frac=0.9] -->\n",
|
||
"<!-- begin figure -->\n",
|
||
"\n",
|
||
"<img src=\"figures/BiasVariance.png\" width=\"600\"><p style=\"font-size: 0.9em\"><i>Figure 1: </i></p>\n",
|
||
"<!-- end figure -->"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "baf08f8a",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Understanding what happens"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 1,
|
||
"id": "1bd7ac4e",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"%matplotlib inline\n",
|
||
"\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"import numpy as np\n",
|
||
"from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
|
||
"from sklearn.preprocessing import PolynomialFeatures\n",
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"from sklearn.pipeline import make_pipeline\n",
|
||
"from sklearn.utils import resample\n",
|
||
"\n",
|
||
"np.random.seed(2018)\n",
|
||
"\n",
|
||
"n = 40\n",
|
||
"n_boostraps = 100\n",
|
||
"maxdegree = 14\n",
|
||
"\n",
|
||
"\n",
|
||
"# Make data set.\n",
|
||
"x = np.linspace(-3, 3, n).reshape(-1, 1)\n",
|
||
"y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)\n",
|
||
"error = np.zeros(maxdegree)\n",
|
||
"bias = np.zeros(maxdegree)\n",
|
||
"variance = np.zeros(maxdegree)\n",
|
||
"polydegree = np.zeros(maxdegree)\n",
|
||
"x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)\n",
|
||
"\n",
|
||
"for degree in range(maxdegree):\n",
|
||
" model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))\n",
|
||
" y_pred = np.empty((y_test.shape[0], n_boostraps))\n",
|
||
" for i in range(n_boostraps):\n",
|
||
" x_, y_ = resample(x_train, y_train)\n",
|
||
" y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()\n",
|
||
"\n",
|
||
" polydegree[degree] = degree\n",
|
||
" error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )\n",
|
||
" bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )\n",
|
||
" variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )\n",
|
||
" print('Polynomial degree:', degree)\n",
|
||
" print('Error:', error[degree])\n",
|
||
" print('Bias^2:', bias[degree])\n",
|
||
" print('Var:', variance[degree])\n",
|
||
" print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))\n",
|
||
"\n",
|
||
"plt.plot(polydegree, error, label='Error')\n",
|
||
"plt.plot(polydegree, bias, label='bias')\n",
|
||
"plt.plot(polydegree, variance, label='Variance')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3edb75ab",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Summing up\n",
|
||
"\n",
|
||
"The bias-variance tradeoff summarizes the fundamental tension in\n",
|
||
"machine learning, particularly supervised learning, between the\n",
|
||
"complexity of a model and the amount of training data needed to train\n",
|
||
"it. Since data is often limited, in practice it is often useful to\n",
|
||
"use a less-complex model with higher bias, that is a model whose asymptotic\n",
|
||
"performance is worse than another model because it is easier to\n",
|
||
"train and less sensitive to sampling noise arising from having a\n",
|
||
"finite-sized training dataset (smaller variance). \n",
|
||
"\n",
|
||
"The above equations tell us that in\n",
|
||
"order to minimize the expected test error, we need to select a\n",
|
||
"statistical learning method that simultaneously achieves low variance\n",
|
||
"and low bias. Note that variance is inherently a nonnegative quantity,\n",
|
||
"and squared bias is also nonnegative. Hence, we see that the expected\n",
|
||
"test MSE can never lie below $Var(\\epsilon)$, the irreducible error.\n",
|
||
"\n",
|
||
"What do we mean by the variance and bias of a statistical learning\n",
|
||
"method? The variance refers to the amount by which our model would change if we\n",
|
||
"estimated it using a different training data set. Since the training\n",
|
||
"data are used to fit the statistical learning method, different\n",
|
||
"training data sets will result in a different estimate. But ideally the\n",
|
||
"estimate for our model should not vary too much between training\n",
|
||
"sets. However, if a method has high variance then small changes in\n",
|
||
"the training data can result in large changes in the model. In general, more\n",
|
||
"flexible statistical methods have higher variance.\n",
|
||
"\n",
|
||
"You may also find this recent [article](https://www.pnas.org/content/116/32/15849) of interest."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "88ce8a48",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Another Example from Scikit-Learn's Repository\n",
|
||
"\n",
|
||
"This example demonstrates the problems of underfitting and overfitting and\n",
|
||
"how we can use linear regression with polynomial features to approximate\n",
|
||
"nonlinear functions. The plot shows the function that we want to approximate,\n",
|
||
"which is a part of the cosine function. In addition, the samples from the\n",
|
||
"real function and the approximations of different models are displayed. The\n",
|
||
"models have polynomial features of different degrees. We can see that a\n",
|
||
"linear function (polynomial with degree 1) is not sufficient to fit the\n",
|
||
"training samples. This is called **underfitting**. A polynomial of degree 4\n",
|
||
"approximates the true function almost perfectly. However, for higher degrees\n",
|
||
"the model will **overfit** the training data, i.e. it learns the noise of the\n",
|
||
"training data.\n",
|
||
"We evaluate quantitatively overfitting and underfitting by using\n",
|
||
"cross-validation. We calculate the mean squared error (MSE) on the validation\n",
|
||
"set, the higher, the less likely the model generalizes correctly from the\n",
|
||
"training data."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 2,
|
||
"id": "40385eb8",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"\n",
|
||
"\n",
|
||
"#print(__doc__)\n",
|
||
"\n",
|
||
"import numpy as np\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.pipeline import Pipeline\n",
|
||
"from sklearn.preprocessing import PolynomialFeatures\n",
|
||
"from sklearn.linear_model import LinearRegression\n",
|
||
"from sklearn.model_selection import cross_val_score\n",
|
||
"\n",
|
||
"\n",
|
||
"def true_fun(X):\n",
|
||
" return np.cos(1.5 * np.pi * X)\n",
|
||
"\n",
|
||
"np.random.seed(0)\n",
|
||
"\n",
|
||
"n_samples = 30\n",
|
||
"degrees = [1, 4, 15]\n",
|
||
"\n",
|
||
"X = np.sort(np.random.rand(n_samples))\n",
|
||
"y = true_fun(X) + np.random.randn(n_samples) * 0.1\n",
|
||
"\n",
|
||
"plt.figure(figsize=(14, 5))\n",
|
||
"for i in range(len(degrees)):\n",
|
||
" ax = plt.subplot(1, len(degrees), i + 1)\n",
|
||
" plt.setp(ax, xticks=(), yticks=())\n",
|
||
"\n",
|
||
" polynomial_features = PolynomialFeatures(degree=degrees[i],\n",
|
||
" include_bias=False)\n",
|
||
" linear_regression = LinearRegression()\n",
|
||
" pipeline = Pipeline([(\"polynomial_features\", polynomial_features),\n",
|
||
" (\"linear_regression\", linear_regression)])\n",
|
||
" pipeline.fit(X[:, np.newaxis], y)\n",
|
||
"\n",
|
||
" # Evaluate the models using crossvalidation\n",
|
||
" scores = cross_val_score(pipeline, X[:, np.newaxis], y,\n",
|
||
" scoring=\"neg_mean_squared_error\", cv=10)\n",
|
||
"\n",
|
||
" X_test = np.linspace(0, 1, 100)\n",
|
||
" plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label=\"Model\")\n",
|
||
" plt.plot(X_test, true_fun(X_test), label=\"True function\")\n",
|
||
" plt.scatter(X, y, edgecolor='b', s=20, label=\"Samples\")\n",
|
||
" plt.xlabel(\"x\")\n",
|
||
" plt.ylabel(\"y\")\n",
|
||
" plt.xlim((0, 1))\n",
|
||
" plt.ylim((-2, 2))\n",
|
||
" plt.legend(loc=\"best\")\n",
|
||
" plt.title(\"Degree {}\\nMSE = {:.2e}(+/- {:.2e})\".format(\n",
|
||
" degrees[i], -scores.mean(), scores.std()))\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a0c0d4df",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Various steps in cross-validation\n",
|
||
"\n",
|
||
"When the repetitive splitting of the data set is done randomly,\n",
|
||
"samples may accidently end up in a fast majority of the splits in\n",
|
||
"either training or test set. Such samples may have an unbalanced\n",
|
||
"influence on either model building or prediction evaluation. To avoid\n",
|
||
"this $k$-fold cross-validation structures the data splitting. The\n",
|
||
"samples are divided into $k$ more or less equally sized exhaustive and\n",
|
||
"mutually exclusive subsets. In turn (at each split) one of these\n",
|
||
"subsets plays the role of the test set while the union of the\n",
|
||
"remaining subsets constitutes the training set. Such a splitting\n",
|
||
"warrants a balanced representation of each sample in both training and\n",
|
||
"test set over the splits. Still the division into the $k$ subsets\n",
|
||
"involves a degree of randomness. This may be fully excluded when\n",
|
||
"choosing $k=n$. This particular case is referred to as leave-one-out\n",
|
||
"cross-validation (LOOCV)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "68d3e653",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Cross-validation in brief\n",
|
||
"\n",
|
||
"For the various values of $k$\n",
|
||
"\n",
|
||
"1. shuffle the dataset randomly.\n",
|
||
"\n",
|
||
"2. Split the dataset into $k$ groups.\n",
|
||
"\n",
|
||
"3. For each unique group:\n",
|
||
"\n",
|
||
"a. Decide which group to use as set for test data\n",
|
||
"\n",
|
||
"b. Take the remaining groups as a training data set\n",
|
||
"\n",
|
||
"c. Fit a model on the training set and evaluate it on the test set\n",
|
||
"\n",
|
||
"d. Retain the evaluation score and discard the model\n",
|
||
"\n",
|
||
"5. Summarize the model using the sample of model evaluation scores"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7f7a6350",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Code Example for Cross-validation and $k$-fold Cross-validation\n",
|
||
"\n",
|
||
"The code here uses Ridge regression with cross-validation (CV) resampling and $k$-fold CV in order to fit a specific polynomial."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 3,
|
||
"id": "23eef50b",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.model_selection import KFold\n",
|
||
"from sklearn.linear_model import Ridge\n",
|
||
"from sklearn.model_selection import cross_val_score\n",
|
||
"from sklearn.preprocessing import PolynomialFeatures\n",
|
||
"\n",
|
||
"# A seed just to ensure that the random numbers are the same for every run.\n",
|
||
"# Useful for eventual debugging.\n",
|
||
"np.random.seed(3155)\n",
|
||
"\n",
|
||
"# Generate the data.\n",
|
||
"nsamples = 100\n",
|
||
"x = np.random.randn(nsamples)\n",
|
||
"y = 3*x**2 + np.random.randn(nsamples)\n",
|
||
"\n",
|
||
"## Cross-validation on Ridge regression using KFold only\n",
|
||
"\n",
|
||
"# Decide degree on polynomial to fit\n",
|
||
"poly = PolynomialFeatures(degree = 6)\n",
|
||
"\n",
|
||
"# Decide which values of lambda to use\n",
|
||
"nlambdas = 500\n",
|
||
"lambdas = np.logspace(-3, 5, nlambdas)\n",
|
||
"\n",
|
||
"# Initialize a KFold instance\n",
|
||
"k = 5\n",
|
||
"kfold = KFold(n_splits = k)\n",
|
||
"\n",
|
||
"# Perform the cross-validation to estimate MSE\n",
|
||
"scores_KFold = np.zeros((nlambdas, k))\n",
|
||
"\n",
|
||
"i = 0\n",
|
||
"for lmb in lambdas:\n",
|
||
" ridge = Ridge(alpha = lmb)\n",
|
||
" j = 0\n",
|
||
" for train_inds, test_inds in kfold.split(x):\n",
|
||
" xtrain = x[train_inds]\n",
|
||
" ytrain = y[train_inds]\n",
|
||
"\n",
|
||
" xtest = x[test_inds]\n",
|
||
" ytest = y[test_inds]\n",
|
||
"\n",
|
||
" Xtrain = poly.fit_transform(xtrain[:, np.newaxis])\n",
|
||
" ridge.fit(Xtrain, ytrain[:, np.newaxis])\n",
|
||
"\n",
|
||
" Xtest = poly.fit_transform(xtest[:, np.newaxis])\n",
|
||
" ypred = ridge.predict(Xtest)\n",
|
||
"\n",
|
||
" scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)\n",
|
||
"\n",
|
||
" j += 1\n",
|
||
" i += 1\n",
|
||
"\n",
|
||
"\n",
|
||
"estimated_mse_KFold = np.mean(scores_KFold, axis = 1)\n",
|
||
"\n",
|
||
"## Cross-validation using cross_val_score from sklearn along with KFold\n",
|
||
"\n",
|
||
"# kfold is an instance initialized above as:\n",
|
||
"# kfold = KFold(n_splits = k)\n",
|
||
"\n",
|
||
"estimated_mse_sklearn = np.zeros(nlambdas)\n",
|
||
"i = 0\n",
|
||
"for lmb in lambdas:\n",
|
||
" ridge = Ridge(alpha = lmb)\n",
|
||
"\n",
|
||
" X = poly.fit_transform(x[:, np.newaxis])\n",
|
||
" estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)\n",
|
||
"\n",
|
||
" # cross_val_score return an array containing the estimated negative mse for every fold.\n",
|
||
" # we have to the the mean of every array in order to get an estimate of the mse of the model\n",
|
||
" estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)\n",
|
||
"\n",
|
||
" i += 1\n",
|
||
"\n",
|
||
"## Plot and compare the slightly different ways to perform cross-validation\n",
|
||
"\n",
|
||
"plt.figure()\n",
|
||
"\n",
|
||
"plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')\n",
|
||
"#plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')\n",
|
||
"\n",
|
||
"plt.xlabel('log10(lambda)')\n",
|
||
"plt.ylabel('mse')\n",
|
||
"\n",
|
||
"plt.legend()\n",
|
||
"\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "76662787",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## More examples on bootstrap and cross-validation and errors"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 4,
|
||
"id": "166cd085",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Common imports\n",
|
||
"import os\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"from sklearn.utils import resample\n",
|
||
"from sklearn.metrics import mean_squared_error\n",
|
||
"# Where to save the figures and data files\n",
|
||
"PROJECT_ROOT_DIR = \"Results\"\n",
|
||
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
||
"DATA_ID = \"DataFiles/\"\n",
|
||
"\n",
|
||
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
||
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
||
"\n",
|
||
"if not os.path.exists(FIGURE_ID):\n",
|
||
" os.makedirs(FIGURE_ID)\n",
|
||
"\n",
|
||
"if not os.path.exists(DATA_ID):\n",
|
||
" os.makedirs(DATA_ID)\n",
|
||
"\n",
|
||
"def image_path(fig_id):\n",
|
||
" return os.path.join(FIGURE_ID, fig_id)\n",
|
||
"\n",
|
||
"def data_path(dat_id):\n",
|
||
" return os.path.join(DATA_ID, dat_id)\n",
|
||
"\n",
|
||
"def save_fig(fig_id):\n",
|
||
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
||
"\n",
|
||
"infile = open(data_path(\"EoS.csv\"),'r')\n",
|
||
"\n",
|
||
"# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
|
||
"EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
|
||
"EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
|
||
"EoS = EoS.dropna()\n",
|
||
"Energies = EoS['Energy']\n",
|
||
"Density = EoS['Density']\n",
|
||
"# The design matrix now as function of various polytrops\n",
|
||
"\n",
|
||
"Maxpolydegree = 30\n",
|
||
"X = np.zeros((len(Density),Maxpolydegree))\n",
|
||
"X[:,0] = 1.0\n",
|
||
"testerror = np.zeros(Maxpolydegree)\n",
|
||
"trainingerror = np.zeros(Maxpolydegree)\n",
|
||
"polynomial = np.zeros(Maxpolydegree)\n",
|
||
"\n",
|
||
"trials = 100\n",
|
||
"for polydegree in range(1, Maxpolydegree):\n",
|
||
" polynomial[polydegree] = polydegree\n",
|
||
" for degree in range(polydegree):\n",
|
||
" X[:,degree] = Density**(degree/3.0)\n",
|
||
"\n",
|
||
"# loop over trials in order to estimate the expectation value of the MSE\n",
|
||
" testerror[polydegree] = 0.0\n",
|
||
" trainingerror[polydegree] = 0.0\n",
|
||
" for samples in range(trials):\n",
|
||
" x_train, x_test, y_train, y_test = train_test_split(X, Energies, test_size=0.2)\n",
|
||
" model = LinearRegression(fit_intercept=False).fit(x_train, y_train)\n",
|
||
" ypred = model.predict(x_train)\n",
|
||
" ytilde = model.predict(x_test)\n",
|
||
" testerror[polydegree] += mean_squared_error(y_test, ytilde)\n",
|
||
" trainingerror[polydegree] += mean_squared_error(y_train, ypred) \n",
|
||
"\n",
|
||
" testerror[polydegree] /= trials\n",
|
||
" trainingerror[polydegree] /= trials\n",
|
||
" print(\"Degree of polynomial: %3d\"% polynomial[polydegree])\n",
|
||
" print(\"Mean squared error on training data: %.8f\" % trainingerror[polydegree])\n",
|
||
" print(\"Mean squared error on test data: %.8f\" % testerror[polydegree])\n",
|
||
"\n",
|
||
"plt.plot(polynomial, np.log10(trainingerror), label='Training Error')\n",
|
||
"plt.plot(polynomial, np.log10(testerror), label='Test Error')\n",
|
||
"plt.xlabel('Polynomial degree')\n",
|
||
"plt.ylabel('log10[MSE]')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "53dc97b8",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"Note that we kept the intercept column in the fitting here. This means that we need to set the **intercept** in the call to the **Scikit-Learn** function as **False**. Alternatively, we could have set up the design matrix $X$ without the first column of ones."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "660084ab",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## The same example but now with cross-validation\n",
|
||
"\n",
|
||
"In this example we keep the intercept column again but add cross-validation in order to estimate the best possible value of the means squared error."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 5,
|
||
"id": "5dd5aec2",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Common imports\n",
|
||
"import os\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
|
||
"from sklearn.metrics import mean_squared_error\n",
|
||
"from sklearn.model_selection import KFold\n",
|
||
"from sklearn.model_selection import cross_val_score\n",
|
||
"\n",
|
||
"\n",
|
||
"# Where to save the figures and data files\n",
|
||
"PROJECT_ROOT_DIR = \"Results\"\n",
|
||
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
||
"DATA_ID = \"DataFiles/\"\n",
|
||
"\n",
|
||
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
||
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
||
"\n",
|
||
"if not os.path.exists(FIGURE_ID):\n",
|
||
" os.makedirs(FIGURE_ID)\n",
|
||
"\n",
|
||
"if not os.path.exists(DATA_ID):\n",
|
||
" os.makedirs(DATA_ID)\n",
|
||
"\n",
|
||
"def image_path(fig_id):\n",
|
||
" return os.path.join(FIGURE_ID, fig_id)\n",
|
||
"\n",
|
||
"def data_path(dat_id):\n",
|
||
" return os.path.join(DATA_ID, dat_id)\n",
|
||
"\n",
|
||
"def save_fig(fig_id):\n",
|
||
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
||
"\n",
|
||
"infile = open(data_path(\"EoS.csv\"),'r')\n",
|
||
"\n",
|
||
"# Read the EoS data as csv file and organize the data into two arrays with density and energies\n",
|
||
"EoS = pd.read_csv(infile, names=('Density', 'Energy'))\n",
|
||
"EoS['Energy'] = pd.to_numeric(EoS['Energy'], errors='coerce')\n",
|
||
"EoS = EoS.dropna()\n",
|
||
"Energies = EoS['Energy']\n",
|
||
"Density = EoS['Density']\n",
|
||
"# The design matrix now as function of various polytrops\n",
|
||
"\n",
|
||
"Maxpolydegree = 30\n",
|
||
"X = np.zeros((len(Density),Maxpolydegree))\n",
|
||
"X[:,0] = 1.0\n",
|
||
"estimated_mse_sklearn = np.zeros(Maxpolydegree)\n",
|
||
"polynomial = np.zeros(Maxpolydegree)\n",
|
||
"k =5\n",
|
||
"kfold = KFold(n_splits = k)\n",
|
||
"\n",
|
||
"for polydegree in range(1, Maxpolydegree):\n",
|
||
" polynomial[polydegree] = polydegree\n",
|
||
" for degree in range(polydegree):\n",
|
||
" X[:,degree] = Density**(degree/3.0)\n",
|
||
" OLS = LinearRegression(fit_intercept=False)\n",
|
||
"# loop over trials in order to estimate the expectation value of the MSE\n",
|
||
" estimated_mse_folds = cross_val_score(OLS, X, Energies, scoring='neg_mean_squared_error', cv=kfold)\n",
|
||
"#[:, np.newaxis]\n",
|
||
" estimated_mse_sklearn[polydegree] = np.mean(-estimated_mse_folds)\n",
|
||
"\n",
|
||
"plt.plot(polynomial, np.log10(estimated_mse_sklearn), label='Test Error')\n",
|
||
"plt.xlabel('Polynomial degree')\n",
|
||
"plt.ylabel('log10[MSE]')\n",
|
||
"plt.legend()\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2c1f6d4b",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Logistic Regression\n",
|
||
"\n",
|
||
"In linear regression our main interest was centered on learning the\n",
|
||
"coefficients of a functional fit (say a polynomial) in order to be\n",
|
||
"able to predict the response of a continuous variable on some unseen\n",
|
||
"data. The fit to the continuous variable $y_i$ is based on some\n",
|
||
"independent variables $\\boldsymbol{x}_i$. Linear regression resulted in\n",
|
||
"analytical expressions for standard ordinary Least Squares or Ridge\n",
|
||
"regression (in terms of matrices to invert) for several quantities,\n",
|
||
"ranging from the variance and thereby the confidence intervals of the\n",
|
||
"parameters $\\boldsymbol{\\theta}$ to the mean squared error. If we can invert\n",
|
||
"the product of the design matrices, linear regression gives then a\n",
|
||
"simple recipe for fitting our data."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "149e92ec",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Classification problems\n",
|
||
"\n",
|
||
"Classification problems, however, are concerned with outcomes taking\n",
|
||
"the form of discrete variables (i.e. categories). We may for example,\n",
|
||
"on the basis of DNA sequencing for a number of patients, like to find\n",
|
||
"out which mutations are important for a certain disease; or based on\n",
|
||
"scans of various patients' brains, figure out if there is a tumor or\n",
|
||
"not; or given a specific physical system, we'd like to identify its\n",
|
||
"state, say whether it is an ordered or disordered system (typical\n",
|
||
"situation in solid state physics); or classify the status of a\n",
|
||
"patient, whether she/he has a stroke or not and many other similar\n",
|
||
"situations.\n",
|
||
"\n",
|
||
"The most common situation we encounter when we apply logistic\n",
|
||
"regression is that of two possible outcomes, normally denoted as a\n",
|
||
"binary outcome, true or false, positive or negative, success or\n",
|
||
"failure etc."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "ce85cd3a",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Optimization and Deep learning\n",
|
||
"\n",
|
||
"Logistic regression will also serve as our stepping stone towards\n",
|
||
"neural network algorithms and supervised deep learning. For logistic\n",
|
||
"learning, the minimization of the cost function leads to a non-linear\n",
|
||
"equation in the parameters $\\boldsymbol{\\theta}$. The optimization of the\n",
|
||
"problem calls therefore for minimization algorithms. This forms the\n",
|
||
"bottle neck of all machine learning algorithms, namely how to find\n",
|
||
"reliable minima of a multi-variable function. This leads us to the\n",
|
||
"family of gradient descent methods. The latter are the working horses\n",
|
||
"of basically all modern machine learning algorithms.\n",
|
||
"\n",
|
||
"We note also that many of the topics discussed here on logistic \n",
|
||
"regression are also commonly used in modern supervised Deep Learning\n",
|
||
"models, as we will see later."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2eb9e687",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Basics\n",
|
||
"\n",
|
||
"We consider the case where the outputs/targets, also called the\n",
|
||
"responses or the outcomes, $y_i$ are discrete and only take values\n",
|
||
"from $k=0,\\dots,K-1$ (i.e. $K$ classes).\n",
|
||
"\n",
|
||
"The goal is to predict the\n",
|
||
"output classes from the design matrix $\\boldsymbol{X}\\in\\mathbb{R}^{n\\times p}$\n",
|
||
"made of $n$ samples, each of which carries $p$ features or predictors. The\n",
|
||
"primary goal is to identify the classes to which new unseen samples\n",
|
||
"belong.\n",
|
||
"\n",
|
||
"Let us specialize to the case of two classes only, with outputs\n",
|
||
"$y_i=0$ and $y_i=1$. Our outcomes could represent the status of a\n",
|
||
"credit card user that could default or not on her/his credit card\n",
|
||
"debt. That is"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "9b8b7d05",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"y_i = \\begin{bmatrix} 0 & \\mathrm{no}\\\\ 1 & \\mathrm{yes} \\end{bmatrix}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "7db50d1a",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Linear classifier\n",
|
||
"\n",
|
||
"Before moving to the logistic model, let us try to use our linear\n",
|
||
"regression model to classify these two outcomes. We could for example\n",
|
||
"fit a linear model to the default case if $y_i > 0.5$ and the no\n",
|
||
"default case $y_i \\leq 0.5$.\n",
|
||
"\n",
|
||
"We would then have our \n",
|
||
"weighted linear combination, namely"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a78fc346",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"<!-- Equation labels as ordinary links -->\n",
|
||
"<div id=\"_auto1\"></div>\n",
|
||
"\n",
|
||
"$$\n",
|
||
"\\begin{equation}\n",
|
||
"\\boldsymbol{y} = \\boldsymbol{X}^T\\boldsymbol{\\theta} + \\boldsymbol{\\epsilon},\n",
|
||
"\\label{_auto1} \\tag{1}\n",
|
||
"\\end{equation}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "661d8faf",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"where $\\boldsymbol{y}$ is a vector representing the possible outcomes, $\\boldsymbol{X}$ is our\n",
|
||
"$n\\times p$ design matrix and $\\boldsymbol{\\theta}$ represents our estimators/predictors."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8620ba1b",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Some selected properties\n",
|
||
"\n",
|
||
"The main problem with our function is that it takes values on the\n",
|
||
"entire real axis. In the case of logistic regression, however, the\n",
|
||
"labels $y_i$ are discrete variables. A typical example is the credit\n",
|
||
"card data discussed below here, where we can set the state of\n",
|
||
"defaulting the debt to $y_i=1$ and not to $y_i=0$ for one the persons\n",
|
||
"in the data set (see the full example below).\n",
|
||
"\n",
|
||
"One simple way to get a discrete output is to have sign\n",
|
||
"functions that map the output of a linear regressor to values $\\{0,1\\}$,\n",
|
||
"$f(s_i)=sign(s_i)=1$ if $s_i\\ge 0$ and 0 if otherwise. \n",
|
||
"We will encounter this model in our first demonstration of neural networks.\n",
|
||
"\n",
|
||
"Historically it is called the **perceptron** model in the machine learning\n",
|
||
"literature. This model is extremely simple. However, in many cases it is more\n",
|
||
"favorable to use a ``soft\" classifier that outputs\n",
|
||
"the probability of a given category. This leads us to the logistic function."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8fdbebd2",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Simple example\n",
|
||
"\n",
|
||
"The following example on data for coronary heart disease (CHD) as function of age may serve as an illustration. In the code here we read and plot whether a person has had CHD (output = 1) or not (output = 0). This ouput is plotted the person's against age. Clearly, the figure shows that attempting to make a standard linear regression fit may not be very meaningful."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 6,
|
||
"id": "8dc64aeb",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Common imports\n",
|
||
"import os\n",
|
||
"import numpy as np\n",
|
||
"import pandas as pd\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"from sklearn.linear_model import LinearRegression, Ridge, Lasso\n",
|
||
"from sklearn.model_selection import train_test_split\n",
|
||
"from sklearn.utils import resample\n",
|
||
"from sklearn.metrics import mean_squared_error\n",
|
||
"from IPython.display import display\n",
|
||
"from pylab import plt, mpl\n",
|
||
"mpl.rcParams['font.family'] = 'serif'\n",
|
||
"\n",
|
||
"# Where to save the figures and data files\n",
|
||
"PROJECT_ROOT_DIR = \"Results\"\n",
|
||
"FIGURE_ID = \"Results/FigureFiles\"\n",
|
||
"DATA_ID = \"DataFiles/\"\n",
|
||
"\n",
|
||
"if not os.path.exists(PROJECT_ROOT_DIR):\n",
|
||
" os.mkdir(PROJECT_ROOT_DIR)\n",
|
||
"\n",
|
||
"if not os.path.exists(FIGURE_ID):\n",
|
||
" os.makedirs(FIGURE_ID)\n",
|
||
"\n",
|
||
"if not os.path.exists(DATA_ID):\n",
|
||
" os.makedirs(DATA_ID)\n",
|
||
"\n",
|
||
"def image_path(fig_id):\n",
|
||
" return os.path.join(FIGURE_ID, fig_id)\n",
|
||
"\n",
|
||
"def data_path(dat_id):\n",
|
||
" return os.path.join(DATA_ID, dat_id)\n",
|
||
"\n",
|
||
"def save_fig(fig_id):\n",
|
||
" plt.savefig(image_path(fig_id) + \".png\", format='png')\n",
|
||
"\n",
|
||
"infile = open(data_path(\"chddata.csv\"),'r')\n",
|
||
"\n",
|
||
"# Read the chd data as csv file and organize the data into arrays with age group, age, and chd\n",
|
||
"chd = pd.read_csv(infile, names=('ID', 'Age', 'Agegroup', 'CHD'))\n",
|
||
"chd.columns = ['ID', 'Age', 'Agegroup', 'CHD']\n",
|
||
"output = chd['CHD']\n",
|
||
"age = chd['Age']\n",
|
||
"agegroup = chd['Agegroup']\n",
|
||
"numberID = chd['ID'] \n",
|
||
"display(chd)\n",
|
||
"\n",
|
||
"plt.scatter(age, output, marker='o')\n",
|
||
"plt.axis([18,70.0,-0.1, 1.2])\n",
|
||
"plt.xlabel(r'Age')\n",
|
||
"plt.ylabel(r'CHD')\n",
|
||
"plt.title(r'Age distribution and Coronary heart disease')\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "40385068",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Plotting the mean value for each group\n",
|
||
"\n",
|
||
"What we could attempt however is to plot the mean value for each group."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 7,
|
||
"id": "a473659b",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"agegroupmean = np.array([0.1, 0.133, 0.250, 0.333, 0.462, 0.625, 0.765, 0.800])\n",
|
||
"group = np.array([1, 2, 3, 4, 5, 6, 7, 8])\n",
|
||
"plt.plot(group, agegroupmean, \"r-\")\n",
|
||
"plt.axis([0,9,0, 1.0])\n",
|
||
"plt.xlabel(r'Age group')\n",
|
||
"plt.ylabel(r'CHD mean values')\n",
|
||
"plt.title(r'Mean values for each age group')\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3e2ab512",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"We are now trying to find a function $f(y\\vert x)$, that is a function which gives us an expected value for the output $y$ with a given input $x$.\n",
|
||
"In standard linear regression with a linear dependence on $x$, we would write this in terms of our model"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "40361f1b",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"f(y_i\\vert x_i)=\\theta_0+\\theta_1 x_i.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a1b379fb",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"This expression implies however that $f(y_i\\vert x_i)$ could take any\n",
|
||
"value from minus infinity to plus infinity. If we however let\n",
|
||
"$f(y\\vert y)$ be represented by the mean value, the above example\n",
|
||
"shows us that we can constrain the function to take values between\n",
|
||
"zero and one, that is we have $0 \\le f(y_i\\vert x_i) \\le 1$. Looking\n",
|
||
"at our last curve we see also that it has an S-shaped form. This leads\n",
|
||
"us to a very popular model for the function $f$, namely the so-called\n",
|
||
"Sigmoid function or logistic model. We will consider this function as\n",
|
||
"representing the probability for finding a value of $y_i$ with a given\n",
|
||
"$x_i$."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "bcbf3d2b",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## The logistic function\n",
|
||
"\n",
|
||
"Another widely studied model, is the so-called \n",
|
||
"perceptron model, which is an example of a \"hard classification\" model. We\n",
|
||
"will encounter this model when we discuss neural networks as\n",
|
||
"well. Each datapoint is deterministically assigned to a category (i.e\n",
|
||
"$y_i=0$ or $y_i=1$). In many cases, and the coronary heart disease data forms one of many such examples, it is favorable to have a \"soft\"\n",
|
||
"classifier that outputs the probability of a given category rather\n",
|
||
"than a single value. For example, given $x_i$, the classifier\n",
|
||
"outputs the probability of being in a category $k$. Logistic regression\n",
|
||
"is the most common example of a so-called soft classifier. In logistic\n",
|
||
"regression, the probability that a data point $x_i$\n",
|
||
"belongs to a category $y_i=\\{0,1\\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event,"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "38918f44",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"p(t) = \\frac{1}{1+\\mathrm \\exp{-t}}=\\frac{\\exp{t}}{1+\\mathrm \\exp{t}}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "fd225d0f",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"Note that $1-p(t)= p(-t)$."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d340b5c1",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Examples of likelihood functions used in logistic regression and nueral networks\n",
|
||
"\n",
|
||
"The following code plots the logistic function, the step function and other functions we will encounter from here and on."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 8,
|
||
"id": "357d6f03",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"\"\"\"The sigmoid function (or the logistic curve) is a\n",
|
||
"function that takes any real number, z, and outputs a number (0,1).\n",
|
||
"It is useful in neural networks for assigning weights on a relative scale.\n",
|
||
"The value z is the weighted sum of parameters involved in the learning algorithm.\"\"\"\n",
|
||
"\n",
|
||
"import numpy\n",
|
||
"import matplotlib.pyplot as plt\n",
|
||
"import math as mt\n",
|
||
"\n",
|
||
"z = numpy.arange(-5, 5, .1)\n",
|
||
"sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))\n",
|
||
"sigma = sigma_fn(z)\n",
|
||
"\n",
|
||
"fig = plt.figure()\n",
|
||
"ax = fig.add_subplot(111)\n",
|
||
"ax.plot(z, sigma)\n",
|
||
"ax.set_ylim([-0.1, 1.1])\n",
|
||
"ax.set_xlim([-5,5])\n",
|
||
"ax.grid(True)\n",
|
||
"ax.set_xlabel('z')\n",
|
||
"ax.set_title('sigmoid function')\n",
|
||
"\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"\"\"\"Step Function\"\"\"\n",
|
||
"z = numpy.arange(-5, 5, .02)\n",
|
||
"step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)\n",
|
||
"step = step_fn(z)\n",
|
||
"\n",
|
||
"fig = plt.figure()\n",
|
||
"ax = fig.add_subplot(111)\n",
|
||
"ax.plot(z, step)\n",
|
||
"ax.set_ylim([-0.5, 1.5])\n",
|
||
"ax.set_xlim([-5,5])\n",
|
||
"ax.grid(True)\n",
|
||
"ax.set_xlabel('z')\n",
|
||
"ax.set_title('step function')\n",
|
||
"\n",
|
||
"plt.show()\n",
|
||
"\n",
|
||
"\"\"\"tanh Function\"\"\"\n",
|
||
"z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)\n",
|
||
"t = numpy.tanh(z)\n",
|
||
"\n",
|
||
"fig = plt.figure()\n",
|
||
"ax = fig.add_subplot(111)\n",
|
||
"ax.plot(z, t)\n",
|
||
"ax.set_ylim([-1.0, 1.0])\n",
|
||
"ax.set_xlim([-2*mt.pi,2*mt.pi])\n",
|
||
"ax.grid(True)\n",
|
||
"ax.set_xlabel('z')\n",
|
||
"ax.set_title('tanh function')\n",
|
||
"\n",
|
||
"plt.show()"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8be63821",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Two parameters\n",
|
||
"\n",
|
||
"We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\\theta$ in our fitting of the Sigmoid function, that is we define probabilities"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f79d930e",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\begin{align*}\n",
|
||
"p(y_i=1|x_i,\\boldsymbol{\\theta}) &= \\frac{\\exp{(\\theta_0+\\theta_1x_i)}}{1+\\exp{(\\theta_0+\\theta_1x_i)}},\\nonumber\\\\\n",
|
||
"p(y_i=0|x_i,\\boldsymbol{\\theta}) &= 1 - p(y_i=1|x_i,\\boldsymbol{\\theta}),\n",
|
||
"\\end{align*}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "8a758aae",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"where $\\boldsymbol{\\theta}$ are the weights we wish to extract from data, in our case $\\theta_0$ and $\\theta_1$. \n",
|
||
"\n",
|
||
"Note that we used"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "88159170",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"p(y_i=0\\vert x_i, \\boldsymbol{\\theta}) = 1-p(y_i=1\\vert x_i, \\boldsymbol{\\theta}).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f9972402",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Maximum likelihood\n",
|
||
"\n",
|
||
"In order to define the total likelihood for all possible outcomes from a \n",
|
||
"dataset $\\mathcal{D}=\\{(y_i,x_i)\\}$, with the binary labels\n",
|
||
"$y_i\\in\\{0,1\\}$ and where the data points are drawn independently, we use the so-called [Maximum Likelihood Estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) (MLE) principle. \n",
|
||
"We aim thus at maximizing \n",
|
||
"the probability of seeing the observed data. We can then approximate the \n",
|
||
"likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "949524d2",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\begin{align*}\n",
|
||
"P(\\mathcal{D}|\\boldsymbol{\\theta})& = \\prod_{i=1}^n \\left[p(y_i=1|x_i,\\boldsymbol{\\theta})\\right]^{y_i}\\left[1-p(y_i=1|x_i,\\boldsymbol{\\theta}))\\right]^{1-y_i}\\nonumber \\\\\n",
|
||
"\\end{align*}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d9a7fded",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"from which we obtain the log-likelihood and our **cost/loss** function"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4c5f78fb",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathcal{C}(\\boldsymbol{\\theta}) = \\sum_{i=1}^n \\left( y_i\\log{p(y_i=1|x_i,\\boldsymbol{\\theta})} + (1-y_i)\\log\\left[1-p(y_i=1|x_i,\\boldsymbol{\\theta}))\\right]\\right).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "5ccce506",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## The cost function rewritten\n",
|
||
"\n",
|
||
"Reordering the logarithms, we can rewrite the **cost/loss** function as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "bf58bb76",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathcal{C}(\\boldsymbol{\\theta}) = \\sum_{i=1}^n \\left(y_i(\\theta_0+\\theta_1x_i) -\\log{(1+\\exp{(\\theta_0+\\theta_1x_i)})}\\right).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "41543ca6",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\\theta$.\n",
|
||
"Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e664b57a",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\mathcal{C}(\\boldsymbol{\\theta})=-\\sum_{i=1}^n \\left(y_i(\\theta_0+\\theta_1x_i) -\\log{(1+\\exp{(\\theta_0+\\theta_1x_i)})}\\right).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "eb357503",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"This equation is known in statistics as the **cross entropy**. Finally, we note that just as in linear regression, \n",
|
||
"in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e388ad02",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Minimizing the cross entropy\n",
|
||
"\n",
|
||
"The cross entropy is a convex function of the weights $\\boldsymbol{\\theta}$ and,\n",
|
||
"therefore, any local minimizer is a global minimizer. \n",
|
||
"\n",
|
||
"Minimizing this\n",
|
||
"cost function with respect to the two parameters $\\theta_0$ and $\\theta_1$ we obtain"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1d4f2850",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\theta})}{\\partial \\theta_0} = -\\sum_{i=1}^n \\left(y_i -\\frac{\\exp{(\\theta_0+\\theta_1x_i)}}{1+\\exp{(\\theta_0+\\theta_1x_i)}}\\right),\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "68a0c133",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"and"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c942a72b",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\theta})}{\\partial \\theta_1} = -\\sum_{i=1}^n \\left(y_ix_i -x_i\\frac{\\exp{(\\theta_0+\\theta_1x_i)}}{1+\\exp{(\\theta_0+\\theta_1x_i)}}\\right).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "42caf6db",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## A more compact expression\n",
|
||
"\n",
|
||
"Let us now define a vector $\\boldsymbol{y}$ with $n$ elements $y_i$, an\n",
|
||
"$n\\times p$ matrix $\\boldsymbol{X}$ which contains the $x_i$ values and a\n",
|
||
"vector $\\boldsymbol{p}$ of fitted probabilities $p(y_i\\vert x_i,\\boldsymbol{\\theta})$. We can rewrite in a more compact form the first\n",
|
||
"derivative of the cost function as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "22cd94c9",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\theta})}{\\partial \\boldsymbol{\\theta}} = -\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{p}\\right).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d9428067",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"If we in addition define a diagonal matrix $\\boldsymbol{W}$ with elements \n",
|
||
"$p(y_i\\vert x_i,\\boldsymbol{\\theta})(1-p(y_i\\vert x_i,\\boldsymbol{\\theta})$, we can obtain a compact expression of the second derivative as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "29178d5a",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\theta})}{\\partial \\boldsymbol{\\theta}\\partial \\boldsymbol{\\theta}^T} = \\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "6b7671ad",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Extending to more predictors\n",
|
||
"\n",
|
||
"Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "500b6574",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\log{ \\frac{p(\\boldsymbol{\\theta}\\boldsymbol{x})}{1-p(\\boldsymbol{\\theta}\\boldsymbol{x})}} = \\theta_0+\\theta_1x_1+\\theta_2x_2+\\dots+\\theta_px_p.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "cf0b50ce",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"Here we defined $\\boldsymbol{x}=[1,x_1,x_2,\\dots,x_p]$ and $\\boldsymbol{\\theta}=[\\theta_0, \\theta_1, \\dots, \\theta_p]$ leading to"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "537486ee",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"p(\\boldsymbol{\\theta}\\boldsymbol{x})=\\frac{ \\exp{(\\theta_0+\\theta_1x_1+\\theta_2x_2+\\dots+\\theta_px_p)}}{1+\\exp{(\\theta_0+\\theta_1x_1+\\theta_2x_2+\\dots+\\theta_px_p)}}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "534fb571",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Including more classes\n",
|
||
"\n",
|
||
"Till now we have mainly focused on two classes, the so-called binary\n",
|
||
"system. Suppose we wish to extend to $K$ classes. Let us for the sake\n",
|
||
"of simplicity assume we have only two predictors. We have then following model"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "fa7ca275",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\log{\\frac{p(C=1\\vert x)}{p(K\\vert x)}} = \\theta_{10}+\\theta_{11}x_1,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "cc765c0e",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"and"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2c43387d",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\log{\\frac{p(C=2\\vert x)}{p(K\\vert x)}} = \\theta_{20}+\\theta_{21}x_1,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e063f183",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"and so on till the class $C=K-1$ class"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "060fa00c",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\log{\\frac{p(C=K-1\\vert x)}{p(K\\vert x)}} = \\theta_{(K-1)0}+\\theta_{(K-1)1}x_1,\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b9034492",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"and the model is specified in term of $K-1$ so-called log-odds or\n",
|
||
"**logit** transformations."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b7fba1fc",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## More classes\n",
|
||
"\n",
|
||
"In our discussion of neural networks we will encounter the above again\n",
|
||
"in terms of a slightly modified function, the so-called **Softmax** function.\n",
|
||
"\n",
|
||
"The softmax function is used in various multiclass classification\n",
|
||
"methods, such as multinomial logistic regression (also known as\n",
|
||
"softmax regression), multiclass linear discriminant analysis, naive\n",
|
||
"Bayes classifiers, and artificial neural networks. Specifically, in\n",
|
||
"multinomial logistic regression and linear discriminant analysis, the\n",
|
||
"input to the function is the result of $K$ distinct linear functions,\n",
|
||
"and the predicted probability for the $k$-th class given a sample\n",
|
||
"vector $\\boldsymbol{x}$ and a weighting vector $\\boldsymbol{\\theta}$ is (with two\n",
|
||
"predictors):"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "a8346f86",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"p(C=k\\vert \\mathbf {x} )=\\frac{\\exp{(\\theta_{k0}+\\theta_{k1}x_1)}}{1+\\sum_{l=1}^{K-1}\\exp{(\\theta_{l0}+\\theta_{l1}x_1)}}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b05e18eb",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"It is easy to extend to more predictors. The final class is"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3bff89b1",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"p(C=K\\vert \\mathbf {x} )=\\frac{1}{1+\\sum_{l=1}^{K-1}\\exp{(\\theta_{l0}+\\theta_{l1}x_1)}},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "e89e832c",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"and they sum to one. Our earlier discussions were all specialized to\n",
|
||
"the case with two classes only. It is easy to see from the above that\n",
|
||
"what we derived earlier is compatible with these equations.\n",
|
||
"\n",
|
||
"To find the optimal parameters we would typically use a gradient\n",
|
||
"descent method. Newton's method and gradient descent methods are\n",
|
||
"discussed in the material on [optimization\n",
|
||
"methods](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html)."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "464d4933",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Optimization, the central part of any Machine Learning algortithm\n",
|
||
"\n",
|
||
"Almost every problem in machine learning and data science starts with\n",
|
||
"a dataset $X$, a model $g(\\theta)$, which is a function of the\n",
|
||
"parameters $\\theta$ and a cost function $C(X, g(\\theta))$ that allows\n",
|
||
"us to judge how well the model $g(\\theta)$ explains the observations\n",
|
||
"$X$. The model is fit by finding the values of $\\theta$ that minimize\n",
|
||
"the cost function. Ideally we would be able to solve for $\\theta$\n",
|
||
"analytically, however this is not possible in general and we must use\n",
|
||
"some approximative/numerical method to compute the minimum."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "c707d4a0",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Revisiting our Logistic Regression case\n",
|
||
"\n",
|
||
"In our discussion on Logistic Regression we studied the \n",
|
||
"case of\n",
|
||
"two classes, with $y_i$ either\n",
|
||
"$0$ or $1$. Furthermore we assumed also that we have only two\n",
|
||
"parameters $\\theta$ in our fitting, that is we\n",
|
||
"defined probabilities"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "3f00d244",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\begin{align*}\n",
|
||
"p(y_i=1|x_i,\\boldsymbol{\\theta}) &= \\frac{\\exp{(\\theta_0+\\theta_1x_i)}}{1+\\exp{(\\theta_0+\\theta_1x_i)}},\\nonumber\\\\\n",
|
||
"p(y_i=0|x_i,\\boldsymbol{\\theta}) &= 1 - p(y_i=1|x_i,\\boldsymbol{\\theta}),\n",
|
||
"\\end{align*}\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "2d239661",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"where $\\boldsymbol{\\theta}$ are the weights we wish to extract from data, in our case $\\theta_0$ and $\\theta_1$."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "4243778f",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## The equations to solve\n",
|
||
"\n",
|
||
"Our compact equations used a definition of a vector $\\boldsymbol{y}$ with $n$\n",
|
||
"elements $y_i$, an $n\\times p$ matrix $\\boldsymbol{X}$ which contains the\n",
|
||
"$x_i$ values and a vector $\\boldsymbol{p}$ of fitted probabilities\n",
|
||
"$p(y_i\\vert x_i,\\boldsymbol{\\theta})$. We rewrote in a more compact form\n",
|
||
"the first derivative of the cost function as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "21ce04bb",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\theta})}{\\partial \\boldsymbol{\\theta}} = -\\boldsymbol{X}^T\\left(\\boldsymbol{y}-\\boldsymbol{p}\\right).\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "b854153c",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"If we in addition define a diagonal matrix $\\boldsymbol{W}$ with elements \n",
|
||
"$p(y_i\\vert x_i,\\boldsymbol{\\theta})(1-p(y_i\\vert x_i,\\boldsymbol{\\theta})$, we can obtain a compact expression of the second derivative as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "235c9b1d",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\theta})}{\\partial \\boldsymbol{\\theta}\\partial \\boldsymbol{\\theta}^T} = \\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1651fe82",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"This defines what is called the Hessian matrix."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f36a8c94",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Solving using Newton-Raphson's method\n",
|
||
"\n",
|
||
"If we can set up these equations, Newton-Raphson's iterative method is normally the method of choice. It requires however that we can compute in an efficient way the matrices that define the first and second derivatives. \n",
|
||
"\n",
|
||
"Our iterative scheme is then given by"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "438b5efe",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{\\theta}^{\\mathrm{new}} = \\boldsymbol{\\theta}^{\\mathrm{old}}-\\left(\\frac{\\partial^2 \\mathcal{C}(\\boldsymbol{\\theta})}{\\partial \\boldsymbol{\\theta}\\partial \\boldsymbol{\\theta}^T}\\right)^{-1}_{\\boldsymbol{\\theta}^{\\mathrm{old}}}\\times \\left(\\frac{\\partial \\mathcal{C}(\\boldsymbol{\\theta})}{\\partial \\boldsymbol{\\theta}}\\right)_{\\boldsymbol{\\theta}^{\\mathrm{old}}},\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "f3ae8207",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"or in matrix form as"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "702a38c4",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"$$\n",
|
||
"\\boldsymbol{\\theta}^{\\mathrm{new}} = \\boldsymbol{\\theta}^{\\mathrm{old}}-\\left(\\boldsymbol{X}^T\\boldsymbol{W}\\boldsymbol{X} \\right)^{-1}\\times \\left(-\\boldsymbol{X}^T(\\boldsymbol{y}-\\boldsymbol{p}) \\right)_{\\boldsymbol{\\theta}^{\\mathrm{old}}}.\n",
|
||
"$$"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "43b5a9ab",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"The right-hand side is computed with the old values of $\\theta$. \n",
|
||
"\n",
|
||
"If we can compute these matrices, in particular the Hessian, the above is often the easiest method to implement."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "5b579d10",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"## Example code for Logistic Regression\n",
|
||
"\n",
|
||
"Here we make a class for Logistic regression. The code uses a simple data set and includes both a binary case and a multiclass case."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 9,
|
||
"id": "a59b8c77",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"\n",
|
||
"class LogisticRegression:\n",
|
||
" \"\"\"\n",
|
||
" Logistic Regression for binary and multiclass classification.\n",
|
||
" \"\"\"\n",
|
||
" def __init__(self, lr=0.01, epochs=1000, fit_intercept=True, verbose=False):\n",
|
||
" self.lr = lr # Learning rate for gradient descent\n",
|
||
" self.epochs = epochs # Number of iterations\n",
|
||
" self.fit_intercept = fit_intercept # Whether to add intercept (bias)\n",
|
||
" self.verbose = verbose # Print loss during training if True\n",
|
||
" self.weights = None\n",
|
||
" self.multi_class = False # Will be determined at fit time\n",
|
||
"\n",
|
||
" def _add_intercept(self, X):\n",
|
||
" \"\"\"Add intercept term (column of ones) to feature matrix.\"\"\"\n",
|
||
" intercept = np.ones((X.shape[0], 1))\n",
|
||
" return np.concatenate((intercept, X), axis=1)\n",
|
||
"\n",
|
||
" def _sigmoid(self, z):\n",
|
||
" \"\"\"Sigmoid function for binary logistic.\"\"\"\n",
|
||
" return 1 / (1 + np.exp(-z))\n",
|
||
"\n",
|
||
" def _softmax(self, Z):\n",
|
||
" \"\"\"Softmax function for multiclass logistic.\"\"\"\n",
|
||
" exp_Z = np.exp(Z - np.max(Z, axis=1, keepdims=True))\n",
|
||
" return exp_Z / np.sum(exp_Z, axis=1, keepdims=True)\n",
|
||
"\n",
|
||
" def fit(self, X, y):\n",
|
||
" \"\"\"\n",
|
||
" Train the logistic regression model using gradient descent.\n",
|
||
" Supports binary (sigmoid) and multiclass (softmax) based on y.\n",
|
||
" \"\"\"\n",
|
||
" X = np.array(X)\n",
|
||
" y = np.array(y)\n",
|
||
" n_samples, n_features = X.shape\n",
|
||
"\n",
|
||
" # Add intercept if needed\n",
|
||
" if self.fit_intercept:\n",
|
||
" X = self._add_intercept(X)\n",
|
||
" n_features += 1\n",
|
||
"\n",
|
||
" # Determine classes and mode (binary vs multiclass)\n",
|
||
" unique_classes = np.unique(y)\n",
|
||
" if len(unique_classes) > 2:\n",
|
||
" self.multi_class = True\n",
|
||
" else:\n",
|
||
" self.multi_class = False\n",
|
||
"\n",
|
||
" # ----- Multiclass case -----\n",
|
||
" if self.multi_class:\n",
|
||
" n_classes = len(unique_classes)\n",
|
||
" # Map original labels to 0...n_classes-1\n",
|
||
" class_to_index = {c: idx for idx, c in enumerate(unique_classes)}\n",
|
||
" y_indices = np.array([class_to_index[c] for c in y])\n",
|
||
" # Initialize weight matrix (features x classes)\n",
|
||
" self.weights = np.zeros((n_features, n_classes))\n",
|
||
"\n",
|
||
" # One-hot encode y\n",
|
||
" Y_onehot = np.zeros((n_samples, n_classes))\n",
|
||
" Y_onehot[np.arange(n_samples), y_indices] = 1\n",
|
||
"\n",
|
||
" # Gradient descent\n",
|
||
" for epoch in range(self.epochs):\n",
|
||
" scores = X.dot(self.weights) # Linear scores (n_samples x n_classes)\n",
|
||
" probs = self._softmax(scores) # Probabilities (n_samples x n_classes)\n",
|
||
" # Compute gradient (features x classes)\n",
|
||
" gradient = (1 / n_samples) * X.T.dot(probs - Y_onehot)\n",
|
||
" # Update weights\n",
|
||
" self.weights -= self.lr * gradient\n",
|
||
"\n",
|
||
" if self.verbose and epoch % 100 == 0:\n",
|
||
" # Compute current loss (categorical cross-entropy)\n",
|
||
" loss = -np.sum(Y_onehot * np.log(probs + 1e-15)) / n_samples\n",
|
||
" print(f\"[Epoch {epoch}] Multiclass loss: {loss:.4f}\")\n",
|
||
"\n",
|
||
" # ----- Binary case -----\n",
|
||
" else:\n",
|
||
" # Convert y to 0/1 if not already\n",
|
||
" if not np.array_equal(unique_classes, [0, 1]):\n",
|
||
" # Map the two classes to 0 and 1\n",
|
||
" class0, class1 = unique_classes\n",
|
||
" y_binary = np.where(y == class1, 1, 0)\n",
|
||
" else:\n",
|
||
" y_binary = y.copy().astype(int)\n",
|
||
"\n",
|
||
" # Initialize weights vector (features,)\n",
|
||
" self.weights = np.zeros(n_features)\n",
|
||
"\n",
|
||
" # Gradient descent\n",
|
||
" for epoch in range(self.epochs):\n",
|
||
" linear_model = X.dot(self.weights) # (n_samples,)\n",
|
||
" probs = self._sigmoid(linear_model) # (n_samples,)\n",
|
||
" # Gradient for binary cross-entropy\n",
|
||
" gradient = (1 / n_samples) * X.T.dot(probs - y_binary)\n",
|
||
" self.weights -= self.lr * gradient\n",
|
||
"\n",
|
||
" if self.verbose and epoch % 100 == 0:\n",
|
||
" # Compute binary cross-entropy loss\n",
|
||
" loss = -np.mean(\n",
|
||
" y_binary * np.log(probs + 1e-15) + \n",
|
||
" (1 - y_binary) * np.log(1 - probs + 1e-15)\n",
|
||
" )\n",
|
||
" print(f\"[Epoch {epoch}] Binary loss: {loss:.4f}\")\n",
|
||
"\n",
|
||
" def predict_prob(self, X):\n",
|
||
" \"\"\"\n",
|
||
" Compute probability estimates. Returns a 1D array for binary or\n",
|
||
" a 2D array (n_samples x n_classes) for multiclass.\n",
|
||
" \"\"\"\n",
|
||
" X = np.array(X)\n",
|
||
" # Add intercept if the model used it\n",
|
||
" if self.fit_intercept:\n",
|
||
" X = self._add_intercept(X)\n",
|
||
" scores = X.dot(self.weights)\n",
|
||
" if self.multi_class:\n",
|
||
" return self._softmax(scores)\n",
|
||
" else:\n",
|
||
" return self._sigmoid(scores)\n",
|
||
"\n",
|
||
" def predict(self, X):\n",
|
||
" \"\"\"\n",
|
||
" Predict class labels for samples in X.\n",
|
||
" Returns integer class labels (0,1 for binary, or 0...C-1 for multiclass).\n",
|
||
" \"\"\"\n",
|
||
" probs = self.predict_prob(X)\n",
|
||
" if self.multi_class:\n",
|
||
" # Choose class with highest probability\n",
|
||
" return np.argmax(probs, axis=1)\n",
|
||
" else:\n",
|
||
" # Threshold at 0.5 for binary\n",
|
||
" return (probs >= 0.5).astype(int)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "d7401376",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"The class implements the sigmoid and softmax internally. During fit(),\n",
|
||
"we check the number of classes: if more than 2, we set\n",
|
||
"self.multi_class=True and perform multinomial logistic regression. We\n",
|
||
"one-hot encode the target vector and update a weight matrix with\n",
|
||
"softmax probabilities. Otherwise, we do standard binary logistic\n",
|
||
"regression, converting labels to 0/1 if needed and updating a weight\n",
|
||
"vector. In both cases we use batch gradient descent on the\n",
|
||
"cross-entropy loss (we add a small epsilon 1e-15 to logs for numerical\n",
|
||
"stability). Progress (loss) can be printed if verbose=True."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 10,
|
||
"id": "8609fd64",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"# Evaluation Metrics\n",
|
||
"#We define helper functions for accuracy and cross-entropy loss. Accuracy is the fraction of correct predictions . For loss, we compute the appropriate cross-entropy:\n",
|
||
"\n",
|
||
"def accuracy_score(y_true, y_pred):\n",
|
||
" \"\"\"Accuracy = (# correct predictions) / (total samples).\"\"\"\n",
|
||
" y_true = np.array(y_true)\n",
|
||
" y_pred = np.array(y_pred)\n",
|
||
" return np.mean(y_true == y_pred)\n",
|
||
"\n",
|
||
"def binary_cross_entropy(y_true, y_prob):\n",
|
||
" \"\"\"\n",
|
||
" Binary cross-entropy loss.\n",
|
||
" y_true: true binary labels (0 or 1), y_prob: predicted probabilities for class 1.\n",
|
||
" \"\"\"\n",
|
||
" y_true = np.array(y_true)\n",
|
||
" y_prob = np.clip(np.array(y_prob), 1e-15, 1-1e-15)\n",
|
||
" return -np.mean(y_true * np.log(y_prob) + (1 - y_true) * np.log(1 - y_prob))\n",
|
||
"\n",
|
||
"def categorical_cross_entropy(y_true, y_prob):\n",
|
||
" \"\"\"\n",
|
||
" Categorical cross-entropy loss for multiclass.\n",
|
||
" y_true: true labels (0...C-1), y_prob: array of predicted probabilities (n_samples x C).\n",
|
||
" \"\"\"\n",
|
||
" y_true = np.array(y_true, dtype=int)\n",
|
||
" y_prob = np.clip(np.array(y_prob), 1e-15, 1-1e-15)\n",
|
||
" # One-hot encode true labels\n",
|
||
" n_samples, n_classes = y_prob.shape\n",
|
||
" one_hot = np.zeros_like(y_prob)\n",
|
||
" one_hot[np.arange(n_samples), y_true] = 1\n",
|
||
" # Compute cross-entropy\n",
|
||
" loss_vec = -np.sum(one_hot * np.log(y_prob), axis=1)\n",
|
||
" return np.mean(loss_vec)"
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "markdown",
|
||
"id": "1879aba2",
|
||
"metadata": {
|
||
"editable": true
|
||
},
|
||
"source": [
|
||
"### Synthetic data generation\n",
|
||
"\n",
|
||
"Binary classification data: Create two Gaussian clusters in 2D. For example, class 0 around mean [-2,-2] and class 1 around [2,2].\n",
|
||
"Multiclass data: Create several Gaussian clusters (one per class) spread out in feature space."
|
||
]
|
||
},
|
||
{
|
||
"cell_type": "code",
|
||
"execution_count": 11,
|
||
"id": "6083d844",
|
||
"metadata": {
|
||
"collapsed": false,
|
||
"editable": true
|
||
},
|
||
"outputs": [],
|
||
"source": [
|
||
"import numpy as np\n",
|
||
"\n",
|
||
"def generate_binary_data(n_samples=100, n_features=2, random_state=None):\n",
|
||
" \"\"\"\n",
|
||
" Generate synthetic binary classification data.\n",
|
||
" Returns (X, y) where X is (n_samples x n_features), y in {0,1}.\n",
|
||
" \"\"\"\n",
|
||
" rng = np.random.RandomState(random_state)\n",
|
||
" # Half samples for class 0, half for class 1\n",
|
||
" n0 = n_samples // 2\n",
|
||
" n1 = n_samples - n0\n",
|
||
" # Class 0 around mean -2, class 1 around +2\n",
|
||
" mean0 = -2 * np.ones(n_features)\n",
|
||
" mean1 = 2 * np.ones(n_features)\n",
|
||
" X0 = rng.randn(n0, n_features) + mean0\n",
|
||
" X1 = rng.randn(n1, n_features) + mean1\n",
|
||
" X = np.vstack((X0, X1))\n",
|
||
" y = np.array([0]*n0 + [1]*n1)\n",
|
||
" return X, y\n",
|
||
"\n",
|
||
"def generate_multiclass_data(n_samples=150, n_features=2, n_classes=3, random_state=None):\n",
|
||
" \"\"\"\n",
|
||
" Generate synthetic multiclass data with n_classes Gaussian clusters.\n",
|
||
" \"\"\"\n",
|
||
" rng = np.random.RandomState(random_state)\n",
|
||
" X = []\n",
|
||
" y = []\n",
|
||
" samples_per_class = n_samples // n_classes\n",
|
||
" for cls in range(n_classes):\n",
|
||
" # Random cluster center for each class\n",
|
||
" center = rng.uniform(-5, 5, size=n_features)\n",
|
||
" Xi = rng.randn(samples_per_class, n_features) + center\n",
|
||
" yi = [cls] * samples_per_class\n",
|
||
" X.append(Xi)\n",
|
||
" y.extend(yi)\n",
|
||
" X = np.vstack(X)\n",
|
||
" y = np.array(y)\n",
|
||
" return X, y\n",
|
||
"\n",
|
||
"\n",
|
||
"# Generate and test on binary data\n",
|
||
"X_bin, y_bin = generate_binary_data(n_samples=200, n_features=2, random_state=42)\n",
|
||
"model_bin = LogisticRegression(lr=0.1, epochs=1000)\n",
|
||
"model_bin.fit(X_bin, y_bin)\n",
|
||
"y_prob_bin = model_bin.predict_prob(X_bin) # probabilities for class 1\n",
|
||
"y_pred_bin = model_bin.predict(X_bin) # predicted classes 0 or 1\n",
|
||
"\n",
|
||
"acc_bin = accuracy_score(y_bin, y_pred_bin)\n",
|
||
"loss_bin = binary_cross_entropy(y_bin, y_prob_bin)\n",
|
||
"print(f\"Binary Classification - Accuracy: {acc_bin:.2f}, Cross-Entropy Loss: {loss_bin:.2f}\")\n",
|
||
"#For multiclass:\n",
|
||
"# Generate and test on multiclass data\n",
|
||
"X_multi, y_multi = generate_multiclass_data(n_samples=300, n_features=2, n_classes=3, random_state=1)\n",
|
||
"model_multi = LogisticRegression(lr=0.1, epochs=1000)\n",
|
||
"model_multi.fit(X_multi, y_multi)\n",
|
||
"y_prob_multi = model_multi.predict_prob(X_multi) # (n_samples x 3) probabilities\n",
|
||
"y_pred_multi = model_multi.predict(X_multi) # predicted labels 0,1,2\n",
|
||
"\n",
|
||
"acc_multi = accuracy_score(y_multi, y_pred_multi)\n",
|
||
"loss_multi = categorical_cross_entropy(y_multi, y_prob_multi)\n",
|
||
"print(f\"Multiclass Classification - Accuracy: {acc_multi:.2f}, Cross-Entropy Loss: {loss_multi:.2f}\")\n",
|
||
"\n",
|
||
"# CSV Export\n",
|
||
"import csv\n",
|
||
"\n",
|
||
"# Export binary results\n",
|
||
"with open('binary_results.csv', mode='w', newline='') as f:\n",
|
||
" writer = csv.writer(f)\n",
|
||
" writer.writerow([\"TrueLabel\", \"PredictedLabel\"])\n",
|
||
" for true, pred in zip(y_bin, y_pred_bin):\n",
|
||
" writer.writerow([true, pred])\n",
|
||
"\n",
|
||
"# Export multiclass results\n",
|
||
"with open('multiclass_results.csv', mode='w', newline='') as f:\n",
|
||
" writer = csv.writer(f)\n",
|
||
" writer.writerow([\"TrueLabel\", \"PredictedLabel\"])\n",
|
||
" for true, pred in zip(y_multi, y_pred_multi):\n",
|
||
" writer.writerow([true, pred])"
|
||
]
|
||
}
|
||
],
|
||
"metadata": {},
|
||
"nbformat": 4,
|
||
"nbformat_minor": 5
|
||
}
|