<jupyter_start><jupyter_text>Time Series Analysis dan Forecasting menggunakan SARIMAXNotebook ini merupakan bagian dari buku **Fundamental Machine Learning menggunakan Python** oleh **<NAME>**. Notebook ini berisi contoh kode untuk **Bab 10 - SARIMAX.**<jupyter_code># Mengimpor library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from pmdarima import auto_arima

from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.stattools import adfuller
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.graphics.tsaplots import plot_pacf
from statsmodels.tools.eval_measures import mse
from statsmodels.tools.eval_measures import rmse
# Fungsi untuk uji stasioner dan dekomposisi komponen time series
def test_stationarity(timeseries):
    rolmean = timeseries.rolling(12).mean()
    rolstd = timeseries.rolling(12).std()

    plt.plot(timeseries, color='blue',label='Original')
    plt.plot(rolmean, color='red', label='Rolling Mean')
    plt.plot(rolstd, color='black', label = 'Rolling Std')
    plt.legend(loc='best')
    plt.title('Rolling Mean & Standard Deviation')
    plt.show()

    print('>> Dickey-Fuller Test <<')
    dftest = adfuller(timeseries, autolag='AIC')
    dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
    for key,value in dftest[4].items():
        dfoutput['Critical Value ({})'.format(key)] = value

    print(dfoutput)<jupyter_output><empty_output><jupyter_text>Data Ingestion<jupyter_code># Membaca data dari file CSV
df = pd.read_csv(r'../datasets/air-passengers.csv', parse_dates=True, index_col="month")<jupyter_output><empty_output><jupyter_text>Exploratory Data Analysis dan Preprocessing<jupyter_code># Menampilkan informasi dataset
df.info()
# Uji stasioner data mentah
test_stationarity(df)<jupyter_output><empty_output><jupyter_text>Preprocessing<jupyter_code># Transformasi logaritmik
df_log = df.copy()
df_log["passengers"] = df_log["passengers"].apply(np.log)
# Uji stasioner
test_stationarity(df_log)
# Uji stasioner pada data dengan lag = 1
df_log_diff = df_log - df_log.shift()
df_log_diff.dropna(inplace=True)
test_stationarity(df_log_diff)
# Dekomposisi komponen musiman
decomposition = seasonal_decompose(df_log)

plt.figure(figsize=(8,10))
ax1 = plt.subplot(4, 1, 1)
plt.plot(df_log)
ax1.set_title("Original")
ax1.set_xticklabels([])

ax2 = plt.subplot(4, 1, 2, sharex=ax1)
plt.plot(decomposition.trend)
ax2.set_title("Trend")
ax2.set_xticklabels([])

ax3 = plt.subplot(4, 1, 3, sharex=ax1)
plt.plot(decomposition.seasonal)
ax3.set_title("Seasonality")
ax3.set_xticklabels([])

ax4 = plt.subplot(4, 1, 4, sharex=ax1)
plt.plot(decomposition.resid)
ax4.set_title("Residuals")

plt.tight_layout()
# Plot ACF dan PACF
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
plot_acf(df_log_diff, ax=ax1)
plot_pacf(df_log_diff, ax=ax2)

fig.show()<jupyter_output><empty_output><jupyter_text>Training<jupyter_code># Cari parameter yang terbaik
auto_arima(df_log["passengers"], m=12, trace=True, suppress_warnings=True)
# Membuat model SARIMAX dengan model (2,0,0)x(0,1,1,12)
model = SARIMAX(df_log, trend='c', order=(2, 0, 0), seasonal_order=(0, 1, 1, 12))
model_fit = model.fit(disp=False)
# Deskripsi model
model_fit.summary()<jupyter_output><empty_output><jupyter_text>Evaluation<jupyter_code># Melakukan prediksi data 36 bulan terakhir
y_base = pd.Series(df_log["passengers"][-36:]).apply(np.exp)
y_pred = model_fit.predict(start=df_log.index[-36], end=df_log.index[-1]).apply(np.exp)

print("MSE: {}".format(mse(y_base, y_pred)))
print("RMSE: {}".format(rmse(y_base, y_pred)))
# Plot hasil prediksi pada interval 36 hari terakhir
fig, ax = plt.subplots(figsize=(10,4))
y_base.plot(ax=ax)
y_pred.plot(ax=ax)<jupyter_output><empty_output><jupyter_text>Prediction<jupyter_code># Lakukan forecast 30 bulan ke depan
forecasted = model_fit.get_forecast(30)

y = df_log["passengers"].apply(np.exp)
y_forecast = pd.Series(forecasted.predicted_mean).apply(np.exp)
y_interval = forecasted.conf_int().apply(np.exp)
# Plot hasil forecast
fig, ax = plt.subplots(figsize=(10,4))
y.plot(ax=ax)
y_forecast.plot(ax=ax)
ax.fill_between(y_interval.index, y_interval.iloc[:,0], y_interval.iloc[:,1], color='g', alpha=0.1)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13836622303809087, 'fraction_numerical': 0.02042221202386416, 'mean_word_length': 7.193609022556391, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 32, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '365725', 'license': 'MIT', 'n_tokens_mistral': 1762, 'n_tokens_neox': 1671, 'n_words': 312, 'path': 'jupyter/time-series_sarimax.ipynb', 'repo_name': 'fahminlb33/buku-ml-python', 'size': '4368'}