prophet tuning

mail@pastecode.io avatar
unknown
python
13 days ago
3.6 kB
5
Indexable
Never
# Impor library yang diperlukan
import pandas as pd
from prophet import Prophet
from sklearn.metrics import mean_squared_error, mean_absolute_error
from prophet.diagnostics import cross_validation, performance_metrics
from sklearn.model_selection import ParameterGrid

# Load dataset
bbri_history = pd.read_csv("/content/drive/My Drive/Dataset_Bank/historical_value/bbri_hist.csv", parse_dates=['Date'])

# Menghapus informasi timezone
bbri_history['Date'] = bbri_history['Date'].dt.tz_localize(None)

# Mengganti nama kolom untuk Prophet
bbri_history.rename(columns={'Date': 'ds', 'Open': 'y'}, inplace=True)

# Normalisasi data
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
bbri_history['y'] = scaler.fit_transform(bbri_history[['y']])

best_model = None
best_params = None
best_mape_cv = float('inf')  # Initialize with a high value

# Definisikan grid hyperparameter
param_grid = {
    'changepoint_prior_scale': [0.01, 0.5, 1.0],
    'seasonality_mode': ['additive'],
    'seasonality_prior_scale': [0.1, 1.0, 0.5, 10.0],
    'holidays_prior_scale': [0.5, 1.0, 2.0, 5.0, 10.0, 20.0]
}

# Dataframe untuk menyimpan hasil tuning
results = []

# Loop through all combinations of parameters
for params in ParameterGrid(param_grid):
    # Create and train the Prophet model
    model = Prophet(changepoint_prior_scale=params['changepoint_prior_scale'],
                    seasonality_prior_scale=params['seasonality_prior_scale'],
                    seasonality_mode=params['seasonality_mode'],
                    holidays_prior_scale=params['holidays_prior_scale']
                    )
    model.add_country_holidays(country_name='ID')
    model.fit(bbri_history)

    # Perform cross-validation
    cutoffs = pd.to_datetime(['2020-01-01', '2020-09-04', '2021-05-10'])
    df_cv = cross_validation(model, cutoffs=cutoffs, initial='730 days', period='180 days', horizon='365 days')
    df_p = performance_metrics(df_cv)

    # Calculate mean error metrics from cross-validation
    mse_cv = df_p['mse'].mean()
    mae_cv = df_p['mae'].mean()
    mape_cv = df_p['mape'].mean()
    rmse_cv = df_p['rmse'].mean()

    # Store the results
    results.append({
        'changepoint_prior_scale': params['changepoint_prior_scale'],
        'seasonality_prior_scale': params['seasonality_prior_scale'],
        'seasonality_mode': params['seasonality_mode'],
        'holidays_prior_scale': params['holidays_prior_scale'],
        'mse_cv': mse_cv,
        'mae_cv': mae_cv,
        'mape_cv': mape_cv,
        'rmse_cv': rmse_cv
    })

    # Check if this is the best model so far
    if mape_cv < best_mape_cv:
        print(f"New best model found with MAPE={mape_cv}")
        best_mape_cv = mape_cv
        best_model = model
        best_params = params
        
    # Print the results
for result in results:
    print(f"Parameters: changepoint_prior_scale={result['changepoint_prior_scale']}, seasonality_mode={result['seasonality_mode']}, holidays_prior_scale={result['holidays_prior_scale']}, seasonality_prior_scale={result['seasonality_prior_scale']}")
    print(f"Cross-Validation MSE: {result['mse_cv']}")
    print(f"Cross-Validation MAE: {result['mae_cv']}")
    print(f"Cross-Validation MAPE: {result['mape_cv']}")
    print(f"Cross-Validation RMSE: {result['rmse_cv']}")
    print("------")
    
# Make future predictions with the best model
future = best_model.make_future_dataframe(periods=365)
forecast = best_model.predict(future)

# Plot the forecast
fig1 = best_model.plot(forecast)
plt.title('Forecast')
plt.xlabel('Date')
plt.ylabel('Value')
plt.show()
Leave a Comment