-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblog-solving-ols-regression-using-matrix-algebra.Rmd
executable file
·256 lines (187 loc) · 6.1 KB
/
blog-solving-ols-regression-using-matrix-algebra.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
---
title: "Solving Ordinary Least Squares (OLS) Regression Using Matrix Algebra"
date: "2019-01-30"
output:
html_document:
highlight: textmate
theme: lumen
code_download: true
toc: yes
toc_float:
collapsed: yes
smooth_scroll: yes
---
<br>*Tags:* <span class="badge badge-pill badge-light">Statistics</span>
<span class="badge badge-pill badge-primary">R</span>
<br>
In psychology, we typically learn how to calculate OLS regression by calculating each coefficient separately. However, I recently learned how to calculate this using matrix algebra. Here is a brief tutorial on how to perform this using R.
<br>
## R Packages
```{r}
packages <- c("tidyverse", "broom")
xfun::pkg_attach(packages, message = F)
```
<br>
## Dataset
```{r}
dataset <- carData::Salaries %>%
select(salary, yrs.since.phd) %>%
mutate(yrs.since.phd = scale(yrs.since.phd, center = T, scale = F))
```
```{r}
summary(dataset)
```
The `Salaries` dataset is from the `carData` package, which shows the salary of professors in the US during the academic year of 2008 and 2009. Let's say we are interested in determining if professors who have had their Ph.D. degree for longer are more likely to also have higher salaries.
<br>
## Solve Using Matrix Algebra
### Design Matrix
The design matrix is just a dataset of the all the predictors, which includes the `intercept` set at 1 and `yrs.since.phd`.
```{r}
x <- tibble(
intercept = 1,
yrs.since.phd = as.numeric(dataset$yrs.since.phd)
) %>%
as.matrix()
head(x)
```
<br>
### Dependent Variable
```{r}
y <- dataset$salary %>% as.matrix()
head(y)
```
<br>
### $X'X$
First, we need to solve for $X'X$, which is the transposed design matrix ($X'$) multiplied by the design matrix ($X$).
Let's take a look at what $X'$ looks like.
```{r}
x_transposed <- t(x)
x_transposed[, 1:6]
```
<br>
After multiplication, the matrix provides the total number of participants ($n$ = 397; really, the sum of the intercept), sum of `yrs.since.phd` ($\Sigma(yrs.since.phd)$ = 0), and sum of squared `yrs.since.phd` ($\Sigma (yrs.since.phd^2)$ = 65765.64). Respectively, $\Sigma (years.since.phd)$ and $\Sigma (yrs.since.phd^2)$ are sum of error ($\Sigma(yrs.since.phd-M_{yrs.since.phd})$) and sum of squared error ($\Sigma(yrs.since.phd-M_{yrs.since.phd})^2$) because we first centered the `yrs.since.phd` variable.
```{r}
x_prime_x <- (x_transposed %*% x)
x_prime_x %>% round(., 2)
```
<br>
Let's verify this.
```{r}
colSums(x) %>% round(., 2)
colSums(x^2) %>% round(., 2)
```
<br>
### $(X'X)^{-1}$
$(X'X)^{-1}$ is the inverse matrix of $X'X$.
```{r}
x_prime_x_inverse <- solve(x_prime_x)
x_prime_x_inverse
```
<br>
### $X'Y$
$X'Y$ contains the sum of Y ($\Sigma Y$ = 45141464) and sum of $XY$ ($\Sigma XY$ = 64801658).
```{r}
x_prime_y <- x_transposed %*% y
x_prime_y
```
<br>
Let's verify this.
```{r}
sum(y)
sum(x[, 2] * y)
```
<br>
### Coefficients
To obtain the coefficients, we can multiply these last two matrices ($b = (X'X)^{-1}X'Y$).
```{r}
coef <- x_prime_x_inverse %*% x_prime_y
coef
```
<br>
### Standard Error
To calculate the standard error, we multiply the inverse matrix of $X'X$ by the mean squared error (MSE) of the model and take the square root of its diagonal matrix ($\sqrt{diag((X'X)^{-1} * MSE)}$).
<br>
First, we need to calculate the $MSE$ of the model. Calculating $MSE$ of the model is still the same, $MSE = \frac{\Sigma(Y-\hat{Y})^{2}}{n-p} = \frac{\Sigma(e^2)}{df}$ where $Y$ is the DV, $\hat{Y}$ is the predicted DV, $n$ is the total number of participants (or data points), and $p$ is the total number of variables in the design matrix (or predictors, which includes the intercept).
<br>
To obtain the predicted values ($\hat{Y}$), we can also use matrix algebra by multiplying the design matrix with the coefficients ($\hat{Y} = Xb$).
```{r}
y_predicted <- x %*% coef
head(y_predicted)
```
<br>
Now that we have $\hat{Y}$, we can then calculate the $MSE$.
```{r}
e <- y - y_predicted
se <- sum(e^2)
n <- nrow(x)
p <- ncol(x)
df <- n - p
mse <- se / df
mse
```
<br>
Then, we multiply $(X'X)^{-1}$ by MSE.
```{r}
mse_coef <- x_prime_x_inverse * mse
mse_coef %>% round(., 2)
```
<br>
Then, we take the square root of the diagonal matrix to obtain the standard error of the coefficients.
```{r}
rmse_coef <- sqrt(diag(mse_coef))
rmse_coef %>% round(., 2)
```
<br>
### *t*-Statistic
The *t*-statistic is just the coefficient divided by the standard error of the coefficient.
```{r}
t_statistic <- as.numeric(coef) / as.numeric(rmse_coef)
t_statistic
```
<br>
### *p*-Value
We want the probability of obtaining that score or more extreme and not the other way around. Thus, we need to set lower to FALSE. Also, we need to multiply it by 2 to obtain a two-tailed test.
```{r}
p_value <- 2 * pt(t_statistic, df, lower = FALSE)
p_value
```
<br>
### Summary
```{r}
tibble(
term = colnames(x),
estimate = as.numeric(coef),
std.error = as.numeric(rmse_coef),
statistic = as.numeric(t_statistic),
p.value = as.numeric(p_value)
)
```
<br>
## Solve Using `lm` Function
```{r}
lm(salary ~ yrs.since.phd, dataset) %>% tidy()
```
<!-- disqus START -->
<br>
<hr>
<br>
<div id="disqus_thread"></div>
<script>
/**
* RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
* LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/
/*
var disqus_config = function () {
this.page.url = 'https://ekarinpongpipat.com/blog-solving-ols-regression-using-matrix-algebra.html'; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = 'blog_solving_ols_regression_using_matrix_algebra'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
*/
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = 'https://epongpipat.disqus.com/embed.js';
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
<!-- disqus END -->