def simpleExponentialSmoothing(df, no_predictions=7, debug=False, visualize=False): train_data, test_data = df[1:int(len(df) - no_predictions )], df[int(len(df) - no_predictions):] fit1 = SimpleExpSmoothing(np.asarray(train_data)).fit(smoothing_level=0.85, optimized=False) if (debug): print(fit1.summary()) predictions = fit1.forecast(no_predictions * 2) if (visualize): plt.plot(list(test_data), color='blue', label='testing data') plt.plot(list(predictions), color='red', label='prediction') plt.legend(loc='upper left', fontsize=8) plt.show() error = np.sqrt(mean_squared_error(test_data, predictions[:no_predictions])) return (predictions[-no_predictions:], error, fit1)
import math from statistics import mean plt.style.use('fivethirtyeight') df = pd.read_excel("../00Daily/Egypt.xlsx", squeeze=True, parse_dates=True) df = df[["Date", "LocalTransmission"]] df.set_index("Date", inplace=True) df.dropna(inplace=True) ##df['Date'] = pd.to_datetime(df['Date']) LocalTransmission = df['LocalTransmission'].astype('int32') #print (df.head()) print(df.index) result = SimpleExpSmoothing(df).fit() print(result.summary()) #print(result.params) predictions = result.predict(start="2020-03-01", end="2020-05-01") #accuracy = result.score() print("Predictions: ", predictions, sep='\n') ##accuracy = result.score() #print (accuracy) #result.plot_predict(start="2020-03-01", end="2020-05-01") plt.plot(predictions) plt.show() ##def mean_forecast_error(y, yhat): ## return y.sub(yhat).mean()
rain_mod1_pred = pd.DataFrame(rain_mod1_pred, index=pd.date_range(start='1913-01-01', periods=8, freq='YS')) rain_mod1_pred #Plot Actual & forecast plt.plot(rain) plt.plot(rain_mod1_pred) plt.legend(['Actual', 'Forecast'], bbox_to_anchor=(1, 1), loc=2) plt.show() #Model with single exponential smoothing from statsmodels.tsa.holtwinters import SimpleExpSmoothing rain_ses = SimpleExpSmoothing(rain).fit() rain_ses.summary() ''' SimpleExpSmoothing Model Results ============================================================================== Dep. Variable: rain No. Observations: 100 Model: SimpleExpSmoothing SSE 1758.465 Optimized: True AIC 290.703 Trend: None BIC 295.913 Seasonal: None AICC 291.124 Seasonal Periods: None Date: Fri, 26 Mar 2021 Box-Cox: False Time: 00:58:24 Box-Cox Coeff.: None ============================================================================== coeff code optimized ------------------------------------------------------------------------------ smoothing_level 1.4901e-08 alpha True initial_level 24.823898 l.0 True
) #First 6 and last 6 values are Na's due calculation of seasonality indices of 12 months births_dec_a.seasonal births_dec_a.resid.head( 20 ) #First 6 and last 6 values are Na's due calculation of seasonality indices of 12 months ''' SimpleExpSmoothing is used when there is no trend and Seasonal Holt is used when there is trend ExponentialSmoothing is when there trend and seasonal''' #For this data supposed to use last method but trying other methods for practice #Model with single exponential smoothing from statsmodels.tsa.holtwinters import SimpleExpSmoothing births_ses = SimpleExpSmoothing(births).fit() births_ses.summary() ''' SimpleExpSmoothing Model Results ============================================================================== Dep. Variable: births No. Observations: 168 Model: SimpleExpSmoothing SSE 280.315 Optimized: True AIC 90.007 Trend: None BIC 96.255 Seasonal: None AICC 90.253 Seasonal Periods: None Date: Fri, 26 Mar 2021 Box-Cox: False Time: 00:21:27 Box-Cox Coeff.: None ============================================================================== coeff code optimized ------------------------------------------------------------------------------ smoothing_level 0.4379774 alpha True
''' ADF Statistic: -1.614915 p-value: 0.475396 Critical Values: 1%: -3.610 5%: -2.939 10%: -2.608''' #p-value: 0.475396 ie > 0.5, Null Hypothesis accepted, Data is not stationary #H0: Data is not stationary #Being trend and seasonality is not visible in the data using #single exponential smoothing from statsmodels.tsa.holtwinters import SimpleExpSmoothing skirts_ses = SimpleExpSmoothing(skirts).fit() skirts_ses.summary() ''' SimpleExpSmoothing Model Results ============================================================================== Dep. Variable: diam No. Observations: 46 Model: SimpleExpSmoothing SSE 41869.930 Optimized: True AIC 317.429 Trend: None BIC 321.087 Seasonal: None AICC 318.405 Seasonal Periods: None Date: Thu, 25 Mar 2021 Box-Cox: False Time: 23:09:03 Box-Cox Coeff.: None ============================================================================== coeff code optimized ------------------------------------------------------------------------------ smoothing_level 0.9950000 alpha True
Train = bluejet.head(132) Test = bluejet.tail(12) # Creating a function to calculate the MAPE value for test data def MAPE(pred, org): temp = np.abs((pred - org) / org) * 100 return np.mean(temp) Train["flyers"] = Train.flyers.astype('double') bluejet["flyers"] = bluejet.flyers.astype('double') # Simple Exponential Method help(SimpleExpSmoothing) ses_model = SimpleExpSmoothing(Train["flyers"]).fit() ses_model.summary() pred_ses = ses_model.predict(start=Test.index[0], end=Test.index[-1]) MAPE(pred_ses, Test.flyers) #14.25 # Holt method hw_model = Holt(Train["flyers"]).fit() hw_model.summary() pred_hw = hw_model.predict(start=Test.index[0], end=Test.index[-1]) MAPE(pred_hw, Test.flyers) #12.41 # Holts winter exponential smoothing with additive seasonality hwe_model_add_add = ExponentialSmoothing(Train["flyers"], seasonal="add", trend="add", seasonal_periods=12).fit() hwe_model_add_add.summary()