ACAIT

[BDA 데분기] 10주차 - kaggle master 코드 분석 본문

학회 활동/BDA 7기(데이터 분석 기초반)

[BDA 데분기] 10주차 - kaggle master 코드 분석

831x99 2024. 1. 31. 23:19
  • kaggle에 있는 저수지에 대한 데이터.
  • kaggle에서 데이터 분석 내용 코드 가지고 와서 어떻게 분석했는지 확인하는 실습.
  • 시계열 데이터를 어떤 식으로 대체하고 확인하는지 캐글 전문가들의 코드를 보면서 인사이트 얻기 위한 것.
  • 이 인사이트를 가지고 전처리 준비하면 좋음.

  • 아래 코드는 line 그래프 하나씩 그리면서 어디에 문제 있는지, 어디를 대체해야 하는지 확인하고 있음.
  • 패턴과 결측치에 대해서 보간법으로 잡고, 해당 df에 결측값 없도록 처리했음.
  • 해당 분석은 daily, wikely, monthly, yearly 등으로 접근했음.
  • 출처: https://www.kaggle.com/code/iamleonie/intro-to-time-series-forecasting
 

Intro to Time Series Forecasting

Explore and run machine learning code with Kaggle Notebooks | Using data from Acea Smart Water Analytics

www.kaggle.com


# 리스트 컴프리헨션

  • 구조: [expression for item in iterable if condition]
  • expression: 각 아이템에 대한 결과 값
  • item: iterable에서 가져온 각 항목.
  • feature for feature in df.columns 부분에서 각 열 이름을 feature로 가져옴.
  • if feature not in targets 부분에서 현재 feature가 targets 리스트에 없는 경우만 해당 feature를 features 리스트에 포함.
  • 결론: targets 리스트에 'Depth_to_Groundwater'가 들어있고, 이를 제외한 나머지 열들을 features로 선택.


 

결측값에 관련된 데이터 코드

  • 보간법을 이용한 코드.
  • 시계열 데이터는 보간법 등으로 missing value 대체하면 좋다.


# .shift(periods = 1, freq = None, axis = 0, fill_value = NoDefault.no_default)

  • periods : 이동할 기간. axis 인수 설정 안 해 주면 행 방향으로 지정한 수만큼 값이 이동함.
  • freq : 입력 할 경우 인덱스가 이동. Y, M, D, H, T, S, Timestamp, 'Infer'등.
  • fill_value : shift로 인해 생긴 결측치를 대체할 값.


# Resample로 해당 데이터 월, 일, 연으로 데이터 확인.

 

# Stationarity Some time-series models, such as such as ARIMA, assume that the underlying data is stationary. Stationarity describes that the time-series has constant mean and mean is not time-dependent constant variance and variance is not time-dependent constant covariance and covariance is not time-dependent If a time series has a specific (stationary) behavior over a given time interval, then it can be assumed that the time series will behave the same at a later time. Time series with trend and/or seasonality are not stationary. Trend indicates that the mean is not constant over time and seasonality indicates that the variance is not constant over time.

 

# 정상성 ARIMA와 같은 일부 시계열 모델은 기본 데이터가 고정되어 있다고 가정합니다. 정상성은 시계열이 일정한 평균을 가지며 평균은 시간 종속 상수 분산이 아니며 분산은 시간 종속 상수 공분산이 아니며 공분산은 시간 종속이 아니라는 것을 설명합니다. 시계열이 주어진 시간에 대해 특정(정상) 동작을 갖는 경우 간격이 있으면 시계열이 나중에 동일하게 동작할 것이라고 가정할 수 있습니다. 추세 및/또는 계절성이 있는 시계열은 고정되어 있지 않습니다. 추세는 평균이 시간에 따라 일정하지 않음을 나타내고 계절성은 분산이 시간에 따라 일정하지 않음을 나타냅니다.

 


정상성과 비정상성 예시

 

# The check for stationarity can be done via three different approaches:

  • visually: plot time series and check for trends or seasonality
  • basic statistics: split time series and compare the mean and variance of each partition
  • statistical test: Augmented Dickey Fuller test Let's do the visual check first.

We can see that all features except Temperature have non-constant mean and non-constant variance. Therefore, none of these seem to be stationary. However, Temperature shows strong seasonality (hot in summer, cold in winter) and therefore it is not stationary either.

 

# 정상성 확인은 세 가지 접근 방식을 통해 수행할 수 있습니다.

  • 시각적으로: 시계열을 플롯하고 추세 또는 계절성을 확인합니다.
  • 기본 통계: 시계열을 분할하고 각 파티션의 평균과 분산을 비교합니다.
  • 통계 테스트: Augmented Dickey Fuller 테스트 먼저 시각적 확인을 해보겠습니다.

온도를 제외한 모든 특성은 평균이 일정하지 않고 분산이 일정하지 않음을 알 수 있습니다. 따라서 이들 중 어느 것도 고정되어 있지 않은 것 같습니다. 그러나 기온은 강한 계절성(여름에는 덥고 겨울에는 추운)을 나타내므로 일정하지 않습니다.


 

# .rolling(): pandas에서 제공하는 이동평균 함수.

  • 전체 데이터에 대한 평균, 최소/최대값 등을 알고 싶은 게 아니라 window 창이 이동하듯 x축의 창을 이동하면서 y값의 각 계산값을 알고 싶을 때.
  • default: pd.df.rolling(window, min_preiod=None, center=False, win_type=None, on=None, axis=0, closed=None)
  • window: 윈도우 크기.(ex. 30일에 대한 평균을 이동하면서 구할 때 = 30)
  • min_period: 윈도우 사이즈보다 데이터가 작을 때 NaN으로 표시할지, 최소한의 개수만 있으면 데이터를 처리할지.
  • mean(평균), min(최소값), max(최대값), sum(총합), median(중간값), std(표준편차) 계산 가능.

# Let's evaluate the histograms. Since we are looking at the mean and variance, we are expecting that the data conforms to a Gaussian distribution (bell shaped distribution) in case of stationarity.

 

# 히스토그램을 평가해 봅시다. 평균과 분산을 보고 있으므로 정상성의 경우 데이터가 가우스 분포(종 모양 분포)를 따를 것으로 기대합니다.


# Augmented Dickey-Fuller (ADF) test is a type of statistical test called a unit root test. Unit roots are a cause for non-stationarity.

  • Null Hypothesis (H0): Time series has a unit root. (Time series is not stationary).
  • Alternate Hypothesis (H1): Time series has no unit root (Time series is stationary).
  • If the null hypothesis can be rejected, we can conclude that the time series is stationary.
  • There are two ways to rejects the null hypothesis:
  • On the one hand, the null hypothesis can be rejected if the p-value is below a set significance level. The defaults significance level is 5%
  • p-value > significance level (default: 0.05): Fail to reject the null hypothesis (H0), the data has a unit root and is non-stationary. p-value <= significance level (default: 0.05): Reject the null hypothesis (H0), the data does not have a unit root and is stationary. On the other hand, the null hypothesis can be rejects if the test statistic is less than the critical value.
  • ADF statistic > critical value: Fail to reject the null hypothesis (H0), the data has a unit root and is non-stationary. ADF statistic < critical value: Reject the null hypothesis (H0), the data does not have a unit root and is stationary.

 

# ADF(Augmented Dickey-Fuller) 테스트는 단위근 테스트라고 불리는 통계 테스트의 한 유형입니다.

  단위근은 비정상성의 원인입니다.

  • - 귀무 가설(H0): 시계열에는 단위근이 있습니다. (시계열은 고정되어 있지 않습니다).
  • - 대체 가설(H1): 시계열에는 단위근이 없습니다(시계열은 고정되어 있습니다).
  • - 귀무가설이 기각될 수 있다면 시계열이 고정되어 있다는 결론을 내릴 수 있습니다.
  • - 귀무가설을 기각하는 방법에는 두 가지가 있습니다.
  • - 한편, p-값이 설정된 유의 수준보다 낮으면 귀무 가설이 기각될 수 있습니다. 기본 유의 수준은 5%입니다.
  • - p-값 > 유의 수준(기본값: 0.05): 귀무 가설(H0)을 기각하지 못하며 데이터에 단위근이 있고 고정적이지 않습니다. p-값 <= 유의 수준(기본값: 0.05): 귀무 가설(H0)을 기각합니다. 데이터에 단위근이 없으며 고정되어 있습니다. 반면, 검정 통계량이 임계값보다 작으면 귀무가설이 기각될 수 있습니다.
  • ADF 통계 > 임계값: 귀무 가설(H0)을 기각하지 못하며 데이터에 단위근이 있고 고정적이지 않습니다. ADF 통계 < 임계값: 귀무 가설(H0)을 기각합니다. 데이터에 단위근이 없으며 고정되어 있습니다.

- 코드 잘린 부분: ax.set_title(f'ADF Statistic {adf_stat:0.3f}, p-value: {p_val:0.3f}\nCritical Values 1%: {crit_val_1:0.3f}, 5%: {crit_val_5:0.3f}, 10%: {crit_val_10:0.3f}', fontsize = 14)


# If the data is not stationary but we want to use a model that requires with characteristic, the data has to be transformed. However, if the data is not stationary to begin with, we should rethink the choice of model.

The two most common methods to achieve stationarity are:

Transformation: e.g. log or square root to stabilize non-constant variance Differencing: subtracts the current value from the previous

 

# 데이터가 고정되어 있지 않지만 특성이 필요한 모델을 사용하려면 데이터를 변환해야 합니다. 그러나 데이터가 처음부터 고정적이지 않은 경우 모델 선택을 다시 생각해야 합니다.

정상성을 달성하는 가장 일반적인 두 가지 방법은 다음과 같습니다.

변환: 예. 일정하지 않은 분산을 안정화하기 위한 로그 또는 제곱근 차이(이전 값에서 현재 값 차감.)

 

# Differencing can be done in different orders:

First order differencing: linear trends with 𝑧𝑖=𝑦𝑖−𝑦𝑖−1

Second-order differencing: quadratic trends with 𝑧𝑖=(𝑦𝑖−𝑦𝑖−1)−(𝑦𝑖−1−𝑦𝑖−2)

and so on...

 

# 차이점은 다양한 순서로 수행할 수 있습니다.

1차 차분: 𝑧𝑖=𝑦𝑖−𝑦𝑖−1인 선형 추세

2차 차분: 𝑧𝑖=(𝑦𝑖−𝑦𝑖−1)−(𝑦𝑖−1−𝑦𝑖−2)을 사용한 2차 추세

등등...