---
title: 'STA 35C: Homework 5'
subtitle: 'Instructor: Akira Horiguchi'
author: "Student name: ABCDE FGHIJ; Student ID: 123456789"
date: "2025-11-05 23:59:00 PDT"
date-format: "MMM D, YYYY (dddd), HH:mm z"
format: 
    pdf: 
        include-in-header:
          text: |
            \usepackage{fancyhdr}
            \usepackage{lastpage}
            \pagestyle{fancy}
            \fancyhf{} % sets both header and footer to nothing
            \renewcommand{\headrulewidth}{0pt}
            \fancyhead[RO,RE]{}
            \fancyhead[LO,LE]{}
            \fancyfoot[LE,LO]{}
            \fancyfoot[LE,CO]{Page \thepage\ of \pageref{LastPage}}
editor: source
geometry:
  - top=5mm
  - bottom=20mm
  - left=5mm
  - right=5mm
urlcolor: blue
---

The assignment must be done in an [R Markdown](https://rmarkdown.rstudio.com) or [Quarto](https://quarto.org/) document. The assignment must be submitted by the due date above by uploading:

-   a .pdf file in GRADESCOPE (if you can knit/compile your .rmd to a .html file only, please save the created .html file as a .pdf file (by opening the .html file -\> print -\> save to .pdf)).

Email submissions will not be accepted.

Each answer has to be based on `R` code that shows how the result was obtained. The code has to answer the question or solve the task. For example, if you are asked to find the largest entry of a vector, the code has to return the largest element of the vector. If the code just prints all values of the vector, and you determine the largest element by hand, this will not be accepted as an answer. No points will be given for answers that are not based on `R`. This homework already contains chunks for your solution (you can also create additional chunks for each solution if needed, but it must be clear to which tasks your chunks belong).

There are many possible ways to write `R` code that is needed to answer the questions or do the tasks, but for some of the questions or tasks you might have to use something that has not been discussed during the lectures or the discussion sessions. You will have to come up with a solution on your own. Try to understand what you need to do to complete the task or to answer the question, feel free to search the Internet for possible solutions, and discuss possible solutions with other students. It is perfectly fine to ask what kind of an approach or a function other students use. However, you are not allowed to share your code or your answers with other students. Everyone has to write the code, do the tasks and answer the questions on their own.

During the discussion sessions, you may be asked to present and share your solutions.

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(knitr)
library(tibble)

hook_output <- knit_hooks$get("output")
knit_hooks$set(output = function(x, options) {
  lines <- options$output.lines
  if (is.null(lines)) {
    return(hook_output(x, options))  # pass to default hook
  }
  x <- unlist(strsplit(x, "\n"))
  more <- "..."
  if (length(lines)==1) {        # first n lines
    if (length(x) > lines) {
      # truncate the output, but add ....
      x <- c(head(x, lines), more)
    }
  } else {
    x <- c(more, x[lines], more)
  }
  # paste these lines together
  x <- paste(c(x, ""), collapse = "\n")
  hook_output(x, options)
})

knitr::opts_chunk$set(comment = NA) # makes it so the ## doesnt appear in output for chunks
```

```{r}
set.seed(2025*4)  # do not change this; this helps to reproduce the "random" results
```

\newpage


# 1. Cross-validation

(Code examples: <https://hastie.su.domains/ISLR2/Labs/Rmarkdown_Notebooks/Ch5-resample-lab.html>)

We perform cross-validation on a simulated data set.

```{r}
set.seed(1)
x <- runif(100) # 100 values being uniformly distributed (btw 0 and 1) are generated
y <- 1 + x -  x^2  + rnorm(100, 0, 0.1)
```

(a) Create a scatterplot where `y` is plotted against `x`. Describe your findings.

```{r}
### Your Solution (Code)


```



(b) Use `lm()` to fit the three models below. Print the summary tables for the three fitted models and comment on your findings.

- Model I: $Y = \beta_0 + \beta_1 X + \varepsilon$
- Model II: $Y = \beta_0 + \beta_1 X + \beta_2 X^2 + \varepsilon$
- Model III: $Y = \beta_0 + \beta_1 X + \beta_2 X^2 + \beta_3 X^3 + \varepsilon$


```{r}
### Your Solution (Code)


```


(c) Calculate the leave-one-out-cross-validation mean squared error for each model I-III.

```{r}
### Your Solution (Code)


```


(d) Calculate the $k$-fold cross-validation mean squared error for each model I-III for $k=10.$


```{r}
### Your Solution (Code)


```



(e) Which model has the smallest cross-validation error based on your results in (c) and (d)? Briefly explain why.



(f) Explain the individual concepts and the relationship between the validation set approach, leave-one-out cross-validation and $k$-fold cross-validation in about 1/2 page (maximum one page).

\newpage

# 2. Ridge regression

ISLR2 Chapter 6, conceptual problem 4


