Repository navigation
Expand file tree
/
Copy pathassignment2.Rmd
More file actions
346 lines (267 loc) · 20.7 KB
/
Copy pathassignment2.Rmd
File metadata and controls
346 lines (267 loc) · 20.7 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
---
title: "ETC3250/5250 Assignment 2"
date: "DUE: Friday, Apr 24 5pm "
output: html_document
editor_options:
chunk_output_type: inline
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
message = FALSE,
warning = FALSE,
error = FALSE,
collapse = TRUE,
comment = "#",
fig.height = 4,
fig.width = 6,
fig.align = "center",
cache = FALSE,
echo = FALSE
)
```
##Team Members
26927462 Phadon Phipat
27103013 Kwan King Yung
29730163 Thomas Hughes
## Exercises
1. (5pts)This question is about the normal distribution, and how it relates to the classification rule provided by quadratic discriminant analysis.
a. Write down the density function for a univariate normal distribution ($p=1$), with mean $\mu_k$ and variance $\sigma_k$.
b. Show that the quadratic discriminant rule for two groups ($K=2$), $\pi_1=\pi_2$ is equal to:
*Assign a new observation $x_0$ to group 1 if*
$$-\frac12 \left( \frac{1}{\sigma_1^2}- \frac{1}{\sigma_2^2} \right) {x_0^2} + \left(\frac{\mu_1}{\sigma_1^2}-\frac{\mu_2}{\sigma_2^2}\right)x_0 -\frac12 \left(\frac{\mu_1^2}{\sigma_1^2}- \frac{\mu_2^2}{\sigma_2^2} \right) -\log{\sigma_1}+\log{\sigma_2}>0$$

James, G., Witten, D., Hastie, T., & Tibshirani, R. (2017)(pp 149)
c. Suppose $\mu_1=4, \mu_2=-5, \sigma_1=0.5, \sigma_2=5$ simulate a set of 50 observations from each population. Make a plot of the population model, and add these samples as a rug plot on the horizontal axis. (See the lecture notes for a similar plot and code for linear discriminant analysis.)
```{r fig.width=6, fig.height=4, out.width="80%"}
library(tidyverse)
set.seed("24042020")
n <- 100; n1 <- 50
m1 <- 4
m2 <- -5
s1 <- 0.5
s2 <- 5
x <- c(rnorm(n1, m1, s1), rnorm(n-n1, m2, s2))
y <- c(rep(1, n1), rep(2, n-n1))
df <- tibble(x, y)
x <- seq(-20, 20, 0.1)
dx <- c(dnorm(x, m1, s1), dnorm(x, m2, s2))
y <- factor(c(rep(1, length(x)), rep(2, length(x))))
df_pop <- tibble(x=c(x,x), dx, y)
p <- ggplot() +
geom_rug(data=df, aes(x=x, y=0, colour=factor(y)), alpha=0.7) +
geom_line(data=df_pop, aes(x=x, y=dx, colour=y)) +
scale_color_brewer("", palette="Dark2") +
xlab("x") + ylab("density")
p
```
d. Write down the rule using these parameter values, and sketch the boundary corresponding to the rule on the previous plot.

```{r}
p + geom_vline(xintercept=2.68045, linetype=2) + geom_vline(xintercept=5.50135, linetype=2)
```
e. If instead you had made a mistake and assumed that the two variances were equal, this would have produced a linear discrimant rule. Mark this boundary on the previous plot. Explain why and how this differs from result of the QDA rule.
It would produce a rule where the discriminant x is halfway between the means. If you assume the variances are equal, the shapes of the two fitted normal distributions is different to if you didn't assume they were. This means the x values where each distribution has a higher density is different.
```{r echo=FALSE}
p + geom_vline(xintercept=2.68045, linetype=2) +
geom_vline(xintercept=5.50135, linetype=2) +
geom_vline(xintercept=-0.5, linetype=3, colour="red")
```
2. (4pts)In this question you are going to practice conducting bootstrap to obtain confidence intervals for a reasonably complicated yet simple analysis.
*A significant gender gap in maths performance in favour of male students has returned, despite closing in 2015* [Natassia Chrysanthos, Sydney Morning Herald](https://www.smh.com.au/national/nsw/urgent-need-to-address-maths-performance-as-nsw-slumps-in-international-test-20191203-p53ge2.html)
Last December, the 2018 [OECD PISA results](http://www.oecd.org/pisa/data/) were released. These are standardised test scores in math, reading and science, of 15 year olds across the globe. It led to a flurry of articles in the news about slipping standards of Australian students. If you also browsed the news of other countries (including New Zealand, Indonesia, Finland), you would find that many had similarly woeful stories. The above headline focuses on the math gap. To explore this, we will compute bootstrap confidence intervals for the difference between weighted averages for boys and girls in each country. The data is from the 2015 results.
The code block below will compute the difference between weighted averages for boys and girls in each country. A weighted average is often used with survey data, to reflect how the sampling was done relative to the population characteristics. The weighted average will typically better reflect the population mean.
```{r gender_means}
library(tidyverse)
library(ISOcodes)
data("ISO_3166_1")
# Load data
load("data/pisa_scores.rda")
# The country information will be used to join the data with map data
# and the ISOcodes package provides information about codes and country
scores <- scores %>%
mutate(CNT=recode(CNT, "QES"="ESP", "QCH"="CHN", "QAR"="ARG", "TAP"="TWN")) %>%
filter(CNT != "QUC") %>%
filter(CNT != "QUD") %>%
filter(CNT != "QUE") %>%
mutate(gender=factor(gender, levels=c(1,2), labels=c("female","male")))
score_gap <- scores %>%
group_by(CNT, gender) %>%
summarise(math=weighted.mean(math, w=w, na.rm=T),
reading=weighted.mean(reading, w=w, na.rm=T),
science=weighted.mean(science, w=w, na.rm=T)) %>%
pivot_longer(cols=c("math","reading","science"), names_to="test", values_to="score") %>%
pivot_wider(names_from=gender, values_from=score) %>%
mutate(gap = male - female) %>%
pivot_wider(id_cols=CNT, names_from="test", values_from=c("female","male","gap"))
```
This block of code will compute 90% bootstrap confidence intervals for the weighted mean difference.
```{r}
library(boot)
# Compute confidence intervals
cifn <- function(d, i) {
x <- d[i,]
female <- x %>% filter(gender == "female")
male <- x %>% filter(gender == "male")
ci <- weighted.mean(male$math, w=male$w, na.rm=T)-
weighted.mean(female$math, w=female$w, na.rm=T)
ci
}
bootfn <- function(d) {
r <- boot(d, statistic=cifn, R=100)
l <- sort(r$t)[5]
u <- sort(r$t)[95]
ci <- c(l, u)
return(ci)
}
score_gap_boot <- scores %>%
split(.$CNT) %>% purrr::map(bootfn) %>% as_tibble() %>% cbind(bound = c("ml", "mu")) %>%
pivot_longer(-bound, names_to="CNT", values_to="score_gap") %>%
pivot_wider(names_from = "bound", values_from = "score_gap")
score_gap <- score_gap %>%
left_join(score_gap_boot, by="CNT")
```
This block of code will add country names, and make dotplots with confidence intervals for the math gap for each country.
```{r gap_dots, fig.height=8, fig.width=6, out.width="60%"}
score_gap <- score_gap %>%
left_join(ISO_3166_1[,c("Alpha_3", "Name")], by=c("CNT"="Alpha_3")) %>%
rename(name = Name)
score_gap$name[score_gap$CNT == "KSV"] <- "Kosovo"
library(forcats)
score_gap <- score_gap %>%
mutate(name = recode(name, "Czechia"="Czech Republic",
"Korea, Republic of"="South Korea",
"Macedonia, Republic of"="Macedonia",
"Moldova, Republic of"="Moldova",
"Russian Federation"="Russia",
"Taiwan, Province of China"="Taiwan",
"Trinidad and Tobago"="Trinidad",
"United States"="USA",
"United Kingdom"="UK",
"Viet Nam"="Vietnam"))
ggplot(data=score_gap, aes(x=fct_reorder(name, gap_math), y=gap_math)) +
geom_hline(yintercept=0, colour="red") +
geom_point() +
geom_errorbar(aes(ymin=ml, ymax=mu), width=0) +
coord_flip() +
xlab("") + ylab("Gender gap") + ylim(c(-35, 35))
```
Write a paragraph explaining what you learn about the math gap across the countries tested in 2015.
The preceding graph illustrates the gender gap in mathematics performance for 15 year olds across the world taking the standardised OECD PISA test in 2015. As the calculation for weighted mean differences was male - female, a positive gender gap will indicate a country where males outperformed females, while a negative gender gap will indicate a country where females outperformed males. The first observation to be noted is that out of the 69 countries tested, 46, or 66.67% show a positive gender gap. Hence, in most countries, males outperformed females in mathematics. Henceforth, the median country, Canada, the mathematics score gap was 6.18, again favouring males. In addition, the mean gender gap across all countries was 4.80, which concludes that overall, males outperform females in mathematics. As mathematics is a base for many STEM fields, this supports the worldwide hypothesis that females are still behind in STEM education, and more needs to be done to empower girls worldwide to improve their mathematics ability. However, according to the "Results in Focus 2015" report by OECD PISA ("PISA 2015 Results in Focus", 2020), "boys and girls tend to think of working in different fields of science: girls envisage themselves as health professionals...boys see themselves as becoming information and communication technologies...scientists, or engineers". This showcases that most girls may not need a strong foundation in mathematics in order to have a successful STEM career, as health professionals rely less on mathematics than, for example engineers do. Hence, perhaps the science test may be a better indication of potential success in STEM.
In terms of regional performance, the results are interesting. There were a total of 37 European countries tested, 25 of which, or 68% had a male favoured gender gap. There were a total of 6 Middle Eastern countries tested, 3 of which, or 50% had a male favoured gender gap. There were a total of 6 North American countries tested, 4 of which, or 67% had a male favoured gender gap. There were a total of 6 South American countries tested, 6 of which, or 100% had a male favoured gender gap. There were a total of 2 Oceanic countries tested, 2 of which, or 100% had a male favoured gender gap. There were a total of 10 East Asian countries tested, 5 of which, or 50%, had a male favoured gender gap. There were a total of 2 African countries tested, 1 of which, or 50% had a male favoured gender gap.
If we discount South America for the time being, and assume that Europe, North America and Oceania are comprised mostly of countries with the majority speaking English as a main language, and assume that the Middle East, East Asia and Africa are all comprised mostly with the majority not speaking English as a main language, there is a lot to infer. Firstly, we see that in all the English-mainly speaking countries, the male favoured gender gap was at or above 67% of countries. Whereas in all the Non-English-mainly speaking countries, the male favoured gender gap was at exactly 50% of countries. This indicates that females in the 'Western world' are outperformed by their male counterparts at a greater rate than females in the 'Eastern world', who seem to be on par with their male counterparts. Of course, this does not take into account how extreme each country's gender gap is, but it indicates where the favour lies generally in each region.
Finally, these differences should be analysed with full knowledge of the 90% confidence interval shown. If we were to take the lower bound of the confidence interval as the new mean difference in mathematics, 5 countries previously male favoured would become female favoured. Hence, it is hard to accurately estimate each country's relative performance, especially since there is heteroskedasticity in the size of confidence intervals across all countries. For example, visibly Spain has a much smaller confidence interval than Uruguay, which could be due to a multitude of factors.
3. (9pts)A cross-rate is *an exchange rate between two currencies computed by reference to a third currency, usually the US dollar.*
The data file `rates_Nov19_Mar20.csv` was extracted from https://openexchangerates.org using the code below (my API key has been hidden from you):
```{r eval=FALSE}
# WARNING: YOU DON'T NEED TO RUN THIS CODE!!!!!
library(jsonlite)
library(lubridate)
library(tidyverse)
ru <- NULL
dt <- ymd("2019-11-01")
dt_end <- ymd("2020-03-31")
for (i in 1:151) {
cat(i,"\n")
url <- paste("http://openexchangerates.org/api/historical/",dt,".json?app_id=XXX", sep="")
x <- fromJSON(url)
x <- x$rates
if (length(x) == 171)
x <- x[-c(164,166)]
ru <- rbind(ru, data.frame(date=dt, x))
dt <- dt + days(1)
}
rownames(ru) <- ru$date
write_csv(ru, path="data/rates_new.csv")
```
a. (1)What's the data? Make a plot of the Australian dollar against date. Explain how the Australian dollar has changed relative to the US dollar over the 5 month period.
The Australian dollar stayed relatively constant from November to February, but experienced a drastic increase between February and April as compared to the US dollar. This meant that the Australian dollar had become significantly weaker on average as compared to the US dollar throughout the five months.
*Over the 5 month period the Australian dollar has weakened against the US dollar, with a big decline in mid-March as the coronavirus impact affected the world.*
```{r}
library(tidyverse)
rates <- read_csv("data/rates_Nov19_Mar20.csv")
ggplot(rates, aes(x=date, y=AUD)) + geom_line()
```
b. (1)You are going to work with these currencies: AUD, CAD, CHF, CNY, EUR, GBP, INR, JPY, KRW, MXN, NZD, RUB, SEK, SGD, ZAR. List the names of the countries and currency name that these codes refer to. Secondary question: why is the USD a constant 1 in this data.
AUD - Australia - Dollar
CAD - Canada - Dollar
CHF - Switzerland - Franc
CNY - China - Yuan
EUR - Europe - Euro
GBP - Great Britain - Pound
INR - India - Rupee
JPY - Japan - Yen
KRW - South Korea - Won
MXN - Mexico - Peso
NZD - New Zealand - Dollar
RUB - Russia - Ruble
SEK - Sweden - Krona
SGD - Singapore - Dollar
ZAR - South Africa - Rand
The US is the base rate, against which all other currencies are compared. So USD to USD is 1.
c. (2)The goal of the principal component analysis is to examine the relative movement of this subset of currencies, especially since coronavirus emerged until the end of March. PCA is used to summarise the volatility (variance) in the currencies, relative to each other. To do this you need to:
- Standardise all the currencies, individually. The resulting values will have a mean 0 and standard deviation equal to 1.
- Flip the sign so that high means the currency strengthened against the USD, and low means that it weakened. Its easier to explain trends, if you don't need to talk with double-negatives.
- Make a plot of all the currencies to check the result.
```{r}
library(viridisLite)
library(plotly)
rates_sub <- rates %>%
select(AUD, CAD, CHF, CNY, EUR, GBP, INR, JPY, KRW, MXN, NZD, RUB, SEK, SGD, ZAR) %>%
mutate_if(is.numeric,function(x) -1*(x-mean(x))/sd(x)) %>%
mutate(date = rates$date) %>%
select(date, everything())
rates_sub_long <- rates_sub %>%
pivot_longer(cols=-date, names_to="country", values_to="crossrate") %>% group_by(country)
ggplot(rates_sub_long, aes(x=date, y=crossrate, colour=country)) + geom_line() +
scale_colour_viridis_d("")
# ggplotly() Make an interactive plot to browse the currencies
```
d. (5)Conduct a principal component analysis on the subset of currencies. You need to work from a wide format of the data, where dates are in the columns, and currencies are in the rows. Normally, PCA operate on standardised variables but for this data, you need to NOT standardise each date. Think about why this is best.
- Why is this data considered to be high-dimensional?
- Make a scree plot to summarise the variance explained by cumulative principal components. How much of the total variation do two PCs explain?
- Plot the first two principal components. Write a summary of what you learn about the similarity and difference between the curreencies.
- Plot the loadings for PC1. Add a base line set at $1/\sqrt{15}$. Why use this as a guide? What time frame generated a big movement (or divergence) in the currencies? Which currencies strengthened relative to the USD in that period? What happened to the Australian dollar? Answer these questions in a paragraph, written in your own words.
- Do the same analysis for PC2. What time frame was there another movement of currencies? Which currencies primarily strengthened, and which weakened during this period?
- Finish with a paragraph summarising what variability the principal components analysis is summarising. What dimension reduction is being done?
```{r}
library(ggrepel)
rates_sub_wide <- rates_sub_long %>%
pivot_wider(id_cols=c(-"date",-"crossrate"), names_from="date", values_from = "crossrate")
rates_pca <- prcomp(rates_sub_wide %>% ungroup() %>%select(-country), scale=FALSE)
screeplot(rates_pca, type="l")
summary(rates_pca)
rates_pca$x %>%
as_tibble() %>%
mutate(currency = rates_sub_wide$country) %>%
ggplot(aes(x=PC1, y=PC2)) +
geom_hline(aes(yintercept=0))+
geom_vline(aes(xintercept=0))+
geom_point() +
geom_text(aes(x=PC1, y=PC2, label=currency)) +
theme(aspect.ratio=1)
rates_pc_loadings <- as_tibble(rates_pca$rotation) %>%
mutate(date = rates_sub$date,
indx = 1:nrow(rates_pca$rotation),
ymin=rep(0, nrow(rates_pca$rotation)))
ggplot(rates_pc_loadings) +
geom_hline(yintercept=c(-1/(150**(1/2)), 1/(150**(1/2))), colour="red") +
geom_errorbar(aes(x=indx, ymin=ymin, ymax=PC1)) +
geom_point(aes(x=indx, y=PC1))
ggplot(rates_pc_loadings) +
geom_hline(yintercept=c(-1/(150**(1/2)),
1/(150**(1/2))), colour="red") +
geom_errorbar(aes(x=indx, ymin=ymin, ymax=PC2)) +
geom_point(aes(x=indx, y=PC2))
```
The data is considered high dimensional as the number of variables, p which correspond to date is larger than n which is the number of samples which corresponds to the currencies.
The screeplot shows that just two PCs can explain approximately 80% of the total variation of the samples. The biplot of the first two principal components show that most of the currencies cluster together towards the origin of both PCs which suggest an association of these countries with the trend of weakening compared to US while currencies such as CHF which is distant from both origins suggest a difference from the majority, mostly likely having opposite response patterns from the majority of the currencies.
For the loadings plot for PC1, we set a baseline for 1/(150)^0.5 as there are approximately 150 loadings in the plot which means that 1/(15)^0.5 as given in the question may not be such a good fit for the plot that is shown. It seems that the timeframe where there is a big movement in the currencies starts at index 125 to 150. Based on the biplot previously stated, we can tell that currencies distant to the origin such as CHF, which is the furthest in magnitude away from the origin of PC1, are the ones moving against the overarching trend, thereby strengthening relative to USD in that period. AUD is part of the cluster that is close to the origin of PC1 which means it would weaken during this time period. This PC is the most important as it explains the most amount of variability compared to the rest of the PCs.
As for the loadings of PC2, while not as prominent as PC1 also explains a good portion of variability among the samples. The graph seems to show a consistent magnitude of variation with some spikes throughout the 150 loadings.. These may be caused by the currencies which are furthest from the PC2 origin shown in the biplot such as CNY. However, since PC2 does not explain as much as PC1, it’s effect definitely seems less than currencies which affect the variation in PC1.
To summarise, PC1 and PC2 account for 80% of the variability of samples which is more than the rest of the PCs which therefore allows the data to be explained mostly by these two PCs alone. This directly coincides with our pursuit for better visualisation of data via dimension reduction which is what PCA method has achieved as shown.
4. (2pts)What's wrong with the following statement?
**Principle component analysis is a dimension reduction technique**.
The correct term is ‘principal component analysis’ and not ‘principle’ as seen in the statement.
## Bibliography
James, G., Witten, D., Hastie, T., & Tibshirani, R. (2017). An introduction to statistical learning (8th ed.). New York: Springer Science+Business Media.
R: Documentation. (2020). Retrieved 3 April 2020, from https://www.r-project.org/other-docs.html
PISA 2015 Results in Focus. (2020). Retrieved 24 April 2020, from https://www.oecd.org/pisa/pisa-2015-results-in-focus.pdf