시계열 데이터의 차분(difference)과 역차분(inverse difference)
시계열 모형은 데이터의 정상성이 요구됩니다. 정상성을 확보하기 위해 데이터의 차분(difference)이 적용됩니다. 차분된 데이터는 현재값에서 이전 값의 차를 사용이므로 원 데이터가 가질 수 있는 추세가 제거될 수 있습니다. 즉, 차분된 데이터의 경우 연속된 데이터들 사이의 자기상관이 최소화되므로 평균이나 분산등의 일정성이 유지되는 정상성(stationary)가 확보될 수 있습니다. 예를 들어 다음 샘플에 대해 차분을 실행합니다.
np.random.seed(3) x=pd.Series(np.random.randint(1, 11, 4)) x
0 9 1 10 2 4 3 9 dtype: int32
위 데이터 x의 차분은 다음과 같습니다. pandas객체.diff()
함수를 사용할 수 있습니다.
x1=x.diff() x1
0 NaN 1 1.0 2 -6.0 3 5.0 dtype: float64
위 과정은 1번 차분한 것으로 1차 차분이라합니다. 위 x1을 다시 차분하면 2번 차분, 즉 2차 차분이 됩니다.
$$\begin{align} -6 - 1=-7 \quad& x^1_2-x^1_1=x^2_2\\ 5-(-6) = 11\quad& x^1_3-x^1_2=x^2_3\\\ x^2_i :\quad&\text{2차 차분된 데이터}\end{align}$$x2=x.diff().diff() x2
0 NaN 1 NaN 2 -7.0 3 11.0 dtype: float64
위 과정을 정하면 다음과 같습니다.
$$\begin{align}\text{1st diff } \;y^1_t&=y_t-y_{t-1}\\ \text{2nd diff }\;y^2_t &= y^1_t -y^1_{t-1}\\ &=(y_t-y_{t-1})-(y_{t-1}-y_{t-2})\\&=y_t - 2y_{t-1}+y_{t-2}\end{align}$$위 차분한 결과로부터 원 데이터로 환원하는 과정을 역차분이라 합니다.
$$\begin{align} \text{1차 차분}\quad& x^1_h = x_h-x_{h-1}&\\ \rightarrow &x^1_h+x_{h-1}=x_h&\text{1차 역차분}\\ \\ \text{2차 차분}\quad& x^2_h = x_h-2x_{h-1} +x_{h-2}&\\\rightarrow &x^2_h+2x_{h-1}-x_{h-2}=x_h&\text{2차 역차분} \end{align}$$다음은 1차 차분된 데이터를 기반으로 역차분을 위한 사용자 정의 함수입니다.
def inverse_diff_1st(forcast, originalData): last_value=originalData.iloc[-1] result=[] for i in forcast: y_hat=i + last_value result.append(y_hat) last_value = y_hat return result
inverse_diff_1st(x1.iloc[1:], x.iloc[:1])
[10.0, 4.0, 9.0]
다음은 2차 차분된 데이터를 기반으로 역차분을 위한 사용자 정의 함수입니다.
def inverse_diff_2nd(forcast, originalData): last_value1=originalData.iloc[-2] last_value2=originalData.iloc[-1] result=[] for i in forcast: y_hat=i + 2*last_value2-last_value1 result.append(y_hat) last_value1=last_value2 last_value2 = y_hat return result
inverse_diff_2nd(x2.iloc[2:], x.iloc[:2])
[4.0, 9.0]
댓글
댓글 쓰기