Forecasting and Smoothing Techniques in Time Series Analysis

1/13
100%
Rendu du PDF...
Page 1 sur 13Lecteur de document UniversityLib

Forecasting and Smoothing Techniques in Time Series Analysis

Time Series Analysis and Forecasting · lab

PFA(prévision)

January 17, 2022

[25]: import pandas as pd

import numpy as np

import os

import matplotlib.pyplot as plt

from sklearn.model_selection import ParameterGrid

from statsmodels.tsa.api import SimpleExpSmoothing

from statsmodels.tsa.api import Holt

from statsmodels.tsa.api import ExponentialSmoothing

from sklearn import metrics

[26]: dataset=pd.read_excel('pfa.xlsx') #import excel file(Mois,Na)

[27]: dataset.info()

<class 'pandas.core.frame.DataFrame'>

RangeIndex: 60 entries, 0 to 59

Data columns (total 2 columns):

#

---

0

1

Column Non-Null Count Dtype

------ -------------- -----

Mois

Na

60 non-null

60 non-null

datetime64[ns]

int64

dtypes: datetime64[ns](1), int64(1)

memory usage: 1.1 KB

[28]: dataset.head() #the first five values of our dataset

[28]:

Mois

Na

0 2017-01-01 1999

1 2017-02-01 2999

2 2017-03-01 6715

3 2017-04-01 7010

4 2017-05-01 8500

[29]: dataset.isnull().sum() #no value is emty

1

[29]: Mois

0

0

Na

dtype: int64

[30]: dataset=dataset.groupby('Mois').sum() #set the index as Mois

[31]: dataset.head(10) #the first ten values of our dataset

[31]:

Na

Mois

1999

2017-01-01

2999

2017-02-01

6715

2017-03-01

7010

2017-04-01

2017-05-01

8500

2017-06-01 23905

2017-07-01 44300

2017-08-01 43788

2017-09-01 22563

2017-10-01 19300

[32]: dataset.plot()

[32]: <AxesSubplot:xlabel='Mois'>

2

[33]: import warnings

warnings.filterwarnings('ignore')

1 Moving Average

[50]: Moving_Average=dataset['Na'].rolling(window =3).mean()

Moving_Average.plot()

#moving average with the inisialisation of the first values with the mean of␣

,→the first thre values

[50]: <AxesSubplot:xlabel='Mois'>

[51]: dataset['Na'].plot(figsize=(10,6))

Moving_Average.plot()

[51]: <AxesSubplot:xlabel='Mois'>

3

[52]: Moving_Average #moving average values

[52]: Mois

2017-01-01

2017-02-01

2017-03-01

2017-04-01

2017-05-01

2017-06-01

2017-07-01

2017-08-01

2017-09-01

2017-10-01

2017-11-01

2017-12-01

2018-01-01

2018-02-01

2018-03-01

2018-04-01

2018-05-01

2018-06-01

2018-07-01

2018-08-01

2018-09-01

2018-10-01

NaN

NaN

3904.333333

5574.666667

7408.333333

Publicité

13138.333333

25568.333333

37331.000000

36883.666667

28550.333333

17247.000000

14263.000000

8513.000000

6220.333333

3942.333333

5659.000000

7492.333333

13101.666667

25631.000000

37359.333333

37108.666667

28548.000000

4

2018-11-01

2018-12-01

2019-01-01

2019-02-01

2019-03-01

2019-04-01

2019-05-01

2019-06-01

2019-07-01

2019-08-01

2019-09-01

2019-10-01

2019-11-01

2019-12-01

2020-01-01

2020-02-01

2020-03-01

2020-04-01

2020-05-01

2020-06-01

2020-07-01

2020-08-01

2020-09-01

2020-10-01

2020-11-01

2020-12-01

2021-01-01

2021-02-01

2021-03-01

2021-04-01

2021-05-01

2021-06-01

2021-07-01

2021-08-01

2021-09-01

2021-10-01

2021-11-01

2021-12-01

Name: Na, dtype: float64

17316.666667

14034.000000

8365.333333

6101.666667

4066.666667

5748.333333

7603.333333

13270.000000

25674.333333

37969.333333

37650.000000

29350.666667

17380.666667

14353.333333

8711.666667

6551.666667

4105.000000

5685.000000

7561.333333

13202.000000

25380.333333

36816.333333

36648.333333

28520.666667

17389.666667

14238.000000

8457.333333

6242.333333

4020.000000

5659.333333

7554.666667

13184.333333

25661.666667

37376.000000

36994.333333

28672.000000

17271.666667

14322.000000

[38]: from sklearn.metrics import mean_squared_error

[54]: RMSE=np.sqrt(mean_squared_error(dataset[2:],Moving_Average[2:]))

#Root Mean Square Eroor between the actual dataset and the moving average values

[55]: RMSE

5

[55]: 8844.115882511662

2 Simple Exponential Smoothing

[83]: fit1=SimpleExpSmoothing(dataset).fit(smoothing_level=1,optimized=False) #alpha␣

,→is optimised with excel solver

[84]: dataset.plot(legend=True, label='demande', figsize=(18,8))

fit1.fittedvalues.plot(legend=True, label='Forecast')

[84]: <AxesSubplot:xlabel='Mois'>

[85]: fit1.summary()

[85]: <class 'statsmodels.iolib.summary.Summary'>

"""

Publicité

SimpleExpSmoothing Model Results

==============================================================================

Dep. Variable:

60

6703434090.000

Model:

1115.892

Optimized:

1120.081

Trend:

1116.620

Seasonal:

Sun, 16 Jan 2022

Seasonal Periods:

Box-Cox:

16:05:21

Box-Cox Coeff.:

==============================================================================

Na

SimpleExpSmoothing

False

None

None

None

False

None

No. Observations:

SSE

AIC

BIC

AICC

Date:

Time:

------------------------------------------------------------------------------

coeff

code

optimized

6

False

smoothing_level

initial_level

False

------------------------------------------------------------------------------

"""

1.0000000

1999.0000

alpha

l.0

[86]: from sklearn.metrics import mean_squared_error

[87]: RMSE=np.sqrt(mean_squared_error(dataset,fit1.fittedvalues))

[88]: RMSE

[88]: 10569.952767160315

3 Double Exponential Smoothing

[89]: fit1= Holt(dataset).fit(smoothing_level=1,smoothing_trend=0,optimized=False)

#alpha and beta are optimised with excel solver

[90]: dataset.plot(legend=True, label='demande', figsize=(18,8))

fit1.fittedvalues.plot(legend=True, label='linear trend')

[90]: <AxesSubplot:xlabel='Mois'>

[91]: fit1.summary()

[91]: <class 'statsmodels.iolib.summary.Summary'>

"""

Holt Model Results

==============================================================================

7

Dep. Variable:

Model:

Optimized:

Trend:

Seasonal:

Seasonal Periods:

Box-Cox:

Box-Cox Coeff.:

==============================================================================

No. Observations:

SSE

AIC

BIC

AICC

Date:

Time:

60

6740010090.000

1120.219

1128.596

1121.804

Sun, 16 Jan 2022

16:05:23

Na

Holt

False

Additive

None

None

False

None

coeff

code

optimized

------------------------------------------------------------------------------

False

smoothing_level

False

smoothing_trend

False

initial_level

False

initial_trend

------------------------------------------------------------------------------

"""

1.0000000

Publicité

0.000000

1999.0000

1000.0000

alpha

beta

l.0

b.0

[92]: RMSE=np.sqrt(mean_squared_error(dataset,fit1.fittedvalues))

[93]: RMSE

[93]: 10598.749997051538

4 Triple Exponential Smoothing

[68]: import statsmodels.api as sm

from statsmodels.tsa.seasonal import seasonal_decompose

[69]: seasonal_decompose(dataset,model='additive',period=12).plot(); #seasonal␣

,→decompose of our dataset

8

[70]: train= dataset.iloc[:-12] # values from 2017 to 2020

test=dataset.iloc[-12:] #values of the last year (2021)

[71]: modelhw= ExponentialSmoothing(train['Na'],trend='add', seasonal='add',␣

,→seasonal_periods=12).fit()

#alpha, beta and gamma are optimiser with python

[72]: test_pred=modelhw.forecast(12) # the prediction of 2021

[73]: train['Na'].plot(legend=True,label='train',figsize=(18,9))

#actuals values␣

,→from 2017 to 2020

test_pred.plot(legend=True,label='predicted') #forecasted values of 2021

test['Na'].plot(legend=True,label='test') #actuals values of 2021

[73]: <AxesSubplot:xlabel='Mois'>

9

[74]: test_pred # the prediction values of 2021

[74]: 2021-01-01

2021-02-01

2021-03-01

2021-04-01

2021-05-01

2021-06-01

2021-07-01

2021-08-01

2021-09-01

2021-10-01

2021-11-01

2021-12-01

Freq: MS, dtype: float64

2249.928896

3192.954948

6777.983412

7248.332151

8761.936719

23698.820626

44529.363258

44413.569455

22827.526849

19332.229703

9907.131471

13533.511987

[75]: from sklearn.metrics import mean_squared_error

[76]: RMSE=np.sqrt(mean_squared_error(test,test_pred))

[77]: RMSE

[77]: 187.72249831939774

[78]: dataset.Na.mean(),np.sqrt(dataset.Na.var())

#mean and standar deviation are very high compared to RMSE, so, it is a good␣

,→prediction

10

[78]: (17121.5, 13998.367830402738)

[79]: final_model=modelhw= ExponentialSmoothing(dataset['Na'],trend='add',␣

,→seasonal='add', seasonal_periods=12).fit()

[80]: prediction=final_model.forecast(12) # the prediction of 2022

[81]: prediction # the forecasted values of 2022

[81]: 2022-01-01

2022-02-01

2022-03-01

2022-04-01

2022-05-01

2022-06-01

2022-07-01

2022-08-01

2022-09-01

2022-10-01

2022-11-01

2022-12-01

Freq: MS, dtype: float64

2214.430815

3174.982592

6773.250377

7175.758614

8770.684634

23685.807776

44357.254975

44122.378515

22865.366012

19365.574312

9893.741114

13530.571756

[82]: dataset['Na'].plot(legend=True,label='actuals',figsize=(18,9))

#actuals␣

,→values from 2017 to 2021

prediction.plot(legend=True,label='forcasted') #forecasted values of 2022

[82]: <AxesSubplot:xlabel='Mois'>

11

[83]: final_model.summary()

[83]: <class 'statsmodels.iolib.summary.Summary'>

"""

ExponentialSmoothing Model Results

================================================================================

Dep. Variable:

60

5635098.318

Model:

719.011

Optimized:

Publicité

752.520

Trend:

Seasonal:

735.694

Mon, 17 Jan 2022

Seasonal Periods:

Box-Cox:

17:44:02

Box-Cox Coeff.:

================================================================================

=

Na

ExponentialSmoothing

True

Additive

Additive

12

False

None

No. Observations:

SSE

AIC

BIC

AICC

Date:

Time:

coeff

code

optimized

b.0

l.0

beta

gamma

alpha

0.0001090

0.0757245

0.0002102

1.7716978

17041.058

-14936.623

--------------------------------------------------------------------------------

-

smoothing_level

True

smoothing_trend

True

smoothing_seasonal

True

initial_level

True

initial_trend

True

initial_seasons.0

True

initial_seasons.1

True

initial_seasons.2

True

initial_seasons.3

True

initial_seasons.4

True

initial_seasons.5

True

initial_seasons.6

True

initial_seasons.7

True

initial_seasons.8

True

-13977.855

-9980.6248

-10381.385

-8387.4487

27195.526

6525.7988

26958.923

5700.1722

s.5

s.0

s.2

s.4

s.3

s.6

s.1

s.7

s.8

12

2198.5191

initial_seasons.9

True

initial_seasons.10

True

initial_seasons.11

True

--------------------------------------------------------------------------------

-

"""

-3639.9977

-7275.0411

s.10

s.11

s.9

[ ]:

13