시간에 따른 데이터 예측

Python으로 배우는 시계열 데이터 Machine Learning

Chris Holdgraf

Fellow, Berkeley Institute for Data Science

분류 vs. 회귀

Classification
classification_model.predict(X_test)
array([0, 1, 1, 0])
Regression
regression_model.predict(X_test)
array([0.2, 1.4, 3.6, 0.6])
Python으로 배우는 시계열 데이터 Machine Learning

상관관계와 회귀

  • 회귀는 상관관계 계산과 유사하지만 중요한 차이가 있음
    • 회귀: 데이터의 공식적인 모델을 생성하는 과정
    • 상관관계: 데이터를 설명하는 통계량. 회귀 모델보다 정보가 적음.
Python으로 배우는 시계열 데이터 Machine Learning

변수 간 상관관계는 시간에 따라 변함

  • 시계열에는 시간에 따라 변하는 패턴이 존재함
  • 한 시점에 상관된 것처럼 보이는 두 시계열도 시간이 지나면 그렇지 않을 수 있음
Python으로 배우는 시계열 데이터 Machine Learning

시계열 간 관계 시각화

fig, axs = plt.subplots(1, 2)

# Make a line plot for each timeseries
axs[0].plot(x, c='k', lw=3, alpha=.2)
axs[0].plot(y)
axs[0].set(xlabel='time', title='X values = time')

# Encode time as color in a scatterplot
axs[1].scatter(x_long, y_long, c=np.arange(len(x_long)), cmap='viridis')
axs[1].set(xlabel='x', ylabel='y', title='Color = time')
Python으로 배우는 시계열 데이터 Machine Learning

두 시계열 시각화

Python으로 배우는 시계열 데이터 Machine Learning

scikit-learn 회귀 모델

from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X, y)
model.predict(X)
Python으로 배우는 시계열 데이터 Machine Learning

scikit-learn으로 예측 시각화

alphas = [.1, 1e2, 1e3]
ax.plot(y_test, color='k', alpha=.3, lw=3)
for ii, alpha in enumerate(alphas):
    y_predicted = Ridge(alpha=alpha).fit(X_train, y_train).predict(X_test)
    ax.plot(y_predicted, c=cmap(ii / len(alphas)))
ax.legend(['True values', 'Model 1', 'Model 2', 'Model 3'])
ax.set(xlabel="Time")
Python으로 배우는 시계열 데이터 Machine Learning

scikit-learn으로 예측 시각화

Python으로 배우는 시계열 데이터 Machine Learning

회귀 모델 평가

  • 가장 일반적인 두 가지 방법:
    • 상관계수 ($r$)
    • 결정계수 ($R^2$)
Python으로 배우는 시계열 데이터 Machine Learning

결정계수 ($R^2$)

  • $R^2$의 최댓값은 1이며, 하한은 없음
  • 1에 가까울수록 모델의 예측 성능이 우수함

$$ 1 - \frac{error(model)}{variance(testdata)} $$

Python으로 배우는 시계열 데이터 Machine Learning

scikit-learn의 $R^2$

from sklearn.metrics import r2_score
print(r2_score(y_predicted, y_test))
0.08
Python으로 배우는 시계열 데이터 Machine Learning

연습해 봅시다!

Python으로 배우는 시계열 데이터 Machine Learning

Preparing Video For Download...