# <b>Základy regrese | NMFM 334</b>

<b>Letný semester 2024 | Cvičenie 9 | 23.04.2024</b><br>
  HTML Markdown -- <a href = "cvicenie9.Rmd">Rmd source file</a> (UTF encoding)
  
  
**************
**************
    
  
<b>Outline of the lab session no.9:</b><br><br>
    <ul>
    <li>Statistical inference in heteroscedastic model</li>
     <li>General linear model (known variance structure)</li>
     <li>Heteroscedastic model with unknown structure</li>
    </ul>
    
<br><br>
    

The idea is to consider a general version of the linear regression model where 
$$
\boldsymbol{Y} \sim N(\mathbb{X}\boldsymbol{\beta}, \sigma^2 \mathbb{W}^{-1}),
$$
where $\boldsymbol{Y} = (Y_1, \dots, Y_n)^\top$ is the response vector for $n \in \mathbb{N}$ independent subjects, $\mathbb{X}$ is the corresponding model matrix (of a full rank $p \in \mathbb{N}$) and $\boldsymbol{\beta} \in \mathbb{R}^p$ is the vector of the unknown parameters. 

Note, that the normality assumption above is only used as a simplification but it is not needed 
to fit the model (without normality the results and the inference will hold asymptoticaly). 
<br><br>

Considering the variance structure, reflected in the matrix $\mathbb{W} \in \mathbb{R}^{n \times n}$ (a diagonal matrix because the subjets are mutually independent) can can distinguish two cases: 

<ol>
<li>the variance matrix $\mathbb{W}$ is a known matrix</li>
<li>the variance matrix $\mathbb{W}$ is an unknown matrix</li>
</ol>
  
The first case leads to the so-called <b>general linear model</b> (not a generalized linear model, which is a different class of models) and the second case leads to a regression model under heteroscedastic errors. Both cases will be briefly addressed below. 

<br><br>

### <b>1. General linear model</b> 
    
We start with the dataset <i><Hlavy> (heads) which respresents 
head sizes of fetuses (from an ultrasound monitoring) in different
periods of pregnancy. Each data value (row in the dataframe) provides an average 
over $n \in \mathbb{N}$ measurements of $n$ independent subjects (mothers). \

The information provided in the data stand for the: $i$ serial number; $t$ week of the pregnancy;
$n$ number of measurements used to calculate the average head size; and $y$ the average head size obtained from the particular number of measurements

 ```{R, warning = F, message = F, fig.width = 10} 
library("mffSM")

data(Hlavy, package = "mffSM")

### Exploratory analysis
head(Hlavy)
dim(Hlavy)
summary(Hlavy)

plot(y ~ t, data = Hlavy, pch = 23, col = "red3", bg = "orange")
```

The simple scatterplot above can be, however, substantially improved by accounting also for reliability of each observation (higher number of measurements used to obtain the average also means higher reliability). This can be obtain, for instance, by the following code: 


 ```{R, warning = F, message = F, fig.width = 10} 
with(Hlavy, quantile(n, prob = seq(0, 1, by = 0.2)))
Hlavy <- transform(Hlavy, fn = cut(n, breaks = c(0, 10, 30, 50, 60, 90), 
                          labels = c("<=10", "11-30", "31-50", "51-60", ">60")))
with(Hlavy, summary(fn))

plotData <- function(){
  PAL <- rev(heat_hcl(length(levels(Hlavy[, "fn"])), c.=c(80, 30), l=c(30, 90), 
                      power=c(1/5, 1.3)))
  names(PAL) <- levels(Hlavy[, "fn"])
  plot(y ~ t, data = Hlavy, pch = 23, col = "black", bg = PAL[fn])
  legend(17, 9, legend = levels(Hlavy[, "fn"]), title = "n", fill = PAL)
  abline(v = 27, col = "lightblue", lty = 2)
}    

plotData()
 ```

It is reasonable to assume, that for each measurement we have some model of the form 
$$
\widetilde{Y}_i | \boldsymbol{X}_i \sim N(\boldsymbol{X}_i^\top\boldsymbol{\beta}, \sigma^2)
$$
which is a homoscedastic model. Unfortunattely, we do not observe $\widetilde{Y}_i$ directly, 
but, instead, there a a set of independent measurements $\widetilde{Y}_{ij}$ for $j = 1, \dots, n_i$ (all measured conditionally on $\boldsymbol{X}_i$)
and we only observe the overall average $Y_i = \frac{1}{n_i}\sum_{j = 1}^{n_i} \widetilde{Y}_{ij}$. 

It also holds, that 
$$
Y_i \sim N(\boldsymbol{X}_i^\top\boldsymbol{\beta}, \sigma^2/{n_i}),
$$
or, considering all data together, we have 
$$
\boldsymbol{Y} \sim N_n(\mathbb{X}\boldsymbol{\beta}, \sigma^2 \mathbb{W}^{-1}), 
$$
where $\mathbb{W}^{-1}$ is a diagonal matrix $\mathbb{W}^{-1} = diag(1/n_1, \dots, 1/n_n)$ (thus, the variance structure is known from the design of the experiment). <br><br>

In addition, practical motivation behind the model is the following:
Practitioners say that the relationship $y ~ t$  could be described by a piecewise 
quadratic function with $t = 27$ being a point where the quadratic 
$relationship changes its shape.<br><br>

From the practical point of view, the fitted curve should be continuous at 
$t = 27$ and perhaps also smooth (i.e., with continuous at least the first 
derivative) as it is biologically not defensible to claim that at $t = 27$ 
the growth has a jump in the speed (rate) of the growth.<br><br>

As far as different observations have different credibility, we will use the <b>general linear model</b> with the known matrix $\mathbb{W}$. The model can be fitted as follows: 


 ```{R, warning = F, message = F, fig.width = 10} 
Hlavy <- transform(Hlavy, t27 = t - 27)

### Grid to calculate the fitted regression function
tgrid <- seq(16, 42, length = 100)
pdata <- data.frame(t27 = tgrid - 27)


summary(mCont <- lm(y ~ t27 + I(t27^2) + (t27 > 0):t27 + (t27 > 0):I(t27^2), 
                    weights = n, data = Hlavy))
 ```
 
 <br><br>

### <font color = "#880000">Indidividual work</font> 
<ul>
<li>What is estimated by the model above? Interpret the estimated parameters: </li>
<li>Can you manually reconstruct the estimated values for the mean structure and, also, 
the estimated values for the variance parameters?

 ```{R, warning = F, message = F, fig.width = 10} 
### Some naive calculation 
W <- diag(Hlavy$n);
Y <- Hlavy$y;
X <- model.matrix(mCont)

### Estimated regression coefficients 
(betahat <- solve(t(X)%*%W%*%X)%*%(t(X)%*%W%*%Y));
coef(mCont)

### Generalized fitted values 
(Yg <- X%*%betahat);
fitted(mCont)

### Generalized residual sum of squares 
(RSS <- t(Y - Yg)%*%W%*%(Y - Yg));

### Generalized mean square 
RSS/(length(Y)-ncol(X))
(summary(mCont)$sigma)^2

### Be careful that Multiple R-squared:  0.9968 reported in the output 
### "summary(mCont)" is not equal to 
sum((Yg-mean(Yg))^2)/sum((Y-mean(Y))^2)

### Instead, it equals the following quantity that is more difficult 
### to interpret 
barYw <- sum(Y*Hlavy$n)/sum(Hlavy$n);   
### weigthed mean of the original observations 

### something as "generalized" regression sum of squares 
SSR <- sum((Yg - barYw)^2 * Hlavy$n)

### something as "generalized" total variance 
SST <- sum((Y - barYw)^2 * Hlavy$n); 

### "generalized" R squared
SSR/SST
summary(mCont)$r.squared
 ```
</li>
<li>Compare the general linear model above with the simple model below. What are the main differences between these two models? Can you explain them? 
```{R, warning = F, message = F, fig.width = 10} 
iii <- rep(1:nrow(Hlavy), Hlavy$n)
Hlavy2 <- Hlavy[iii,]; # new dataset

summary(mCont <- lm(y ~ t27 + I(t27^2) + (t27 > 0):t27 + (t27 > 0):I(t27^2), data = Hlavy2))
```
</li>

</ul>
<hr size="3" width="100%" noshade style="color:#440000" align="left" />
<br><br>
<br><br>

### <b>2. Model with heteroscedastic errors (sandwich estimate)</b>

For a general heteroscedastic model it is usually assumed that  
$$
Y_i | \boldsymbol{X}_i \sim N(\boldsymbol{X}_i^\top\boldsymbol{\beta}, \sigma^2(\boldsymbol{X}_i))
$$
where $\sigma^2(\cdot)$ is some positive (unknown) function of the response variables $\boldsymbol{X}_i \in \mathbb{R}^p$. Note, that the normality assumption is here only given for simplification but it is not required. <br><br>


In the following, we will consider the datasat that comes from the project MANA (Maturita na necisto) launched in the Czech Republic in 2005. This project was a part  of a bigger project 
whose goal was to prepare a new form of graduation exam ("statni maturita").  
This dataset contains the results in English language at grammar schools. 

```{R, warning = F, message = F, fig.width = 10} 
load(url("http://msekce.karlin.mff.cuni.cz/~maciak/NMSA407/mana.RData"))
```

<br><br>
The variables in the data are: `region` (1 = Praha; 2 = Stredocesky; 3 = Jihocesky;4 = Plzensky;
=5 = Karlovarsky; 6 = Ustecky; 7 = Liberecky; 8 = Kralovehradecky; 9 = Pardubicky; 10 = Vysocina;
11 = Jihomoravsky; 12 = Olomoucky; 13 = Zlinsky; 14 = Moravskoslezsky), `specialization` (1 = education; 2 = social science; 3 = languages; 4 = law; 5 = math-physics; 6 = engineering; 7 = science;
8 = medicine; 9 = economics; 10 = agriculture; 11 = art), `gender` (0 = female; 1 = male),
`graduation` (0 = no; 1 = yes), `entry.exam`(0 = no; 1 = yes), `score` (score in English language in MANA test), `avg.mark` (aaverage mark (grade) from all subjects at the last report card), and 
`mark.eng` (average mark (grade) from the English language at the last 5 report cards).
<br><br>

For better intuition, we can transform the data as follows: 
```{R, warning = F, message = F, fig.width = 10} 
mana <- transform(mana, fregion = factor(region, levels = 1:14, 
                         labels = c("A", "S", "C", "P", "K", "U", "L", "H", "E",
                                    "J", "B", "M", "Z", "T")),
                        fspec   = factor(specialization, levels = 1:11, 
                                         labels = c("Educ", "Social", "Lang", 
                                                    "Law", "Mat-Phys", "Engin", 
                                                    "Science", "Medic", 
                                                    "Econom", "Agric", "Art")),
                        fgender = factor(gender, levels = 0:1, 
                                        labels = c("Female", "Male")),
                        fgrad   = factor(graduation, levels = 0:1,
                                         labels = c("No", "Yes")),
                        fentry  = factor(entry.exam, levels = 0:1, 
                                         labels = c("No", "Yes")))

summary(mana)
```

### <font color = "#880000">Indidividual work</font> 
<ul>
<li>Consider the transformed data above and perform a simple exploratory analaysis (in terms of some simple sample characteristics and plots).</li>

<li><Focus, in particular on the region in the Czech republic and the specialiation./li>
</ul>

<hr size="3" width="100%" noshade style="color:#440000" align="left" />

<br><br>

For illustration purposes we will fit a simple (additive) model to explain the average mark given the region and the specialization. 

```{R, warning = F, message = F, fig.width = 10} 
mAddit <- lm(avg.mark ~ fregion + fspec, data = mana, x = T)
summary(mAddit)
modelMatrix <- mAddit$x

plotLM(mAddit)
```


In the diagnostic plots, there are some obvious issues with heteroscedasticity. We will use the <b>sandwich estimate</b> of the variance matrix to account for this heteroscedasticty. 

```{R, warning = F, message = F, fig.width = 10} 
library(sandwich)


### Estimate of the variance matrix of the regression coefficients 
(VHC <- vcovHC(mAddit, type = "HC3"))
```


And we can compare the result with manually recontructed estimate

```{R, warning = F, message = F, fig.width = 10} 
X     <- model.matrix(mAddit);                                               
Bread <- solve(t(X) %*% X) %*% t(X)
Meat  <- diag(residuals(mAddit)^2 / (1 - hatvalues(mAddit))^2)
Bread %*% Meat %*% t(Bread)

all.equal(Bread %*% Meat %*% t(Bread), VHC)
```

This can be conpared with the classical estimate of the variance covariance matrix---in the following, we only focuss on some portion of the matrix. 

```{R, warning = F, message = F, fig.width = 10} 
VHC[1:5, 1:5] 

vcov(mAddit)[1:5, 1:5]
```


Note, that some variance component are overestimated by the standard estimate (function `vcov()`) and some others or uderestimated. 

### <font color = "#880000">Indidividual work</font> 
<ul>
<li>How can the variance-covariance matrix above (or the matrices above) be used to get the estimate for the variance matrix of $\boldsymbol{Y}$?</li>
```{R, warning = F, message = F, fig.width = 10} 
(modelMatrix %*% VHC %*% t(modelMatrix))[1:5, 1:5]
```
</ul>




<br><br>
