Skip to content

Commit

Permalink
chapter 1 update
Browse files Browse the repository at this point in the history
  • Loading branch information
issactoast committed Jan 23, 2022
1 parent a6f8fb2 commit 63f2dad
Show file tree
Hide file tree
Showing 24 changed files with 3,092 additions and 26 deletions.
106 changes: 102 additions & 4 deletions 01-intro-to-tsibble.Rmd
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
# 시계열 첫걸음, 관련 패키지의 이해 {#intro}

## `tsibble` 그리고 `fable` 패키지
## `tsibble`, `feasts` 그리고 `fable` 패키지

시계열과 관련 된 R 패키지는 정말 많이 있다. 그 중에서 가장 유명한 패키지는 `forecast` 패키지이다. `fpp` 2판에서 메인 패키지로 활용되었던 `forecast` 패키지는 예측성능이 좋기로 유명하다. 하지만 `forecast`는 base 패키지를 기반으로 짜여져있는 패키지라서 `fpp` 3판에서 사용하게 될 패키지는 `tsibble``fable` 패키지를 주로 사용하게 될 예정이다. 패키지 모두 `tidyverse`스러운 코딩과 잘 맞는 함수들을 지원하는 것이 특징이다.
시계열과 관련 된 R 패키지는 정말 많이 있다. 그 중에서 가장 유명한 패키지는 `forecast` 패키지이다. `fpp` 2판에서 메인 패키지로 활용되었던 `forecast` 패키지는 예측성능이 좋기로 유명하다. 하지만 `forecast`는 base 패키지를 기반으로 짜여져있는 패키지라서 `fpp` 3판에서 사용하게 될 패키지는 `tsibble``feasts`, 그리고 `fable` 패키지를 주로 사용하게 될 예정이다. 세가지 패키지 모두 `tidyverse`스러운 코딩과 잘 맞는 함수들을 지원하는 것이 특징이다.

```{block, type='rmdwarning'}
### 주의하기
`forecast` 패키지는 다른 언어를 사용하는 커뮤니티에도 알려질 정도로 잘 짜여진 패키지이다. 꼭 한번은 사용법을 알아둘 것을 추천한다. [`fpp` 2판의 한글판](https://otexts.com/fppkr/)을 봐두는 것도 나쁘지 않는 선택이다.
```

* `tsibble` 패키지는 `tidyverse`의 대표 객체인 `tibble`을 시계열 데이터를 잘 다룰수 있도록 조정한 `tsibble` 객체를 지원한다.

* `feasts` 패키지는 `Feature Extraction And Statistics for Time Series`의 줄임말로 시계열 데이터에서 특징을 뽑아내는데 사용된다. acf 함수라던지 lag 그래프를 그리는데에 사용된다.

* `fable`은 시계열 모델링에 관한 함수들이 모여져 있는 패키지이다. ARIMA, ETS와 같은 모델링 함수들을 가지고 있다.

## `fpp3` 패키지

`fpp3` 패키지는 Hyndman 교수와 Athanasopoulos 교수가 지은 Forecasting: principles and practice 3판에 딸림 R 패키지라고 생각하면 된다. `fpp3` 패키지를 로드시키면 앞에서 말했던 `tsibble``fable` 패키지가 같이 로드된다.
`fpp3` 패키지는 Hyndman 교수와 Athanasopoulos 교수가 지은 Forecasting: principles and practice 3판에 딸림 R 패키지라고 생각하면 된다. `fpp3` 패키지를 로드시키면 앞에서 말했던 `tsibble``feasts`, 그리고 `fable` 패키지가 같이 로드된다.

```{r message=TRUE}
library(fpp3)
Expand Down Expand Up @@ -189,4 +195,96 @@ prison %>%
y= "population")
```

dfsdfasdf
## Lag plots

다음은 Lag plots을 공부해보자. 이것을 이해하기 위해서는 먼저 Lag라는 것은 무엇인가를 이해해야 하는데, 사실 lag라는 단어는 대한민국 모든 사람이 알고 있는 단어이다. 왜냐하면 컴퓨터 렉 걸렸어! 라고 할 때 렉이 바로 영어로 lag이기 때문.

Lag는 뒤쳐지다라는 뜻인데, 어떤 시계열 벡터가 있을 때, 특정 시점을 기준으로 이전 시점을 가리킨다. 쉽게 생각해서 시차라고 생각해 볼 수 있다.

예를 들어, 다음과 같은 숫자들이 있다고 하자.

```{r echo=FALSE, results='asis'}
x <- cumsum(1:10)
glue::glue(str_c(x, collapse = ", "))
```

위의 숫자들을 시계열 벡터 `x`라고 할 때, `x` 벡터에 대응하는 `lag 1`, `lag 2` 벡터는 다음과 같다.

```{r}
x <- c(1,3,6,10,15,21,28,36,45,55)
lag_x_1 <- lag(x, n = 1)
lag_x_2 <- lag(x, n = 2)
```

```{r echo=FALSE}
lab_tab <- tibble(x = x, lag1 = lag_x_1, lag2 = lag_x_2)
kable(lab_tab, caption = "x에 대한 lag 1, lag 2 벡터") %>%
kableExtra::kable_styling(full_width = TRUE)
```

Lag 플랏은 시계열 벡터와 각 lag 값에 대응하는 벡터를 사용하여 산점도를 그려준다. 이 그래프를 사용하면 좋은 점은 데이터의 주기성을 다시 확인 할 수 있다는 점이다. 다음은 호주의 분기별 맥주 생산량 정보를 담고 있는 `aus_production` 데이터이다.

```{r echo=FALSE}
library(DT)
aus_production %>%
mutate(Quarter = as.Date(Quarter)) %>%
datatable(caption = '호주의 맥주 분기별 생산량')
```

lag plot은 다음과 같이 맥주 생산량 데이터의 계절성을 체크하는데 유용하게 사용할 수 있다. lag 4와 lag 8을 살펴보면 대각선을 따라서 점들이 분포하는 것을 알 수 있다. 반대로 lag 2와 lag 4의 경우에는 좌에서 우로 뻗어 내리는 대각선 형태로 점들이 분포한 것을 알 수 있다.

```{r}
aus_production %>%
janitor::clean_names() %>%
filter(year(quarter) >= 2000) %>%
gg_lag(beer, geom = "point") +
labs(x = "lag(Beer, k)")
```

슬기로운 통계생활에서 진행하는 [R을 사용한 기초 통계 수업](https://www.youtube.com/playlist?list=PLKtLBdGREmMnLbQnqGEfpCBtkGj2g_d-B) 을 충실히 이수한 분이라면 특정 lag에 따라서 상관계수의 절대값이 크게 나올 것이라는 생각을 할 수 있을 것이다. 이러한 현상과 관련이 있는 개념이 바로 시계열에서의 자기 상관성이다.

## Autocorrelation

기초 통계 시간에 배웠던 상관계수를 구하는 식을 살펴보자. 다음과 같이 $\underline{x}=\{x_1, x_2, ..., x_n\}$와 $\underline{y}=\{y_1, y_2, ..., y_n\}$의 $n$개의 표본이 주어졌을 때, 두 벡터의 표본 상관계수를 구하는 식은 다음과 같다.

$$
{\displaystyle r_{xy}={\frac {\sum _{i=1}^{n}(x_{i}-{\bar {x}})(y_{i}-{\bar {y}})}{{\sqrt {\sum _{i=1}^{n}(x_{i}-{\bar {x}})^{2}}}{\sqrt {\sum _{i=1}^{n}(y_{i}-{\bar {y}})^{2}}}}}}
$$

자기 상관성은 특정 lag 값에 대응하는 벡터와 자기 자신과의 상관계수를 측정한 값으로 이해할 수 있다. lag $k$에 대한 (표본) 자기 상관계수 $r_k$는 다음과 같이 계산 할 수 있다.

$$
r_{k}=\frac{\sum_{t=k+1}^{T}\left(x_{t}-\overline{x}\right)\left(x_{t-k}-\overline{x}\right)}{\sum_{t=1}^{T}\left(x_{t}-\overline{x}\right)^{2}}
$$

분자에 위치한 summation기호는 $k+1$ 부터 시작하고, 분모는 $1$부터 시작하는 것에 주의하자. 앞에서 정의한 `x` 벡터의 $r_2$를 계산하면 다음과 같다.

```{r}
# ACF 값 직접 구하기: r_2
sum((x - mean(x)) * (lag(x, n = 2) - mean(x)),
na.rm = TRUE) / (var(x) * (length(x) - 1))
```

위와 같은 자기 상관계수 값은 `k`값이 주어지면 값이 나오는 함수 형태로 볼 수 있다. 우리는 이것을 자기상관함수(autocorrelation function)라고 부른다. 자기상관함수 값은 `ACF` 함수를 사용해 다음과 같이 구할 수 있다.

```{r}
my_x <- tsibble(value = x,
time = 1:length(x),
index = time)
my_x %>%
ACF(value, lag_max = 9)
```

이론상으로 자기상관계수는 주어진 벡터의 길이보다 하나 작은 $n-1$ 시점까지 자기 상관계수를 구할 수 있는데, `autoplot()`은 이 값들을 각 시점마다 바차트 형태로 표현해 준다.

```{r}
my_x %>%
ACF(value, lag_max = 9) %>%
autoplot() +
labs(title = "x 벡터의 자기상관함수",
x = "Time lags",
y = "Autocorrelation function")
```

이러한 자기상관함수 그래프는 시계열 데이터의 특징을 파악하는데에 중요한 역할을 하게 된다. 또한 , 이러한 특성을 잘 잡아내기 때문에 ACF 함수의 형태를 기준으로 시계열 데이터를 분류하는데에도 사용된다.

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions _common.R
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ knitr::opts_chunk$set(
suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(fpp3))
suppressPackageStartupMessages(library(ggthemes))
suppressPackageStartupMessages(library(knitr))
theme_set(theme_igray())
Binary file modified bookdown.rds
Binary file not shown.
187 changes: 183 additions & 4 deletions docs/01-intro-to-tsibble.md

Large diffs are not rendered by default.

Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 3 additions & 2 deletions docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<meta name="author" content="슬기로운통계생활" />


<meta name="date" content="2022-01-16" />
<meta name="date" content="2022-01-22" />

<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
Expand Down Expand Up @@ -192,6 +192,7 @@
<li class="chapter" data-level="1.6" data-path="intro.html"><a href="intro.html#시계열-자료-구성-요소"><i class="fa fa-check"></i><b>1.6</b> 시계열 자료 구성 요소</a></li>
<li class="chapter" data-level="1.7" data-path="intro.html"><a href="intro.html#seasonal-plot"><i class="fa fa-check"></i><b>1.7</b> Seasonal plot</a></li>
<li class="chapter" data-level="1.8" data-path="intro.html"><a href="intro.html#scatter-plots"><i class="fa fa-check"></i><b>1.8</b> Scatter plots</a></li>
<li class="chapter" data-level="1.9" data-path="intro.html"><a href="intro.html#lag-plots"><i class="fa fa-check"></i><b>1.9</b> Lag plots</a></li>
</ul></li>
<li class="chapter" data-level="2" data-path="chap2.html"><a href="chap2.html"><i class="fa fa-check"></i><b>2</b> 시계열 분해의 이해</a>
<ul>
Expand Down Expand Up @@ -221,7 +222,7 @@ <h1>
<div id="header">
<h1 class="title">시계열 공략집 with R</h1>
<p class="author"><em><a href="https://www.youtube.com/c/statisticsplaybook">슬기로운통계생활</a></em></p>
<p class="date"><em>2022-01-16</em></p>
<p class="date"><em>2022-01-22</em></p>
</div>
<div id="들어가며" class="section level1 unnumbered">
<h1>들어가며</h1>
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
title: "시계열 공략집 with R"
author: "[슬기로운통계생활](https://www.youtube.com/c/statisticsplaybook)"
date: "2022-01-16"
date: "2022-01-22"
site: bookdown::bookdown_site
output: bookdown::gitbook
documentclass: book
Expand Down
Loading

0 comments on commit 63f2dad

Please sign in to comment.