y
, covariate x
, intervention 이전 기간인 pre-period
, intervention에 영향 받은 기간인 post-period
check needed
데이터 평활에 사용되는 ?Kalman Filter(칼만 필터 방법) : 변동성 및 측정 오차의 조합으로 시계열 과정을 모델링하여 데이터를 평활함. 칼만필터와 뢰스는 시간의 전후데이터를 모두 고려하여 과거로 정보가 유출될 수 있음" 과는 다른 내용인가?
Beyesian 베이지안 VS Frequentism 빈도론
1. 빈도론
- 경험적 사실만을 중시하기 때문에 확률의 정의를 아래와 같이 내림
- 사건이 일어나는 장기적인 확률
- 베이지안
- 알고 있는 사전 지식을 활용해서 우리가 알고 싶은 확률을 추정
- 지식이나 판단의 정도를 나타내는 수단
ex. 주사위를 던져 1이 나올 확률은 1/6
현실적으로 모든 사건을 경험에 입각하여 결론을 예측할 수 없다는 한계를 가지기 때문에, Bayesian Decision Rule을 사용하여 확률을 추론
Covariate 공변량
분석의 주요 목적은 독립변수들이 종속변수에 얼마나 많은 영향을 끼치는가
그러나 잡음 인자가 존재하면 그 영향을 정확히 파악하기 힘듦
이 부분을 제거하기 위한 방법이 Covariate. Covariate란 종속변수에 대하여 독립변수와 기타 잡음인자들이 공유하는 변량을 의미
즉, 종속변수에 독립변수 이외의 기타 잡음인자들이 영향을 줄 수 없도록 통제하고자 하는 변수가 CovariateExample
특정 마케팅 캠페인이 '수익'에 미칠 영향을 추론하려는 경우 총 방문수가 캠페인의 영향을 받을 수 있으므로 일일 '방문수'를 공변량으로 사용할 수 없음
Method : ANCOVA(ANOVA + Regression)
pycausalimpact
기본은 R 패키지인데 Python을 사용할 예정이기 때문에 아래의 Package를 기재
R 패키지와 Python 패키지의 차이점
pip install pycausalimpact
tfcausalimpact
_ python 3.10 미만에서 가능함 pip install tfcausalimpact
pycausalimpact
import numpy as np
import pandas as pd
from statsmodels.tsa.arima_process import ArmaProcess
from causalimpact import CausalImpact
np.random.seed(12345)
ar = np.r_[1, 0.9]
ma = np.array([1])
arma_process = ArmaProcess(ar, ma)
X = 100 + arma_process.generate_sample(nsample=100)
y = 1.2 * X + np.random.normal(size=100)
y[70:] += 5
data = pd.DataFrame({'y': y, 'X': X}, columns=['y', 'X'])
pre_period = [0, 69]
post_period = [70, 99]
# 맨 처음에 실행할 때는 statsmodel 자체적으로
# local level component를 최적화할 수 있도록 prior_level_sd = None으로 설정
# local level prior에 확신이 있으면 설정해도 좋으나, risky할 수 있음
# ci = CausalImpact(data, pre_period, post_period, prior_level_sd=None)
ci = CausalImpact(data, pre_period, post_period)
print(ci.summary())
print(ci.summary(output='report'))
ci.plot()
prior_level_sd
pycausalimpact documentation strongly recommends setting the prior_level_sd as None when using the Python version of the package.
(prior_level_sd is the prior local level Gaussian standard deviation.)
nseasons
nseasons specifies the seasonal components of the model.
The default value is 1, meaning that there is no seasonality in the time series data.
Changing the value to a positive integer greater than 1 automatically includes the seasonal component. For example, nseasons=7 means that there is weekly seasonality.
Currently the CausalImpact package only supports one seasonal component, but we can include multiple seasonal components using the Bayesian Structural Time Series (BSTS) model, and pass the fitted model in as bsts.model.
The default value for seasonal_duration is 1. For example, nseasons=[{'period': 7}], seasonal_duration=1 means that the time series data has weekly seasonality and each data point represents one day.
If we would like to include the monthly seasonality, nseasons needs to be set to 12 and seasonal_duration needs to be set to 30, indicating that every 30 days represent one month.
In this example, we will use nseasons=[{'period': 12}], seasonal_duration=30 for the hyperparameters.
Since including a time-varying local trend or a time-varying local level often leads to over-specification, this hyperparameter defaults to FALSE.
We can manually change the value to TRUE if the data has local trends for certain time periods.
tfcausalimpact
import pandas as pd
from causalimpact import CausalImpact
data = pd.read_csv('*.csv', index_col=['DATE'])
pre_period = ['2019-04-16', '2019-07-14']
post_period = ['2019-7-15', '2019-08-01']
# Monte Carlo 알고리즘 사용
ci = CausalImpact(data, pre_period, post_period, model_args={'fit_method': 'hmc'})
csv 데이터 예시
분석 예시_1_Basic 데이터
분석 예시_2 Kaggle
분석 예시_3 > Google Search Console 연결
참고페이지1: Causal Impact Github
참고페이지2: Causal Impact - 좀 더 정확한 효과 측정을 위한 방법론
Intervention 이전 시계열 예측 확인 필요
개입 이전 시점까지의 시계열을 얼마나 잘 예측하는지 확인해야 합니다. 임의의 시점에 가상의 개입이 이루어졌다고 가정하고 모형을 학습하면 어떤 결론이 나오는지 확인해봅니다. 이 때 counterfactual 예측과 실제값이 비슷해서 통계적으로 유의미하지 않은 결론이 나와야 합니다.
모형의 학습 결과를 공유할 때는 가정한 내용들과 모형의 파라미터를 포함하여 공유합니다. 다른 사람들과 함께 유효한 가정인지, 적절한 파라미터를 사용한 것인지 논의하는 것이 좋습니다.
Revenue
Conversion
LTV(Lifetime Value)