|
| 1 | +```@setup glm |
| 2 | +function plot_histogram(xs, f; kwargs...) |
| 3 | + plt = histogram(xs; |
| 4 | + label="Sampled density", |
| 5 | + nbins=100, |
| 6 | + normalize = :pdf, |
| 7 | + kwargs... |
| 8 | + ) |
| 9 | +
|
| 10 | + plot!(plt, range(minimum(xs), maximum(xs); length=100), f; |
| 11 | + label="True density", |
| 12 | + line=(4,:black), |
| 13 | + ) |
| 14 | +
|
| 15 | + return plt |
| 16 | +end |
| 17 | +``` |
| 18 | + |
| 19 | + |
| 20 | +# [Linear regression revisited](@id statistics) |
| 21 | + |
| 22 | +This section revisits the linear regression. The classical statistical approach uses a different approach, but derives the same formulation for linear regression. Besides point estimates for parameters, this approach also computes their confidence intervals and is able to test whether some parameters can be omitted from the model. We will start with hypothesis testing and then continue with regression. |
| 23 | + |
| 24 | +Julia provides lots of statistical packages. They are summarized at the [JuliaStats](https://juliastats.org/) webpage. This section will give a brief introduction to many of them. |
| 25 | + |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | +## Theory of hypothesis testing |
| 30 | + |
| 31 | +Hypothesis testing verifies whether data satisfy a given null hypothesis ``H_0``. Under some assumptions and the validity of the null hypothesis, the test derives that a transformation of the data follows some distribution. Then it constructs a confidence interval of this distribution and checks whether the trasnformed variable lies into the confidence interval. If it lies ourside of it, the test rejects the null hypothesis. In the opposite case, it fails to reject the null hypothesis. The latter is different from confirming the null hypothesis. Hypothesis is like a grumpy professor who tells whether a student knows his lecture. He never acknowledges that the student knows it sufficiently, but he is often clear that the student does not know it. |
| 32 | + |
| 33 | +An example is the one-sided [Student's t-test](https://en.wikipedia.org/wiki/Student's_t-test) that verifies that a dataset has mean ``\mu``. It can be generalized to compare the mean (performance) of two datasets. Under some assumption, it derives that |
| 34 | + |
| 35 | +```math |
| 36 | +t = \sqrt{n}\frac{\overline X - \mu}{\hat\sigma} |
| 37 | +``` |
| 38 | + |
| 39 | +follows the [Student's distribution](https://en.wikipedia.org/wiki/Student%27s_t-distribution) with ``n-1`` degress of freedom. Here, the dataset ``X`` has size ``n``, its mean is ``\overline X`` and its standard deviation ``\hat \sigma``. Instead of computing the confidence interval, the usual way is to define the ``p``-value |
| 40 | + |
| 41 | +```math |
| 42 | +p = 2\min\{\mathbb P(T\le t), \mathbb P(T\ge t)\} |
| 43 | +``` |
| 44 | + |
| 45 | +If the ``p``-value is smaller than a given threshold, usually ``5\%``, the null hypothesis is rejected. In the opposite case, it is not rejected. The ``p``-value is a measure of the probability that an observed difference could have occurred just by random chance. |
| 46 | + |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | +## Hypothesis testing |
| 51 | + |
| 52 | + |
| 53 | + |
| 54 | +We first randomly generate data with from the normal distribution with zero mean. |
| 55 | + |
| 56 | +```@example glm |
| 57 | +using Random |
| 58 | +using Statistics |
| 59 | +using LinearAlgebra |
| 60 | +using Plots |
| 61 | +
|
| 62 | +Random.seed!(666) |
| 63 | +
|
| 64 | +n = 1000 |
| 65 | +xs = randn(n) |
| 66 | +
|
| 67 | +nothing # hide |
| 68 | +``` |
| 69 | + |
| 70 | +The following exercise checks performs the ``t``-test to check whether it comes from a distribution with zero mean. |
| 71 | + |
| 72 | + |
| 73 | + |
| 74 | + |
| 75 | + |
| 76 | +```@raw html |
| 77 | +<div class = "exercise-body"> |
| 78 | +<header class = "exercise-header">Exercise:</header><p> |
| 79 | +``` |
| 80 | + |
| 81 | +Use the ``t``-test to verify whether the samples were generated from a distribution with zero mean. |
| 82 | + |
| 83 | +**Hint**: the Student's distribution is invoked by `TDist()`. |
| 84 | + |
| 85 | +**Hint**: the probability ``\mathbb P(T\le t)`` equals to the [distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function) ``F(t)``, which can be called by `cdf`. |
| 86 | + |
| 87 | +```@raw html |
| 88 | +</p></div> |
| 89 | +<details class = "solution-body"> |
| 90 | +<summary class = "solution-header">Solution:</summary><p> |
| 91 | +``` |
| 92 | + |
| 93 | +We compute the statistic ``t``, then define the Student's distribution with ``n-1`` degrees of freedom, evaluate the distribution function at ``t`` and finally compute the ``p``-value. |
| 94 | + |
| 95 | +```@example glm |
| 96 | +using Distributions |
| 97 | +
|
| 98 | +t = mean(xs) / std(xs) * sqrt(n) |
| 99 | +
|
| 100 | +prob = cdf(TDist(n-1), t) |
| 101 | +p = 2*min(prob, 1-prob) |
| 102 | +
|
| 103 | +nothing # hide |
| 104 | +``` |
| 105 | + |
| 106 | +```@raw html |
| 107 | +</p></details> |
| 108 | +``` |
| 109 | + |
| 110 | + |
| 111 | + |
| 112 | + |
| 113 | + |
| 114 | + |
| 115 | + |
| 116 | + |
| 117 | + |
| 118 | +Even though the computation of the ``p``-value is simple, we can use the [HypothesisTests](https://juliastats.org/HypothesisTests.jl/stable/) package. When we run the test, it gives us the same results as we computed. |
| 119 | + |
| 120 | +```@example glm |
| 121 | +using HypothesisTests |
| 122 | +
|
| 123 | +OneSampleTTest(xs) |
| 124 | +``` |
| 125 | + |
| 126 | + |
| 127 | + |
| 128 | + |
| 129 | + |
| 130 | + |
| 131 | + |
| 132 | +## Theory of generalized linear models |
| 133 | + |
| 134 | +The statistical approach to linear regression is different from the one from machine learning. It also assumes linear prediction function |
| 135 | + |
| 136 | +```math |
| 137 | +\operatorname{predict}(w;x) = w^\top x. |
| 138 | +``` |
| 139 | + |
| 140 | +Then it considers some invertible link function ``g:\mathbb R\to \mathbb R`` and assumes that ``y`` conditioned on ``x`` follows an apriori specified distribution with density ``f``. The parameters of this distribution are uknown, but the distribution should satisfy the conditional expectation ``E(y\mid x) = g^{-1}(w^\top x)``. The goal is to find the weights ``w`` by the [maximum likelihood estimate](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation). This technique maximizes the likelihood function |
| 141 | + |
| 142 | +```math |
| 143 | +\operatorname{maximize}\qquad \prod_{i=1}^n f(y_i). |
| 144 | +``` |
| 145 | + |
| 146 | +Since the density is the derivative of the distribution function, the term ``f(y_i)`` describes the "probability" of ``y_i`` under density ``f``. If ``y_i`` are independent, then the product is the joint probability for all samples. Therefore, maximizing the the likelihood function amounts to finding the parameters of the apriori specified distribution such that the observed samples ``y_i`` have the highest probability to follow this distriubtion. Since these distributions are usually taken from the [exponential family](https://en.wikipedia.org/wiki/Exponential_family), the log-likelihood |
| 147 | + |
| 148 | +```math |
| 149 | +\operatorname{maximize}\qquad \sum_{i=1}^n \log f(y_i). |
| 150 | +``` |
| 151 | + |
| 152 | +is often maximized. Since logarithm is an increasing function, these two approaches are equivalent. |
| 153 | + |
| 154 | + |
| 155 | + |
| 156 | + |
| 157 | + |
| 158 | + |
| 159 | +#### Case 1: Linear regression |
| 160 | + |
| 161 | +The first case considers ``g(z)=z`` to be the identity function and ``y\mid x`` with the [normal distribution](https://en.wikipedia.org/wiki/Normal_distribution) ``N(\mu_i, \sigma^2)``. Then |
| 162 | + |
| 163 | +```math |
| 164 | +w^\top x_i = g^{-1}(w^\top x_i) = \mathbb E(y_i \mid x_i) = \mu_i, |
| 165 | +``` |
| 166 | + |
| 167 | +and, therefore, we need the solve the following optimization problem. |
| 168 | + |
| 169 | +```math |
| 170 | +\operatorname{maximize}_w\qquad \sum_{i=1}^n \log \left(\frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(\frac{-(y_i - w^\top x_i)^2}{2\sigma^2}\right)\right). |
| 171 | +``` |
| 172 | + |
| 173 | +Since we maximize with respect to ``w``, most terms behave like constants and this optimization problem is equivalent to |
| 174 | + |
| 175 | + |
| 176 | +```math |
| 177 | +\operatorname{minimize}\qquad \sum_{i=1}^n (y_i - w^\top x_i)^2. |
| 178 | +``` |
| 179 | + |
| 180 | +This is precisely the linear regression as derived in the previous lectures. |
| 181 | + |
| 182 | + |
| 183 | + |
| 184 | +#### Case 2: Logistic regression |
| 185 | + |
| 186 | +The second case considers ``g(z)=\log z`` to be the logarithm function and ``y\mid x`` with the [Poisson distribution](https://en.wikipedia.org/wiki/Poisson_distribution) ``Po(\lambda)``. The inverse function to ``g`` is ``g^{-1}(z)=e^z``. Since the Poisson distribution has non-negative discrete values with probabilities ``\mathbb P(Y=k) = \frac{1}{k!}\lambda^ke^{-\lambda}``, labels ``y_i`` must also be non-negative integers. The same formula for the conditional expectation as before yields: |
| 187 | + |
| 188 | +```math |
| 189 | +e^{w^\top x_i} = g^{-1}(w^\top x_i) = \mathbb E(y_i \mid x_i) = \lambda_i, |
| 190 | +``` |
| 191 | + |
| 192 | +Plugging this term into the maximizing the log-likelihood function, results in the following optimization problem: |
| 193 | + |
| 194 | +```math |
| 195 | +\operatorname{maximize}_w\qquad \sum_{i=1}^n\log\left( \frac{1}{y_i!}\lambda_i^{y_i} e^{-\lambda_i}\right). |
| 196 | +``` |
| 197 | + |
| 198 | +By using the formula for ``\lambda_i`` and getting rid of constants, we transform this problem into |
| 199 | + |
| 200 | +```math |
| 201 | +\operatorname{minimize}_w\qquad \sum_{i=1}^n \left(e^{w^\top x_i} - y_iw^\top x_i\right). |
| 202 | +``` |
| 203 | + |
| 204 | +This function is similar to the one derived for logistic regression. |
| 205 | + |
| 206 | + |
| 207 | +## Linear models |
| 208 | + |
| 209 | +We will use the [Employment and Wages in Spain](https://vincentarelbundock.github.io/Rdatasets/doc/plm/Snmesp.html) dataset because it is slightly larger that iris. It contains 5904 observations of wages from 738 companies in Spain during 1983 to 1990. We will estimate the dependance of wages on other factors such as employment or cash flow. We first load the dataset and transform the original log-wages into normal wages. We use base ``2`` to obtain relatively small numbers. |
| 210 | + |
| 211 | +```@example glm |
| 212 | +using RDatasets |
| 213 | +
|
| 214 | +wages = dataset("plm", "Snmesp") |
| 215 | +wages.W = 2. .^ (wages.W) |
| 216 | +
|
| 217 | +nothing # hide |
| 218 | +``` |
| 219 | + |
| 220 | +We can use the already known precedure to compute the best fit. |
| 221 | + |
| 222 | +```@example glm |
| 223 | +X = Matrix(wages[:, [:N, :Y, :I, :K, :F]]) |
| 224 | +X = hcat(ones(size(X,1)), X) |
| 225 | +y = wages[:, :W] |
| 226 | +
|
| 227 | +w0 = (X'*X) \ (X'*y) |
| 228 | +
|
| 229 | +nothing # hide |
| 230 | +``` |
| 231 | + |
| 232 | +Another possibility is to use the packege [GLM](https://juliastats.org/GLM.jl/stable/) and its command `lm` for linear models. |
| 233 | + |
| 234 | +```@example glm |
| 235 | +using GLM |
| 236 | +
|
| 237 | +model = lm(@formula(W ~ 1 + N + Y + I + K + F), wages) |
| 238 | +``` |
| 239 | + |
| 240 | +The table shows the value of the parameters and their confidence intervals. Besides that, it also tests the null hypothesis ``H_0: w_j = 0`` whether some of the regression coefficient can be omitted. The ``t`` statistics is in column `t`, while its ``p``-value in column `Pr(>|t|)`. The next exercise checks whether we can achieve the same results with fewer features. |
| 241 | + |
| 242 | + |
| 243 | + |
| 244 | + |
| 245 | + |
| 246 | + |
| 247 | + |
| 248 | +```@raw html |
| 249 | +<div class = "exercise-body"> |
| 250 | +<header class = "exercise-header">Exercise:</header><p> |
| 251 | +``` |
| 252 | + |
| 253 | +Check that the results by computing the solution by hand and by `lm` are the same. |
| 254 | + |
| 255 | +Then remove the feature with the highest ``p``-value and observe whether there was any performance drop. The performance is usually evaluated by the [coeffient of determination](https://en.wikipedia.org/wiki/Coefficient_of_determination) denote by ``R^2\in[0,1]``. Its higher values indicate better model. |
| 256 | + |
| 257 | +**Hint**: Use functions `coef` and `r2`. |
| 258 | + |
| 259 | +```@raw html |
| 260 | +</p></div> |
| 261 | +<details class = "solution-body"> |
| 262 | +<summary class = "solution-header">Solution:</summary><p> |
| 263 | +``` |
| 264 | + |
| 265 | +Since the parameters for both approaches are almost the same, the approaches give the same result. |
| 266 | + |
| 267 | +```@example glm |
| 268 | +norm(coef(model) - w0) |
| 269 | +``` |
| 270 | + |
| 271 | +The ``p``-value for column ``K`` is ``3.3\%``. We define the reduced model without this feature. |
| 272 | + |
| 273 | +```@example glm |
| 274 | +model_red = lm(@formula(W ~ 1 + N + Y + I + F), wages) |
| 275 | +``` |
| 276 | + |
| 277 | +Since we observe only a small performance drop, we could omit this feature without a change to prediction capability of the model. |
| 278 | + |
| 279 | +```@example glm |
| 280 | +r2(model) - r2(model_red) |
| 281 | +``` |
| 282 | + |
| 283 | +```@raw html |
| 284 | +</p></details> |
| 285 | +``` |
| 286 | + |
| 287 | + |
| 288 | + |
| 289 | + |
| 290 | + |
| 291 | + |
| 292 | + |
| 293 | + |
| 294 | +The core assumption of this approach is that ``y`` has normal distribution. We use the `predict` function to predict the data and then use the `plot_histogram` function written earlier to plot the histogram and a density of the normal distribution. For the normal distribution, we need to specify the correct mean and variance. |
| 295 | + |
| 296 | +```@example glm |
| 297 | +y_hat = predict(model) |
| 298 | +
|
| 299 | +plot_histogram(y_hat, x -> pdf(Normal(mean(y_hat), std(y_hat)), x)) |
| 300 | +``` |
| 301 | + |
| 302 | +The distribution resembles the normal distribution, but there are some differences. We can use the more formal [Kolmogorov-Smirnov](https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test) test to verify whether a sample comes from a distribution. |
| 303 | + |
| 304 | +```@example glm |
| 305 | +test_normality = ExactOneSampleKSTest(y_hat, Normal(mean(y_hat), std(y_hat))) |
| 306 | +``` |
| 307 | + |
| 308 | +The result is expected. The ``p``-value is close to ``1\%``, which means that we would reject the hypothesis that the data come from the normal distribution even though it is not entirely far away. |
| 309 | + |
| 310 | + |
| 311 | + |
| 312 | +## Generalized linear models |
| 313 | + |
| 314 | + |
| 315 | +For the generalized linear models, we need to specify the link function ``g`` and the distribution of ``y \mid x``. For the former we choose ``g(z) = \sqrt{z}`` and for the latter the [inverse Gaussian](https://en.wikipedia.org/wiki/Inverse_Gaussian_distribution) distribution. Since we want to use the generalized linear model, we replace `lm` by `glm`. |
| 316 | + |
| 317 | +```@example glm |
| 318 | +model = glm(@formula(W ~ 1 + N + Y + I + K + F), wages, InverseGaussian(), SqrtLink()) |
| 319 | +``` |
| 320 | + |
| 321 | + |
| 322 | + |
| 323 | + |
| 324 | + |
| 325 | + |
| 326 | + |
| 327 | + |
| 328 | +The next exercise plots the prediction for the linear model. |
| 329 | + |
| 330 | +```@raw html |
| 331 | +<div class = "exercise-body"> |
| 332 | +<header class = "exercise-header">Exercise:</header><p> |
| 333 | +``` |
| 334 | + |
| 335 | +Create the scatter plot of predictions and labels. You are not allowed to use the `predict` function. |
| 336 | + |
| 337 | +```@raw html |
| 338 | +</p></div> |
| 339 | +<details class = "solution-body"> |
| 340 | +<summary class = "solution-header">Solution:</summary><p> |
| 341 | +``` |
| 342 | + |
| 343 | +Due to construction of generalized linear models, the prediction equals ``g^{-1}(w^\top x)``. We save it into ``\hat y``. |
| 344 | + |
| 345 | +```@example glm |
| 346 | +g_inv(z) = z^2 |
| 347 | +
|
| 348 | +y_hat = g_inv.(X*coef(model)) |
| 349 | +
|
| 350 | +nothing # hide |
| 351 | +``` |
| 352 | + |
| 353 | +The scatter plot is now simple. |
| 354 | + |
| 355 | +```@example glm |
| 356 | +scatter(y, predict(model); |
| 357 | + label="", |
| 358 | + xlabel="Label", |
| 359 | + ylabel="Prediction", |
| 360 | +) |
| 361 | +
|
| 362 | +savefig("glm_predict.svg") |
| 363 | +``` |
| 364 | + |
| 365 | + |
| 366 | +```@raw html |
| 367 | +</p></details> |
| 368 | +``` |
| 369 | + |
| 370 | + |
| 371 | + |
0 commit comments