-
시계열 분석 시리즈 III (Time Series Features)카테고리 없음 2024. 3. 17. 22:13
시계열 데이터의 여러 특성 가시화시계열 데이터 특성(Features)
시계열 데이터의 특성과 통계처리를 위한 전문 패키지인 feasts가 개발되어 쉽게 시계열 데이터를 분석할 수 있게 되었다. feasts 패키지는 FEatures And Statistics from Time Series 약어이다.
참조 : https://feasts.tidyverts.org/reference/index.html
feasts 패키지는 시계열 데이터의 기본적인 통계량을 검출하고 시계열 데이터만의 고유한 특성 즉 자기상관, 성분 분해 등의 특징을 추출하고 가시화하는 강력한 패키지이다.기본 통계량
일반 데이터프레임이나, tibble의 경우 summary 함수를 이용해서 통계량을 한눈에 보면 되지만, tsibble 객체의 경우에는 Key의 조합별로 구분해서 시계열 데이터에 대한 각각의 통계량을 계산해야 한다. 다양한 시계열 객체가 포함된 tsibble 데이터의 통계량을 한꺼번에 보려면 features() 함수를 이용해야 한다. features() 함수의 파라미터로 출력할 value가 되는 수치
변수를 지정하고 list로 원하는 통계량의 종류를 기술하면 된다.
tourism 시계열 데이터의 여행객 수(Trips)에 대한 기본 통계량을 구해보자. tourism 데이터는 1998 Q1부터 2017년 Q4까지 20년간의 분기별(80개 분기) 호주 여행객 수에 대한 24,320건의 tsibble 객체이다. index는 Quarter, Key 변수는 Region, State, Purpose이다. 주별, 지역별, 여행 목적별로 304건(24,320/80 = 304)의 Unique 한 시계열 데이터들이 들어있다. tourism 데이터의 기본 통계량을 구한다는 의미는 Key 변수의 조합으로 이루어지는 304개 각각의 시계열 데이터의 통계량을 각각 구한다는 의미이다.tourism %>% features(Trips, list(mean = mean, sd=sd, quantile))
# A tibble: 304 × 10 Region State Purpose mean sd `0%` `25%` `50%` `75%` `100%` <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 Adelaide Sout… Busine… 156. 35.6 68.7 134. 153. 177. 242. 2 Adelaide Sout… Holiday 157. 27.1 108. 135. 154. 172. 224. 3 Adelaide Sout… Other 56.6 17.3 25.9 43.9 53.8 62.5 107. 4 Adelaide Sout… Visiti… 205. 32.5 137. 179. 206. 229. 270. 5 Adelaide Hil… Sout… Busine… 2.66 4.30 0 0 1.26 3.92 28.6 6 Adelaide Hil… Sout… Holiday 10.5 6.37 0 5.77 8.52 14.1 35.8 7 Adelaide Hil… Sout… Other 1.40 1.65 0 0 0.908 2.09 8.95 8 Adelaide Hil… Sout… Visiti… 14.2 10.7 0.778 8.91 12.2 16.8 81.1 9 Alice Springs Nort… Busine… 14.6 7.20 1.01 9.13 13.3 18.5 34.1 10 Alice Springs Nort… Holiday 31.9 18.1 2.81 16.9 31.5 44.8 76.5 # ℹ 294 more rows
통계량 출력 결과를 보면, 304개 행이 출력되었다. tourism 데이터 안에 304개의 고유한 시계열 데이터가 포함되어 있고, 각 시계열 데이터별로 지정한 평균, 표준편차와 분위수 통계량이 제시되었다.
아래는 tourism 데이터 중 원하는 특정 조건에 해당되는 통계량을 계산한 것이다. Region이 Adelaide이고 State가 남호주이며 여행목적이 Business인 여행객수에 대한 통계랑(평균, 표준편차, 분위수)은 아래와 같다.
tourism %>% filter(Region == "Adelaide" & State =="South Australia" & Purpose =="Business") %>% features(Trips, list(mean = mean, sd=sd, quantile))
# A tibble: 1 × 10 Region State Purpose mean sd `0%` `25%` `50%` `75%` `100%` <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 Adelaide South Australia Business 156. 35.6 68.7 134. 153. 177. 242.
ACF 특징
시계열 데이터의 가장 큰 특징 중 하나는 자기상관(Autocorrelation)이다. (자기상관의 개념과 관련한 내용은 시계열 시리즈 II편에 기술되어있다.) ACF 관련 특징을 확인하기 위해서는 feat_acf 함수를 사용한다. feat_acf() 함수는 시계열 데이터의 자기상관 패턴을 여러 가지 방법으로 요약하고 분석하는 데 사용한다. 자기상관을 요약하여 새로운 특성을 생성하기도 한다. 예를 들어, 시계열 데이터의 처음 열 개의 자기상관 계수 제곱 합은 시계열의 자기상관이 얼마나 되는지를 알 수 있는 유용한 요약값이 된다. ’차분’한 시계열을 만들고 그 차분된 시계열의 자기상관을 계산할 수도 있고, 차분된 시계열을 다시 차분(2중 차분)하여 계산된 자기상관은 유용한 정보를 제공할 수 있다.
계절성을 고려한 다른 관점의 접근방식도 가능하다. 예를 들어, 월별로 집계된 데이터가 있다면, 1월, 2월 이런식으로 연속되는 월이 아닌 매년 1월, 매년 2월끼리 차이를 계산하는 방식으로 계절간 비교를 할 수 있다. 이렇게 계절적으로 차분하면 시계열을 월별 차이가 아닌 계절간 차이의 변화를 살펴볼 수 있다.
feat_acf() 함수는 다음과 같은 6~7종의 ACF 관련 특징을 제공한다.- 원래 데이터의 첫 번째 자기상관 계수: 이는 시계열 데이터와 하나 지연된(Lag 1)된 데이터 간의 자기상관 계수이다.
\[ \rho_1 = \frac{\sum_{t=2}^{T} (y_t - \bar{y})(y_{t-1} - \bar{y})}{\sum_{t=1}^{T} (y_t - \bar{y})^2} \] - 원래 데이터의 처음 10개의 자기상관 계수의 제곱 합: 이는 시계열 데이터의 첫 10개의 자기상관 계수를 각각 제곱한 후, 그 결과를 모두 더하는 값이다.
\[ \sum_{k=1}^{10} \rho_k^2 \]
- 차분된 데이터의 첫 번째 자기상관 계수: 이는 차분된 시계열 데이터의 첫 번째 자기상관 계수를 계산한 것으로 수식은 원래 데이터의 첫 번째 자기상관 계수를 계산하는 수식과 동일하지만, \(y_t\) 대신 차분된 데이터를 사용하는 것이 다르다.
- 차분된 데이터의 첫 10개의 자기상관 계수의 제곱 합: 이는 차분된 시계열 데이터의 첫 10개의 자기상관 계수를 각각 제곱한 후, 그 결과를 모두 더한 것
- 두 번 차분된 데이터의 첫 번째 자기상관 계수: 이는 두 번 차분된 시계열 데이터의 첫 번째 자기상관 계수를 계산하는 것
- 두 번 차분된 데이터의 첫 10개의 자기상관 계수의 제곱 합: 두 번 차분된 시계열 데이터의 첫 10개의 자기상관 계수를 각각 제곱한 후, 그 결과를 모두 더하는 것이다.
- 계절 데이터의 경우, 첫 번째 계절적 지연에서의 자기상관 계수: 계절성을 갖는 시계열 데이터의 첫 번째 계절적 지연에 대한 자기상관 계수를 계산한 값이다. 데이터의 첫 번째 자기상관 계수를 계산하는 수식과 동일하지만, \(y_t\) 대신 계절적 지연을 고려한 데이터를 사용한다. 예륻 들어 index가 월인데 계절성이 년간으로 나타나면 \(t=12\)가 된다..
tourism %>% filter(Region == "Adelaide" & State =="South Australia" & Purpose == "Business") %>% # 특정 시계열에 대한 값만 발췌 features(Trips, feat_acf)
# A tibble: 1 × 10 Region State Purpose acf1 acf10 diff1_acf1 diff1_acf10 diff2_acf1 <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> 1 Adelaide South Austral… Busine… 0.0333 0.131 -0.520 0.463 -0.676 # ℹ 2 more variables: diff2_acf10 <dbl>, season_acf1 <dbl>
tourism %>% features(Trips, feat_acf) # 304종의 모든 시계열 데이터에 대한 features 값
# A tibble: 304 × 10 Region State Purpose acf1 acf10 diff1_acf1 diff1_acf10 diff2_acf1 <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> 1 Adelaide Sout… Busine… 0.0333 0.131 -0.520 0.463 -0.676 2 Adelaide Sout… Holiday 0.0456 0.372 -0.343 0.614 -0.487 3 Adelaide Sout… Other 0.517 1.15 -0.409 0.383 -0.675 4 Adelaide Sout… Visiti… 0.0684 0.294 -0.394 0.452 -0.518 5 Adelaide Hills Sout… Busine… 0.0709 0.134 -0.580 0.415 -0.750 6 Adelaide Hills Sout… Holiday 0.131 0.313 -0.536 0.500 -0.716 7 Adelaide Hills Sout… Other 0.261 0.330 -0.253 0.317 -0.457 8 Adelaide Hills Sout… Visiti… 0.139 0.117 -0.472 0.239 -0.626 9 Alice Springs Nort… Busine… 0.217 0.367 -0.500 0.381 -0.658 10 Alice Springs Nort… Holiday -0.00660 2.11 -0.153 2.11 -0.274 # ℹ 294 more rows # ℹ 2 more variables: diff2_acf10 <dbl>, season_acf1 <dbl>
STL 피처
시계열 데이터는 추세성분, 계절성분, 나머지 잔차 성분으로 구성되어 있으며 각 성분으로 분해할 수 있다.
\(y_{t} = T_{t} + S_{t} + R_{t}\) 여기서 \(T_{t}\)는 평활된 추세 성분, \(S_{t}\)는 계절 성분, 그리고 \(R_{t}\)는 잔차이다. 우리가 시계열 데이터에서 알고 싶은 것은 각 성분의 강도가 얼마 인가에 대한 정보이다. 시계열 데이터의 성분과 관련된 강도와 기타 정보를 확인하려면 feat_stl() 함수를 사용한다.
tourism %>% features(Trips, feat_stl) # stl 관련 특징을 추출
# A tibble: 304 × 12 Region State Purpose trend_strength seasonal_strength_year seasonal_peak_year <chr> <chr> <chr> <dbl> <dbl> <dbl> 1 Adela… Sout… Busine… 0.464 0.407 3 2 Adela… Sout… Holiday 0.554 0.619 1 3 Adela… Sout… Other 0.746 0.202 2 4 Adela… Sout… Visiti… 0.435 0.452 1 5 Adela… Sout… Busine… 0.464 0.179 3 6 Adela… Sout… Holiday 0.528 0.296 2 7 Adela… Sout… Other 0.593 0.404 2 8 Adela… Sout… Visiti… 0.488 0.254 0 9 Alice… Nort… Busine… 0.534 0.251 0 10 Alice… Nort… Holiday 0.381 0.832 3 # ℹ 294 more rows # ℹ 6 more variables: seasonal_trough_year <dbl>, spikiness <dbl>, # linearity <dbl>, curvature <dbl>, stl_e_acf1 <dbl>, stl_e_acf10 <dbl>
이러한 강도를 가시화 시켜 각 성분의 강도를 시각적으로 확인할 수 도 있다.
tourism %>% features(Trips, feat_stl) %>% ggplot(aes(x = trend_strength, y = seasonal_strength_year, col = Purpose)) + geom_point() + facet_wrap(vars(State))
이 그래프는 주별로 면을 분할을 하여 x축은 추세성의 강도, y축은 계절정의 강도를 여행 목적별 산점도를 그린 것이다. 계절성을 강하게 나타내는 것은 Holyday임을 알 수 있다. 계절별로 이동의 차이가 많은 것을 알 수 있다.
기타 시계열 데이터의 특성들
지금까지 살펴본 특징들 외에 시계열 데이터를 설명하는 다양한 지표들이 있다. 구체적인 내용은 https://otexts.com/fpp3/other-features.html 참조하면 된다. feast 패키지에 포함된 모든 특징들을 한꺼번에 출력하려면 다음과 같이 지정하면 된다.
tourism_features <- tourism %>% features(Trips, feature_set(pkgs = "feasts"))
Warning: `n_flat_spots()` was deprecated in feasts 0.1.5. ℹ Please use `longest_flat_spot()` instead. ℹ The deprecated feature was likely used in the fabletools package. Please report the issue at <https://github.com/tidyverts/fabletools/issues>. This warning is displayed once every 8 hours. Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.
tourism_features
# A tibble: 304 × 51 Region State Purpose trend_strength seasonal_strength_year seasonal_peak_year <chr> <chr> <chr> <dbl> <dbl> <dbl> 1 Adela… Sout… Busine… 0.464 0.407 3 2 Adela… Sout… Holiday 0.554 0.619 1 3 Adela… Sout… Other 0.746 0.202 2 4 Adela… Sout… Visiti… 0.435 0.452 1 5 Adela… Sout… Busine… 0.464 0.179 3 6 Adela… Sout… Holiday 0.528 0.296 2 7 Adela… Sout… Other 0.593 0.404 2 8 Adela… Sout… Visiti… 0.488 0.254 0 9 Alice… Nort… Busine… 0.534 0.251 0 10 Alice… Nort… Holiday 0.381 0.832 3 # ℹ 294 more rows # ℹ 45 more variables: seasonal_trough_year <dbl>, spikiness <dbl>, # linearity <dbl>, curvature <dbl>, stl_e_acf1 <dbl>, stl_e_acf10 <dbl>, # acf1 <dbl>, acf10 <dbl>, diff1_acf1 <dbl>, diff1_acf10 <dbl>, # diff2_acf1 <dbl>, diff2_acf10 <dbl>, season_acf1 <dbl>, pacf5 <dbl>, # diff1_pacf5 <dbl>, diff2_pacf5 <dbl>, season_pacf <dbl>, # zero_run_mean <dbl>, nonzero_squared_cv <dbl>, zero_start_prop <dbl>, …
이것을 가시화 시킨 플롯을 보자.
library(glue) tourism_features %>% select_at(vars(contains("season"), Purpose)) %>% # 6개변수 mutate( seasonal_peak_year = seasonal_peak_year + 4*(seasonal_peak_year==0), seasonal_trough_year = seasonal_trough_year + 4*(seasonal_trough_year==0), seasonal_peak_year = glue("Q{seasonal_peak_year}"), seasonal_trough_year = glue("Q{seasonal_trough_year}"), ) %>% GGally::ggpairs(mapping = aes(colour = Purpose))
Registered S3 method overwritten by 'GGally': method from +.gg ggplot2
`stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`. `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
시계열 데이터의 특성과 통계량을 파악하는 것은 데이터 분석의 EDA 과정이다. feasts 패키지는 시계열 데이터의 EDA와 가시화를 쉽게 할 수 있도록 도와 주며 tidyverse하게 처리하도록 디자인 되어있다.
- 원래 데이터의 첫 번째 자기상관 계수: 이는 시계열 데이터와 하나 지연된(Lag 1)된 데이터 간의 자기상관 계수이다.