-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProphet.py
235 lines (138 loc) · 5.19 KB
/
Prophet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#!/usr/bin/env python
# coding: utf-8
# In[1]:
#import libraries
from fbprophet import Prophet
from fbprophet.plot import plot_plotly
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import plotly.offline as py
py.init_notebook_mode()
get_ipython().run_line_magic('matplotlib', 'inline')
# In[3]:
#import datasets
acc=pd.read_csv('ACC.csv',header=None)
parf=pd.read_csv('PARF.csv',header=None)
clothes=pd.read_csv('CL.csv',header=None)
total=pd.read_csv('s2019.csv',header=None)
holidays=pd.read_csv('holidays.csv',header=None)
total.info()
# In[9]:
#create total training set
train_tot= pd.DataFrame()
train_tot['ds'] = pd.to_datetime(total[0])
train_tot['y']=total[1]
train_tot[0:5]
# In[5]:
#create total training set for cosmetics
train_parf= pd.DataFrame()
train_parf['ds'] = pd.to_datetime(parf[0])
train_parf['y']=parf[1]
train_parf
# In[315]:
#create total training set for clothes
train_clothes= pd.DataFrame()
train_clothes['ds'] = pd.to_datetime(clothes[0])
train_clothes['y']=clothes[1]
train_clothes
# In[17]:
#initialize and train baseline Prophet model
prophet_model = Prophet()
prophet_model.fit(train_tot)
# In[18]:
# predict values for 300 days
future= prophet_model.make_future_dataframe(periods=300)
future.tail(2)
# In[19]:
# plot rime series data
fig = plt.figure(facecolor='w', figsize=(10, 6))
plt.plot(train_tot.ds, train_tot.y)
# In[20]:
#plot predicted data
forecast=prophet_model.predict(future)
fig1 =prophet_model.plot(forecast)
# In[21]:
#plot components
fig1 = prophet_model.plot_components(forecast)
# In[13]:
#check changepoints
from fbprophet.plot import add_changepoints_to_plot
fig= prophet_model.plot(forecast)
a = add_changepoints_to_plot(fig.gca(), prophet_model, forecast)
# In[11]:
# add holiday season data
holiday_season = pd.DataFrame({
'holiday': holidays[0],
'ds': pd.to_datetime(holidays[1]),
'lower_window': -1,
'upper_window': 0,
})
holiday_season.head()
# In[15]:
#modify prophet algorithm adding holidat and creating a new periodicity and plot new data
pro_holiday= Prophet(holidays=holiday_season,holidays_prior_scale = 25).add_seasonality(name='bimonthly',period=365.25/6,fourier_order=5).add_seasonality(name='weekly',period=7,fourier_order=20)
pro_holiday.fit(train_tot)
future_data = pro_holiday.make_future_dataframe(periods=12, freq = 'm')
#forecast the data for future data
forecast_data = pro_holiday.predict(future_data)
pro_holiday.plot(forecast_data);
# In[183]:
#modify prophet algorithm adding holidat and creating a new periodicity and plot new data
pro_holiday= Prophet(holidays=holiday_season,holidays_prior_scale = 10,changepoint_prior_scale=10,seasonality_mode='additive',interval_width = 0.6, growth='linear', yearly_seasonality = False,
weekly_seasonality=False).add_seasonality(name='yearly',period=365.25,fourier_order=10).add_seasonality(name='quaterly',period=365.25/4,fourier_order=5)
pro_holiday.fit(train_tot)
future_data = pro_holiday.make_future_dataframe(periods=12, freq = 'm')
#forecast the data for future data
forecast_data = pro_holiday.predict(future_data)
pro_holiday.plot(forecast_data);
# In[16]:
#Cross validate the first model
from fbprophet.diagnostics import cross_validation
df_cv2 = cross_validation(pro_holiday, initial='2000 days', period='180 days', horizon = '180 days')
# Python
from fbprophet.diagnostics import performance_metrics
df_ph = performance_metrics(df_cv2)
df_ph[50:100]
# In[78]:
#Cross validate the modified model
from fbprophet.diagnostics import cross_validation
df_cv1 = cross_validation(prophet_model, initial='2000 days', period='90 days', horizon = '90 days')
from fbprophet.diagnostics import performance_metrics
df_p = performance_metrics(df_cv1)
df_p[50:100]
# In[18]:
#plot MAPE metric for modified model
plt.plot( df_ph['mape'][0:150], 'b') # plotting t, b separately
plt.title('MAPE e Modelit te modifikuar')
plt.xlabel('Diapazoni(Dite)')
plt.ylabel('MAPE')
# In[83]:
#plot time series prediction for original model compared to truth
from sklearn.metrics import mean_absolute_error
# calculate MAE between expected and predicted values for december
y_true = train_tot[(train_tot['ds'] >= '2019-01-01') & (train_tot['ds'] <= '2019-12-30') ]['y'].values
y_pred = forecast_data[(forecast_data['ds'] >= '2019-01-01') & (forecast_data['ds'] <= '2019-12-30')]['yhat'].values
mae = mean_absolute_error(y_true, y_pred)
print('MAE: %.3f' % mae)
# plot expected vs actual
plt.plot(y_true, label='Actual')
plt.plot(y_pred, label='Predicted')
plt.legend()
plt.show()
# In[84]:
## #plot time series prediction for modified model compared to truth
# calculate MAE between expected and predicted values for december
y_true = train_tot[(train_tot['ds'] >= '2019-01-01') & (train_tot['ds'] <= '2019-12-30') ]['y'].values
y_pred = forecast[(forecast['ds'] >= '2019-01-01') & (forecast['ds'] <= '2019-12-30')]['yhat'].values
mae = mean_absolute_error(y_true, y_pred)
print('MAE: %.3f' % mae)
# plot expected vs actual
plt.plot(y_true, label='Actual')
plt.plot(y_pred, label='Predicted')
plt.legend()
plt.show()
# In[1]:
# covert jupyter notebook to the python file
get_ipython().system('jupyter nbconvert --to script DM_Project.ipynb')
# In[ ]: