-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRandomForest.py
352 lines (218 loc) · 9.03 KB
/
RandomForest.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas import read_csv, datetime, DataFrame, concat
from pandas.plotting import autocorrelation_plot
from matplotlib import pyplot
from numpy import asarray
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.ensemble import RandomForestRegressor
from statsmodels.tsa.stattools import adfuller
# In[3]:
df_cases = pd.read_csv("Cases.csv", encoding= 'unicode_escape')
# In[4]:
# clean cases data and convert them to numeric
df_cases = df_cases.applymap(lambda x: x.strip())
df_cases = df_cases.applymap(lambda x: x.replace(",", ""))
df_cases = df_cases.applymap(lambda x: x.replace("..", ""))
counties = df_cases.columns[1:]
for county in counties:
df_cases[county] = pd.to_numeric(df_cases[county],errors='coerce')
df_cases = df_cases.fillna(0)
# In[5]:
# display df test for all counties to detect if there are trends
def county_plots(counties, file_name=None):
figure = plt.gcf()
figure.set_size_inches(20, 20)
figure.suptitle('County Trends (Dickey Fuller Test)', fontsize=18)
plt.rcParams['figure.constrained_layout.use'] = False
for idx, county in enumerate(counties):
result = adfuller(df_cases[county].dropna())
ax = figure.add_subplot(8, 4, idx+1)
plt.title("County " + county + (' (p-value: %.3f)' % result[1]), fontsize=13)
plt.subplots_adjust(wspace = 0.3, hspace= 0.8)
ax.set_xlabel('Week'); ax.set_ylabel('cases')
df_cases[county].plot(ax=ax)
if file_name:
plt.savefig(file_name, dpi=300, bbox_inches="tight")
plt.show()
# In[6]:
county_plots(counties, file_name='all_counties_without_diff')
# In[7]:
# remove trends by differencing
new_cols = []
for county in counties:
new_cols.append(county + "_diff_1")
df_cases[county + "_diff_1"] = df_cases[county].diff(periods=1)
county_plots(new_cols, 'counties_after_diff_1')
# 1st differenced ordered counties
counties_order_1 = [county for county in new_cols if county != 'Westmeath_diff_1']
# In[8]:
# since westmeath was not stationary after 1st differencing, we have introduced 2nd order difference
df_cases["Westmeath_diff_2"] = df_cases["Westmeath_diff_1"].diff(periods=1)
county_plots(["Westmeath_diff_2"], 'Westmeath_diff_2')
counties_order_2 = ['Westmeath_diff_2']
# In[9]:
def series_to_supervised(data, n_in=1, n_out=1, dropnan=True):
n_vars = 1 if type(data) is list else data.shape[1]
df = DataFrame(data)
cols = list()
for i in range(n_in, 0, -1):
cols.append(df.shift(i))
for i in range(0, n_out):
cols.append(df.shift(-i))
agg = concat(cols, axis=1)
if dropnan:
agg.dropna(inplace=True)
return agg.values
# split a univariate dataset into train/test sets
def train_test_split(data, n_test):
return data[:-n_test, :], data[-n_test:, :]
# fit an random forest model and make a one step prediction
def random_forest_forecast(train, testX, n_estimators=1000):
train = asarray(train)
trainX, trainy = train[:, :-1], train[:, -1]
model = RandomForestRegressor(n_estimators=n_estimators)
model.fit(trainX, trainy)
yhat = model.predict([testX])
return yhat[0]
# walk-forward validation for univariate data
def walk_forward_validation(data, n_test, n_est):
predictions = list()
train, test = train_test_split(data, n_test)
history = [x for x in train]
for i in range(len(test)):
testX, testy = test[i, :-1], test[i, -1]
yhat = random_forest_forecast(history, testX, n_est)
predictions.append(yhat)
history.append(test[i])
# estimate prediction error
error = mean_absolute_error(test[:, -1], predictions)
rmse = mean_squared_error(test[:, -1], predictions,squared=False)
return error,rmse, test[:, -1], predictions
# In[10]:
# hyperparameter selection for number of last weeks input
last_week_range = [* range(2, 12)]
weeks_test = 12
figure = plt.gcf()
figure.set_size_inches(20, 20)
figure.suptitle('Cases', fontsize=18)
plt.rcParams['figure.constrained_layout.use'] = False
counties = ['Dublin_diff_1', 'Galway_diff_1', 'Cork_diff_1']
for idx, county in enumerate(counties):
rmse_list = []
for last_week in last_week_range:
data = series_to_supervised(df_cases[[county]].values, n_in=last_week)
mae,rmse, y, yhat = walk_forward_validation(data, weeks_test, n_est=2000)
rmse_list.append(rmse)
min_rmse = min(rmse_list)
min_week = last_week_range[rmse_list.index(min_rmse)]
ax = figure.add_subplot(8, 4, idx+1)
plt.title("County %s (RMSE vs Last Week)" % (county.split('_')[0]), fontsize=13)
plt.subplots_adjust(wspace = 0.3, hspace= 0.8)
ax.plot(last_week_range, rmse_list)
ax.plot(min_week,min_rmse,'ro')
ax.set_xlabel('Week'); ax.set_ylabel('RMSE')
plt.savefig('order_1_counties_rmse', dpi=300, bbox_inches="tight")
# In[197]:
# all counties 1st order .. the code takes a lot of time to run.
weeks_test = 12
last_weeks_input = 8
figure = plt.gcf()
figure.set_size_inches(20, 20)
figure.suptitle('Cases', fontsize=18)
plt.rcParams['figure.constrained_layout.use'] = False
for idx, county in enumerate(counties_order_1):
data = series_to_supervised(df_cases[[county]].values, n_in=last_weeks_input)
# evaluate
mae,rmse, y, yhat = walk_forward_validation(data, weeks_test, n_est=2000)
ax = figure.add_subplot(8, 4, idx+1)
plt.title("County " + county + (' (RMSE: %.3f)' % rmse), fontsize=13)
plt.subplots_adjust(wspace = 0.3, hspace= 0.8)
ax.plot(y, label='Expected')
ax.plot(yhat, label='Predicted')
ax.legend()
ax.set_xlabel('Week'); ax.set_ylabel('diff_1')
plt.savefig('order_1_counties_eval', dpi=300, bbox_inches="tight")
pyplot.show()
# In[198]:
# all counties 2nd order
weeks_test = 12
last_weeks_input = 8
figure = plt.gcf()
figure.set_size_inches(20, 20)
figure.suptitle('Cases', fontsize=18)
plt.rcParams['figure.constrained_layout.use'] = False
for idx, county in enumerate(counties_order_2):
data = series_to_supervised(df_cases[[county]].values, n_in=last_weeks_input)
# evaluate
mae,rmse, y, yhat = walk_forward_validation(data, weeks_test, n_est=2000)
ax = figure.add_subplot(8, 4, idx+1)
plt.title("County " + county + (' (RMSE: %.3f)' % rmse), fontsize=13)
plt.subplots_adjust(wspace = 0.3, hspace= 0.8)
ax.plot(y, label='Expected')
ax.plot(yhat, label='Predicted')
ax.legend()
ax.set_xlabel('Week'); ax.set_ylabel('diff_2')
plt.savefig('order_2_county_eval', dpi=300, bbox_inches="tight")
pyplot.show()
# In[214]:
# counties 1st order predictions
def future_predictions(county, weeks_ahead = 4):
data = series_to_supervised(df_cases[[county]].values, n_in=last_weeks_input)
# split into input and output columns
trainX, trainy = data[:, :-1], data[:, -1]
# fit model
model = RandomForestRegressor(n_estimators=2000)
model.fit(trainX, trainy)
# construct an input for a new prediction
row = df_cases[[county]].values[-last_weeks_input:].flatten()
last_cases = df_cases[county.split('_')[0]].values[-1:][0]
prediction = []
for i in range(weeks_ahead):
yhat = model.predict(asarray([row]))
# print('Input: %s, Predicted: %.3f' % (row, yhat[0] + last_cases))
# invert
prediction.append(yhat[0] + last_cases)
row = np.append(row, round(yhat[0]))
row = np.delete(row, 0)
last_cases = yhat[0] + last_cases
return prediction
# In[215]:
# meath 2nd order predictions
def future_predictions_order_2(county, weeks_ahead = 4):
data = series_to_supervised(df_cases[[county]].values, n_in=last_weeks_input)
# split into input and output columns
trainX, trainy = data[:, :-1], data[:, -1]
# fit model
model = RandomForestRegressor(n_estimators=2000)
model.fit(trainX, trainy)
# construct an input for a new prediction
row = df_cases[[county + '_diff_2']].values[-last_weeks_input:].flatten()
last_cases = df_cases[county.split('_')[0]].values[-1:][0] + df_cases[county.split('_')[0] + '_diff_1'].values[-1:][0]
prediction = []
for i in range(weeks_ahead):
yhat = model.predict(asarray([row]))
prediction.append(yhat[0] + last_cases)
row = np.append(row, round(yhat[0]))
row = np.delete(row, 0)
last_cases = yhat[0] + last_cases
return prediction
# In[220]:
county_pred = []
for county in counties_order_1:
preds = future_predictions(county, 4)
print('%s county : %s' % (county.split('_')[0], preds))
county_pred.append((county, preds))
# handling 2nd order diff separately
county_pred.append(('Westmeath_diff', future_predictions_order_2("Westmeath")))
# In[221]:
sorted_counties = sorted(county_pred, key=lambda x: x[1][1],reverse=True)
# In[222]:
# 3 counties with largest cases for 4 weeks
for county in sorted_counties[:3]:
print('%s county : %s' % (county[0].split('_')[0], county[1]))
# In[ ]: