본 포스팅은 파이토치 버전 1.11.0 이 깔려있다고 가정하고 진행한다.
Neural PROPHET 사용법¶
#필요한 라이브러리들
import time
import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
from neuralprophet import NeuralProphet #neural prophet 모델링에 필요한 패키지
# 패키지 버전 확인
!pip show neuralprophet
Name: neuralprophet Version: 0.3.2 Summary: Explainable Forecasting at Scale Home-page: https://github.com/ourownstory/neural_prophet Author: Oskar Triebe Author-email: trieb@stanford.edu License: MIT Location: c:\users\key10\anaconda3\lib\site-packages Requires: dataclasses, torch-lr-finder, convertdate, LunarCalendar, ipywidgets, numpy, pandas, tqdm, matplotlib, python-dateutil, holidays, torch Required-by:
# 패키지 버전 확인
print("torch version : 1.11.0")
torch version : 1.11.0
===============================================
Neural PROPHET 모형¶
===============================================
Facebook 에서 설명가능하고 사용하기 쉬운 user friendly 한 모형으로써 2021년에 제시됨.
후속 연구로써, AR-NET, Neural Prophet 등을 차례로 제시함. 각 논문들은 아래와 같음.
"Forecasting at Scale", (2018) --- Prophet 모형, pystan 기반
"AR-NET: A SIMPLE AUTO-REGRESSION NEURAL NETWORK FOR TIME SERIES", (2019) --- AR-Net 모형
"NeuralProphet: Explainable Forecasting at Scale", (2021) --- Neural Prophet 모형, PyTorch 기반
===============================================
Neural Prophet 모형은 아래와 같이 구성된다.¶
$y_{t} = T(t) + S(t) + E(t) + F(t) + A(t) + L(t) + \epsilon_{t}$.
T(t) : Trend at time t
S(t) : Seasonal effects at time t
E(t) : Event and holiday effects at time t
F(t) : Regression effects at time t for future-known exogenous variables
A(t) : Auto-regression effects at time t based on past observations
L(t) : Regression effects at time t for lagged observations of exogenous variables
$\epsilon_{t}$ : 모델로 설명이 안되는 shock
1. Neural PROPHET 모델링 (일간)¶
기본적으로 Neural Prophet 모형은 일간 예측을 가정으로 설계되어있다. 하지만 이 framework를 그대로 가지고 월간 예측에 적용가능하다. 먼저, 일간 예측을 진행해보자.
-데이터 전처리 (일간)¶
train = df.reset_index()
train.columns = ['ds','y']
train.head()
| ds | y | |
|---|---|---|
| 0 | 1989-01-03 | 3151.9 |
| 1 | 1989-01-04 | 3166.9 |
| 2 | 1989-01-05 | 3203.5 |
| 3 | 1989-01-06 | 3124.4 |
| 4 | 1989-01-09 | 3145.3 |
train.tail()
| ds | y | |
|---|---|---|
| 8401 | 2022-05-18 | 9262.0 |
| 8402 | 2022-05-19 | 9278.0 |
| 8403 | 2022-05-20 | 9461.0 |
| 8404 | 2022-05-23 | 9485.0 |
| 8405 | 2022-05-24 | 9437.0 |
↑ Neural Prophet 모델링에 사용하기 위해서 데이터프레임의 column 명을 'ds' 와 'y'로 바꿔주어야함.
from dateutil.relativedelta import relativedelta
sim_len = 12 # 향후 12일 예측이 목표
test = pd.DataFrame({"ds":[train.tail(1)['ds'].item() + relativedelta(days = i) for i in range(1,sim_len+2,1)],
"y":[100]*(sim_len+1)}) #예측하고자 하는 날짜가 들어있는 데이터프레임, 하루를 더 여유분으로 만들어주어야 한다. (패키지 버그)
total = pd.concat([train,test])
total = total.reset_index()
total = total.drop("index",axis=1)
#df_train, df_test = total_df.head(len(total_df)-sim_len), total_df.tail(sim_len)
↑ 전망하고자 하는 일수인 sim_len을 정의한다. 모델 학습에 사용할 데이터인 train, 전망하고자 하는 날짜들이 들어있는 test, 그 둘을 합친 total 데이터프레임을 미리 만들어둔다. test기간 동안의 y값은 알 수 없으므로, 임의의 값인 100으로 채워둔다. test 데이터프레임은 모델훈련에 사용되지 않는다.
# holiday 날짜 설정
holiday1 = pd.DataFrame({
'event': 'holiday1',
'ds': pd.to_datetime([str(i)+'-01-01' for i in range(1989,2023)]),
})
holiday2 = pd.DataFrame({
'event': 'holiday2',
'ds': pd.to_datetime([str(i)+'-12-25' for i in range(1989,2023)]),
})
events_df = pd.concat((holiday1, holiday2))
#events_df = events_df[['ds','event']]
events_df.head(3)
| event | ds | |
|---|---|---|
| 0 | holiday1 | 1989-01-01 |
| 1 | holiday1 | 1990-01-01 |
| 2 | holiday1 | 1991-01-01 |
↑ Neural Prophet 모형은 holiday 반영이 가능하다. 위에서는 holiday1, holiday2를 매년 1월 1일, 12월 25일로 각각 설정해보았다. 이들을 Neural Prophet 모델에 반영하기 위해서는 events_df 라는 데이터프레임을 위와 같은 형식으로 만들어주어야한다.
nprophet = NeuralProphet(
#trend
growth='linear',
n_changepoints = 10,
changepoints_range = 0.9,
trend_reg = 0,
trend_reg_threshold = False,
#seasonality
yearly_seasonality=True,
weekly_seasonality=True,
daily_seasonality=False,
seasonality_mode = 'additive',
seasonality_reg = 0,
#AR
n_lags=36,
ar_reg = 0.1,
#deep
num_hidden_layers = 3,
d_hidden = 32,
#model architecture, optimizer
n_forecasts = sim_len,
learning_rate = 0.003,
epochs = None,
batch_size = None,
loss_func = 'Huber',
optimizer = 'AdamW'
)
nprophet.add_seasonality(name='monthly',period=30.5,fourier_order=5) #주기가 30.5일인 seasonality 가정. 푸리에 차수는 5로 설정.
nprophet = nprophet.add_events(["holiday1"], lower_window=-1, upper_window=1) #holiday1 근처 앞뒤 1일간을 hoiday 영향 기간으로 설정.
nprophet = nprophet.add_events(["holiday2"], lower_window=-1, upper_window=1) #holiday2 근처 앞뒤 1일간을 hoiday 영향 기간으로 설정.
↑ NeuralProphet 모델 정의. 각 인자별 설명은 제일 아래에 따로 설명하였음.
# create the data df with events
history_df = nprophet.create_df_with_events(total, events_df)
↑ 모델의 input으로 사용할 데이터프레임을 만든다. (holiday 포함, train, test set 포함)
new_train, new_test = history_df.head(len(history_df)-sim_len-1), history_df.tail(sim_len+1)
↑ history_df 기준으로 train, test set 재정의
new_train.head()
| ds | y | holiday1 | holiday2 | |
|---|---|---|---|---|
| 0 | 1989-01-03 | 3151.9 | 0.0 | 0.0 |
| 1 | 1989-01-04 | 3166.9 | 0.0 | 0.0 |
| 2 | 1989-01-05 | 3203.5 | 0.0 | 0.0 |
| 3 | 1989-01-06 | 3124.4 | 0.0 | 0.0 |
| 4 | 1989-01-09 | 3145.3 | 0.0 | 0.0 |
new_train.tail()
| ds | y | holiday1 | holiday2 | |
|---|---|---|---|---|
| 8401 | 2022-05-18 | 9262.0 | 0.0 | 0.0 |
| 8402 | 2022-05-19 | 9278.0 | 0.0 | 0.0 |
| 8403 | 2022-05-20 | 9461.0 | 0.0 | 0.0 |
| 8404 | 2022-05-23 | 9485.0 | 0.0 | 0.0 |
| 8405 | 2022-05-24 | 9437.0 | 0.0 | 0.0 |
new_test
| ds | y | holiday1 | holiday2 | |
|---|---|---|---|---|
| 8406 | 2022-05-25 | 100.0 | 0.0 | 0.0 |
| 8407 | 2022-05-26 | 100.0 | 0.0 | 0.0 |
| 8408 | 2022-05-27 | 100.0 | 0.0 | 0.0 |
| 8409 | 2022-05-28 | 100.0 | 0.0 | 0.0 |
| 8410 | 2022-05-29 | 100.0 | 0.0 | 0.0 |
| 8411 | 2022-05-30 | 100.0 | 0.0 | 0.0 |
| 8412 | 2022-05-31 | 100.0 | 0.0 | 0.0 |
| 8413 | 2022-06-01 | 100.0 | 0.0 | 0.0 |
| 8414 | 2022-06-02 | 100.0 | 0.0 | 0.0 |
| 8415 | 2022-06-03 | 100.0 | 0.0 | 0.0 |
| 8416 | 2022-06-04 | 100.0 | 0.0 | 0.0 |
| 8417 | 2022-06-05 | 100.0 | 0.0 | 0.0 |
| 8418 | 2022-06-06 | 100.0 | 0.0 | 0.0 |
new_train['ds'][len(new_train)-1] #데이터의 가장 최근 날짜
Timestamp('2022-05-24 00:00:00')
new_train['ds'][len(new_train)-1]-new_train['ds'][0] #total days = 12194 days + 1 day(start date)
Timedelta('12194 days 00:00:00')
len(new_train) #observed days
8406
12195-8406 #unobserved days
3789
↑ 1989년 1월 3일 ~ 2022년 5월 20일의 일수는 총 12191일인데 주말,휴장일 등을 제외한 일수는 8404일임. 즉, 일간 데이터 기준으로 3787일의 NaN이 있는것으로 볼수도 있음.
-모델 fitting (일간)¶
metrics = nprophet.fit(new_train, freq="D")
INFO - (NP.forecaster.__handle_missing_data) - 3789 missing dates added. INFO:NP.forecaster:3789 missing dates added. INFO - (NP.forecaster.__handle_missing_data) - 3789 NaN values in column y were auto-imputed. INFO:NP.forecaster:3789 NaN values in column y were auto-imputed. INFO - (NP.forecaster.__handle_missing_data) - 3789 NaN values in column holiday1 were auto-imputed. INFO:NP.forecaster:3789 NaN values in column holiday1 were auto-imputed. INFO - (NP.forecaster.__handle_missing_data) - 3789 NaN values in column holiday2 were auto-imputed. INFO:NP.forecaster:3789 NaN values in column holiday2 were auto-imputed. Epoch[98/98]: 100%|███████| 98/98 [00:58<00:00, 1.68it/s, SmoothL1Loss=0.000205, MAE=97.7, RMSE=155, RegLoss=0.000397]
↑ 모델 fitting시에 위에서 정의했던 hoilday를 포함하는 new_train이 input으로 들어가게 됨. Model fitting 과정에서 3787개의 NaN이 적절히 Imputation 됨.
-미래 예측 (일간)¶
forecast = nprophet.predict(history_df)
INFO - (NP.forecaster.__handle_missing_data) - 3789 missing dates added. INFO:NP.forecaster:3789 missing dates added. INFO - (NP.forecaster.__handle_missing_data) - 3789 NaN values in column y were auto-imputed. INFO:NP.forecaster:3789 NaN values in column y were auto-imputed. INFO - (NP.forecaster.__handle_missing_data) - 3789 NaN values in column holiday1 were auto-imputed. INFO:NP.forecaster:3789 NaN values in column holiday1 were auto-imputed. INFO - (NP.forecaster.__handle_missing_data) - 3789 NaN values in column holiday2 were auto-imputed. INFO:NP.forecaster:3789 NaN values in column holiday2 were auto-imputed.
↑ Forecasting 시에는 input으로 train set과 test set이 합쳐진 history_df가 들어가게 된다.(holiday포함)
compare_vec = forecast.tail(sim_len+1) #패키지의 문제상 하루 더 길게 뽑아야함.
temp2 = []
for k in range(sim_len):
temp2.append(np.array(compare_vec['yhat'+str(k+1)])[k])
temp2 = list(np.array(temp2))
print(temp2) #향후 12일 예측값들이 들어있는 벡터
[9286.7890625, 9281.521484375, 9358.365234375, 9362.3349609375, 9301.9873046875, 9315.982421875, 9366.986328125, 9418.7626953125, 9348.046875, 9407.4111328125, 9399.314453125, 9353.724609375]
-모델 시각화 (일간)¶
## plotting parameters
fig_param = nprophet.plot_parameters()
↑ Neural Prophet 모형이 트렌드, holiday, seasonality, AR를 어떻게 잡아내고 있는지를 시각화함.
new_test['y'] = pd.Series(temp2)
df1 = new_test[['ds','y']]
df2 = new_train[['ds','y']]
df2 = df2[8000:]
df1 = df1.reset_index()
df1 = df1.drop('index',axis=1)
df1['y'] = pd.Series(temp2)
df1 = df1.drop(12)
from matplotlib import pyplot as plt
plt.figure(figsize=(20,5))
plt.title("time series of y (daily)", fontsize=15)
plt.plot(df2["ds"], df2["y"], "-", color='grey', label='cu')
plt.plot(df1['ds'],df1['y'], "-", color='blue', label='cu_forecast(neural prophet)')
plt.grid()
plt.legend(fontsize=13)
plt.xticks(rotation=90)
plt.show() #향후 12일 예측 시각화
2. Neural PROPHET 모델링 (월간)¶
월간 예측을 하기 위해서 먼저, 데이터를 월간 평균으로 resampling 하자.
-데이터 전처리 (월간)¶
train = df.reset_index()
train.columns = ['ds','y']
train.head()
| ds | y | |
|---|---|---|
| 0 | 1989-01-01 | 3170.352381 |
| 1 | 1989-02-01 | 2910.155000 |
| 2 | 1989-03-01 | 3045.557143 |
| 3 | 1989-04-01 | 2963.680000 |
| 4 | 1989-05-01 | 2708.119048 |
train.tail()
| ds | y | |
|---|---|---|
| 396 | 2022-01-01 | 9748.400000 |
| 397 | 2022-02-01 | 9895.200000 |
| 398 | 2022-03-01 | 10245.652174 |
| 399 | 2022-04-01 | 10194.631579 |
| 400 | 2022-05-01 | 9339.187500 |
import datetime
from dateutil.relativedelta import relativedelta
def to_date(date_in, date_form = "%Y-%m-%d"):
"""
datetime.datetime()이나 str을 datetime.date()화
"""
if type(date_in) == str and len(date_in.split("-")) == 3:
return(datetime.datetime.strptime(date_in, date_form).date())
else:
try:
return(date_in.date())
except:
return(date_in)
train['ds'] = pd.Series([to_date('2000-01-01') + relativedelta(days=x) for x in range(len(train))])
train.head(10)
| ds | y | |
|---|---|---|
| 0 | 2000-01-01 | 3170.352381 |
| 1 | 2000-01-02 | 2910.155000 |
| 2 | 2000-01-03 | 3045.557143 |
| 3 | 2000-01-04 | 2963.680000 |
| 4 | 2000-01-05 | 2708.119048 |
| 5 | 2000-01-06 | 2493.854545 |
| 6 | 2000-01-07 | 2434.495238 |
| 7 | 2000-01-08 | 2694.845455 |
| 8 | 2000-01-09 | 2830.785714 |
| 9 | 2000-01-10 | 2798.172727 |
↑ 월간 시계열을 neuralprophet 패키지가 일간 시계열로 인식하도록 날짜 형식만 바꿔주자. 이는 시계열의 순서를 흩트려 놓지 않는다는 점에서 Neural Prophet모형의 기본 원리에 벗어나지 않는다. 단지 인덱스만 "월간 인덱스"에서 "일간 인덱스"로 변환한 것이므로 모델링에는 영향이 없다고 볼 수 있다. 또한 Neural Prophet 모델링에 사용하기 위해서 데이터프레임의 column 명을 'ds' 와 'y'로 바꿔주어야함.
from dateutil.relativedelta import relativedelta
sim_len = 12 # 12개월 전망이 목표
test = pd.DataFrame({"ds":[train.tail(1)['ds'].item() + relativedelta(days = i) for i in range(1,sim_len+2,1)],
"y":[100]*(sim_len+1)}) #예측하고자 하는 날짜가 들어있는 데이터프레임, 하루를 더 여유분으로 만들어주어야 한다. (패키지 버그)
total = pd.concat([train,test])
total = total.reset_index()
total = total.drop("index",axis=1)
#df_train, df_test = total_df.head(len(total_df)-sim_len), total_df.tail(sim_len)
↑ 전망하고자 하는 일수인 sim_len을 정의한다. 모델 학습에 사용할 데이터인 train, 전망하고자 하는 날짜들이 들어있는 test, 그 둘을 합친 total 데이터프레임을 미리 만들어둔다. test기간 동안의 y값은 알 수 없으므로, 임의의 값인 100으로 채워둔다. test 데이터프레임은 모델훈련에 사용되지 않는다.
nprophet = NeuralProphet(
#trend
growth='linear',
n_changepoints = 10,
changepoints_range = 0.9,
trend_reg = 0,
trend_reg_threshold = False,
#seasonality
yearly_seasonality=False,
weekly_seasonality=False,
daily_seasonality=False,
seasonality_mode = 'additive',
seasonality_reg = 0,
#AR
n_lags=36,
ar_reg = 0.1,
#deep
num_hidden_layers = 3,
d_hidden = 32,
#model architecture, optimizer
n_forecasts = sim_len,
learning_rate = 0.003,
epochs = None,
batch_size = None,
loss_func = 'Huber',
optimizer = 'AdamW'
)
nprophet.add_seasonality(name='year',period=12,fourier_order=5) #주기가 12인 (연간)seasonality 가정. 푸리에 차수는 5로 설정.
#nprophet = nprophet.add_events(["holiday1"], lower_window=-1, upper_window=1) #월간 모델이므로, holday는 우선 배제함.
#nprophet = nprophet.add_events(["holiday2"], lower_window=-1, upper_window=1)
<neuralprophet.forecaster.NeuralProphet at 0x1765f7726a0>
↑ NeuralProphet 모델 정의. 각 인자별 설명은 제일 아래에 따로 설명하였음.
train.head()
| ds | y | |
|---|---|---|
| 0 | 2000-01-01 | 3170.352381 |
| 1 | 2000-01-02 | 2910.155000 |
| 2 | 2000-01-03 | 3045.557143 |
| 3 | 2000-01-04 | 2963.680000 |
| 4 | 2000-01-05 | 2708.119048 |
train.tail()
| ds | y | |
|---|---|---|
| 396 | 2001-01-31 | 9748.400000 |
| 397 | 2001-02-01 | 9895.200000 |
| 398 | 2001-02-02 | 10245.652174 |
| 399 | 2001-02-03 | 10194.631579 |
| 400 | 2001-02-04 | 9339.187500 |
test
| ds | y | |
|---|---|---|
| 0 | 2001-02-05 | 100 |
| 1 | 2001-02-06 | 100 |
| 2 | 2001-02-07 | 100 |
| 3 | 2001-02-08 | 100 |
| 4 | 2001-02-09 | 100 |
| 5 | 2001-02-10 | 100 |
| 6 | 2001-02-11 | 100 |
| 7 | 2001-02-12 | 100 |
| 8 | 2001-02-13 | 100 |
| 9 | 2001-02-14 | 100 |
| 10 | 2001-02-15 | 100 |
| 11 | 2001-02-16 | 100 |
| 12 | 2001-02-17 | 100 |
↑ 위 train과 test의 'ds' 변수는 실제 날짜가 아닌 단지 월간 데이터의 순서를 표현하기 위해 가공된 날짜를 나타냄.
-모델 fitting (월간)¶
metrics = nprophet.fit(train, freq="D")
Epoch[282/282]: 100%|█████| 282/282 [00:15<00:00, 18.80it/s, SmoothL1Loss=0.000872, MAE=241, RMSE=318, RegLoss=0.00072]
-미래 예측 (월간)¶
forecast = nprophet.predict(total)
↑ Forecasting 시에는 input으로 train set과 test set이 합쳐진 total_df가 들어가게 된다.(holiday 미포함)
compare_vec = forecast.tail(sim_len+1) #패키지의 문제상 하루 더 길게 뽑아야함.
temp2 = []
for k in range(sim_len):
temp2.append(np.array(compare_vec['yhat'+str(k+1)])[k])
temp2 = list(np.array(temp2))
print(temp2) #향후 12개월 예측값들이 들어있는 벡터
[10247.2216796875, 10015.984375, 9760.650390625, 10086.994140625, 10369.490234375, 9838.2783203125, 10250.3564453125, 10161.8134765625, 10168.8076171875, 9905.34765625, 10347.9208984375, 9988.51953125]
-모델 시각화 (월간)¶
## plotting parameters
fig_param = nprophet.plot_parameters()
↑ Neural Prophet 모형이 트렌드, holiday, seasonality, AR를 어떻게 잡아내고 있는지를 시각화함.
test['y'] = pd.Series(temp2)
df1 = test[['ds','y']]
df2 = train[['ds','y']]
list(df.reset_index()['date'])[-1]+relativedelta(months=1)
Timestamp('2022-06-01 00:00:00')
start1 = list(df.reset_index()['date'])[-1]+relativedelta(months=1)
start2 = df.reset_index()['date'][0]
df1 = df1.reset_index()
df1 = df1.drop('index',axis=1)
df1['y'] = pd.Series(temp2)
df1['ds'] = pd.Series([start1 + relativedelta(months=i) for i in range(len(df1))]) #날짜를 원래 상태로 변환
df2['ds'] = pd.Series([start2 + relativedelta(months=i) for i in range(len(df2))])
df1 = df1.drop(12)
df1 #향후 12개월 예측값들
| ds | y | |
|---|---|---|
| 0 | 2022-06-01 | 10247.221680 |
| 1 | 2022-07-01 | 10015.984375 |
| 2 | 2022-08-01 | 9760.650391 |
| 3 | 2022-09-01 | 10086.994141 |
| 4 | 2022-10-01 | 10369.490234 |
| 5 | 2022-11-01 | 9838.278320 |
| 6 | 2022-12-01 | 10250.356445 |
| 7 | 2023-01-01 | 10161.813477 |
| 8 | 2023-02-01 | 10168.807617 |
| 9 | 2023-03-01 | 9905.347656 |
| 10 | 2023-04-01 | 10347.920898 |
| 11 | 2023-05-01 | 9988.519531 |
df2.head() #훈련데이터
| ds | y | |
|---|---|---|
| 0 | 1989-01-01 | 3170.352381 |
| 1 | 1989-02-01 | 2910.155000 |
| 2 | 1989-03-01 | 3045.557143 |
| 3 | 1989-04-01 | 2963.680000 |
| 4 | 1989-05-01 | 2708.119048 |
df2.tail() #훈련데이터
| ds | y | |
|---|---|---|
| 396 | 2022-01-01 | 9748.400000 |
| 397 | 2022-02-01 | 9895.200000 |
| 398 | 2022-03-01 | 10245.652174 |
| 399 | 2022-04-01 | 10194.631579 |
| 400 | 2022-05-01 | 9339.187500 |
df2 = df2[200:]
from matplotlib import pyplot as plt
plt.figure(figsize=(20,5))
plt.title("time series of y (monthly)", fontsize=15)
plt.plot(df2["ds"], df2["y"], "-", color='grey', label='cu')
plt.plot(df1['ds'],df1['y'], "-", color='blue', label='cu_forecast(neural prophet)')
plt.grid()
plt.legend(fontsize=13)
plt.xticks(rotation=90)
plt.show() #향후 12개월 예측 시각화
3. Neural PROPHET 파라미터 설명 (상세)¶
nprophet = NeuralProphet(
#trend
growth='linear',
changepoints = None,
n_changepoints = 10,
changepoints_range = 0.9,
trend_reg = 0,
trend_reg_threshold = False,
#seasonality
yearly_seasonality=True,
weekly_seasonality=True,
daily_seasonality=False,
seasonality_mode = 'additive',
seasonality_reg = 0,
#AR
n_lags=36,
ar_reg = 0.1,
#deep
num_hidden_layers = 3,
d_hidden = 32,
#model architecture, optimizer
n_forecasts = sim_len,
learning_rate = 0.003,
epochs = None,
batch_size = None,
loss_func = 'Huber',
optimizer = 'AdamW'
)
nprophet.add_seasonality(name='monthly',period=30.5,fourier_order=5) #주기가 30.5일인 seasonality 가정. 푸리에 차수는 5로 설정.
nprophet = nprophet.add_events(["holiday1"], lower_window=-1, upper_window=1) #holiday1 근처 앞뒤 1일간을 hoiday 영향 기간으로 설정.
nprophet = nprophet.add_events(["holiday2"], lower_window=-1, upper_window=1) #holiday2 근처 앞뒤 1일간을 hoiday 영향 기간으로 설정.
↑ Neural Prophet() 함수에서 각 인자들의 뜻은 아래와 같다.
Trend¶
growth : trend의 함수를 정의. 선형('linear') 또는 트렌드 없음('off') 중 선택 가능
changepoints : change point들을 직접 설정가능함. 리스트 형태. ex) changepoints = ['2020-01-01']
n_changepoints : change point의 개수 (클수록 모델이 유연해지므로 overfitting의 위험 존재)
changepoints_range : 전체 기간 중 change point가 발생할 범위 (0~1 사이의 값, 즉 전체의 몇퍼센트에서 change point가 발생할 수 있는지 설정)
trend_reg : trend의 regularity를 설정. 클수록 underfitting.
trend_reg_threshold : True or False 값. 설정 시, 몇몇 trend에는 regularization 적용 안하게 됨.
Seasonality¶
yearly_seasonality : 연간 계절성 반영 유무 (True/False)
weekly_seasonality : 주간 계절성 반영 유무 (True/False)
daily_seasonality : 일간 계절성 반영 유무 (True/False)
seasonality_mode : 계절성을 트렌드에 더한 형태로 표현할지, 곱한 형태로 표현할지 결정 ('additive', 'multiplicative')
seasonality_reg : 계절성의 regularity를 설정. 클수록 underfitting.
AR¶
n_lags : 과거 몇 시점 까지를 AR 성분에 반영할지 설정. (rule of thumb : n_forecasts의 두배. 논문 참조)
ar_reg : ar성분의 regularity를 설정. 클수록 underfitting. neural prophet의 중요한 파라미터 중 하나.
Deep¶
num_hidden_layers : 딥러닝 모델의 은닉층의 개수.
d_hidden : 딥러닝 모델의 각 은닉층의 뉴런의 개수.
model architecture, optimizer¶
n_forecasts : 딥러닝 모델의 output의 차원.
learning_rate : 딥러닝 모델 학습 시 필요한 하이퍼파라미터. (미세 조정 없이, heuristic algorithm에 의해 결정할 수 있음. 논문 참조)
epochs : 딥러닝 모델 학습 시 필요한 하이퍼파라미터. (미세 조정 없이, heuristic algorithm에 의해 결정할 수 있음. 논문 참조)
batch_size : 딥러닝 모델 학습 시 필요한 하이퍼파라미터. (미세 조정 없이, heuristic algorithm에 의해 결정할 수 있음. 논문 참조)
loss_func : 딥러닝 모델 학습 시 필요한 목적 함수. 'Huber', 'MSE', 'MAE' 제공.
optimizer = 딥러닝 모델 학습 시 필요한 optimizer 방법. 'AdamW' 제공.
customized seasonality, holiday¶
nprophet.add_seasonality(name=a,period=b,fourier_order=c) : 계절성의 주기를 b로 하고 푸리에 차수는 c로 하는 계절성을 반영. 본 계절성의 이름을 a로 명명. (푸리에 차수가 클수록 유연)
nprophet = nprophet.add_events(["holiday1"], lower_window=-1, upper_window=1) : holiday1 근처 앞뒤 1일간을 hoiday 영향 기간으로 설정.
4. Neural Prophet 모델링의 장단점¶
장점: 시계열이 Trend, 계절효과(seasonality), 휴일효과(holidays)로 이루어져 있다는 직관적인 Prophet 모형의 가정과 잔차들간의 종속성을 확률적으로 표현하는 AR 모형의 가정을 합친 모형 (즉, AR_NET + PROPHET). Prophet 모형의 장점을 가져가면서 AR 모형의 장점도 가져오면서 prophet 모형보다 좀 더 robust한 모형이 될 수 있음. 딥러닝 모델에 필요한 튜닝파라미터들 (learning rate, batch size 등) 을 어느정도 알고리즘에 의해 정해두어서 사용자가 사용하기에 편함.¶
단점 : 딥러닝 모델의 특성상 시간이 다소 오래 걸릴 수 있음. Prophet 모형처럼 Uncertainty Plot이 나오지 않음. (Facebook에 의하면 GPU 가속화 및 Uncertainty plot을 추후 버전에서 제공할 예정이라고 함. )¶
'데이터 사이언스 > 머신러닝 & AI' 카테고리의 다른 글
| 크로스엔트로피와 최대가능도추정량(MLE)간의 관계 (0) | 2022.08.17 |
|---|---|
| 엔트로피, 크로스엔트로피, 쿨벡라이블러 다이버전스 (0) | 2022.08.15 |
| 딥러닝과 머신러닝, 그리고 모수적 방법과 비모수적 방법이란 ? (0) | 2022.08.15 |
| 비선형 모델 및 머신러닝에 대하여 (feat. 튜닝) (0) | 2022.08.05 |
| [NLP] Character based tokenization (0) | 2022.06.13 |