-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlinear_regression.py
More file actions
178 lines (136 loc) · 5.84 KB
/
Copy pathlinear_regression.py
File metadata and controls
178 lines (136 loc) · 5.84 KB
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
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error
import wget
import os
import datetime
# Get data updated
if os.path.exists('data.csv'):
os.remove('data.csv')
url = 'https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv'
try:
file = wget.download(url, out='data.csv')
print("\n")
except:
print("BAD", url)
# Setting parameters
config = {
'days_to_forecast': 3,
'global_degree': 5,
'new_case_degree': 3,
'terapia_intensiva': 2,
'time': int(str(datetime.datetime.now().time())[0:2]),
'update_data': 18,
'start_date': datetime.date(2020, 3, 16)
}
path_img = 'img/'
path_data = 'save_data/'
# Define linear regression methods
def train_model(x, y, degree):
polynomial_features = PolynomialFeatures(degree=degree)
x_poly = polynomial_features.fit_transform(x)
model = LinearRegression()
model.fit(x_poly, y)
return model
# Model predictions
def get_predictions(x, model, degree):
polynomial_features = PolynomialFeatures(degree=degree)
x_poly = polynomial_features.fit_transform(x)
return model.predict(x_poly)
# Call model forecasting
def call_model(model_name, model, x, y, days_to_predict, degree):
y_pred = np.round(get_predictions(x, model, degree), 0).astype(np.int32)
predictions = forecast(model_name, model, degree, beginning_day=len(x), limit=days_to_predict)
print("")
return predictions
# Forecast next days
def forecast(model_name, model, degree, beginning_day=0, limit=10):
next_days_x = np.array(range(beginning_day, beginning_day + limit)).reshape(-1, 1)
next_days_pred = np.round(get_predictions(next_days_x, model, degree), 0).astype(np.int32)
print("The results for " + model_name + " in the following " + str(limit) + " days is:")
for i in range(0, limit):
print(str(i + 1) + ": " + str(next_days_pred[i]))
collect_predictions(next_days_pred, model_name)
return next_days_pred
# Plot results
def plot_prediction(y, predictions, title):
total_days = [datetime.date(2020, 2, 24) + datetime.timedelta(days=int(i)) for i in range(int(y.shape[0]) + predictions.shape[0])]
if config['time'] >= config['update_data']:
today = str(datetime.date.today())
last_day = str(datetime.date.today() + datetime.timedelta(days=config['days_to_forecast']))
else:
today = str(datetime.date.today() - datetime.timedelta(1))
last_day = str(datetime.date.today() - datetime.timedelta(1) + datetime.timedelta(days=config['days_to_forecast']))
final_dates = []
for i in total_days:
i = str(i)
final_dates.append(i[5:])
y = np.array(y)
y = y.reshape((y.shape[0]), 1)
predictions = np.array(predictions)
predictions = predictions.reshape((predictions.shape[0]), 1)
series = np.concatenate([y, predictions], axis=0)
#old = load_predictions(title)
fig, ax = plt.subplots(figsize=(15, 8))
ax.plot(final_dates, series, label='Predicted cases')
ax.plot(y, color='red', label='Verified cases')
fig.autofmt_xdate()
plt.gca().xaxis.set_major_locator(plt.LinearLocator(numticks=30))
ax.axvspan(today[5:], last_day[5:], alpha=0.25)
plt.title(title)
plt.legend()
plt.grid()
plt.show()
fig.savefig(path_img + title.replace(" ", "") + ".png")
# Save old predictions
def collect_predictions(data, title):
if config['time'] >= config['update_data']:
filename = str(datetime.date.today() + datetime.timedelta(1))
else:
filename = str(datetime.date.today())
filename = filename.replace('-', '_')
np.save(path_data + title.replace(" ", "") + filename + '.npy', data)
def load_predictions(title):
start = config['start_date']
predictions = [np.nan] * 21
if config['time'] >= config['update_data']:
while start != datetime.date.today() + datetime.timedelta(1):
filename = str(start)
to_append = np.load(path_data + title.replace(" ", "") + filename.replace('-', '_') + '.npy')
predictions.append(to_append)
start = start + + datetime.timedelta(1)
else:
while start != datetime.date.today():
filename = str(start)
to_append = np.load(path_data + title.replace(" ", "") + filename.replace('-', '_') + '.npy')
predictions.append(to_append[0])
start = start + + datetime.timedelta(1)
predictions = np.array(predictions)
print(predictions.shape)
return predictions
# Arrange data and run the routine
def routine(series, title, degree):
first_c = np.array(range(0, series.shape[0]))
first_c = first_c.reshape((first_c.shape[0]), 1)
series = series.reshape((series.shape[0], 1))
series = np.concatenate([first_c, series], axis=1)
x = series[:, 0].reshape(-1, 1)
y = series[:, 1]
model = train_model(x, y, degree)
predictions = call_model(title, model, x, y, config["days_to_forecast"], degree)
plot_prediction(y, predictions, title)
# Get series
series = pd.read_csv('data.csv')
series_nuovi_positivi = np.array(series['variazione_totale_positivi'])
series_totale_casi = np.array(series['totale_casi'])
series_terapia_intensiva = series['terapia_intensiva']
first = series_terapia_intensiva.head(1)
series_terapia_intensiva = np.array(series_terapia_intensiva.diff().fillna(first))
partition = series_totale_casi.shape[0]
# Train and forecast
routine(series_totale_casi[0:partition], 'Italian total cases prediction', config['global_degree'])
routine(series_nuovi_positivi[0:partition], 'Italian new-daily cases prediction', config['new_case_degree'])
routine(series_terapia_intensiva[0:partition], 'Italian daily intensive Care patients', config['terapia_intensiva'])