# -*- coding: utf-8 -*-
"""CovidItalyyy

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1wfe0DtGn_aTy22pQU9MYZ2rfwKmwlY_m
"""

from __future__ import print_function
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

import keras
from keras import metrics
from keras import regularizers
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Activation
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import Adam, RMSprop
from keras.callbacks import TensorBoard, EarlyStopping, ModelCheckpoint
from keras.utils import plot_model
from keras.models import load_model

pd.set_option("max_columns",50)

data=pd.read_csv("ita.csv")
print(data.tail(10))

print(data.keys())

a=data['deceduti'][50]

total_rows=data['deceduti'].count()
for i in range(total_rows-1,-1, -1):
    if i==0:
      data['deceduti'][0]=data['deceduti'][0]
    else:
      data['deceduti'][i]=data['deceduti'][i]-data['deceduti'][i-1]

Y=data['deceduti']
print(Y)

X=data.drop(columns=['data','stato','totale_positivi','isolamento_domiciliare','tamponi',
                     'totale_casi','note_it','note_en','dimessi_guariti','deceduti'])
from sklearn.model_selection import train_test_split
X_train, X_val_and_test, Y_train, Y_val_and_test = train_test_split(X, Y, test_size=0.15 ,shuffle=False)
X_val, X_test, Y_val, Y_test = train_test_split(X_val_and_test, Y_val_and_test, test_size=0.5,shuffle=False)
print(X)

t_model = Sequential()
t_model.add(Dense(80, activation="tanh", kernel_initializer='normal', input_shape=(5,)))
t_model.add(Dropout(0.2))
t_model.add(Dense(120, activation="relu", kernel_initializer='normal', 
kernel_regularizer=regularizers.l1(0.01), bias_regularizer=regularizers.l1(0.01)))
t_model.add(Dropout(0.1))
t_model.add(Dense(20, activation="relu", kernel_initializer='normal', 
kernel_regularizer=regularizers.l1_l2(0.01), bias_regularizer=regularizers.l1_l2(0.01)))
t_model.add(Dropout(0.1))
t_model.add(Dense(10, activation="relu", kernel_initializer='normal'))
t_model.add(Dropout(0.0))
t_model.add(Dense(1))
t_model.compile(
      loss='mean_squared_error',
      optimizer='nadam',
      metrics=[metrics.mae])

epochs = 100
batch_size = 32

keras_callbacks = [
    EarlyStopping(monitor='val_mean_absolute_error', patience=20, verbose=0)
]

history = t_model.fit(X_train, Y_train,
    batch_size=batch_size,
    epochs=epochs,
    shuffle=True,
    verbose=0, # Change it to 2, if wished to observe execution
    validation_data=(X_val, Y_val),
    callbacks=keras_callbacks)

train_score = t_model.evaluate(X_train, Y_train, verbose=0)
valid_score = t_model.evaluate(X_val, Y_val, verbose=0)

print('Train MAE: ', round(train_score[1], 4), ', Train Loss: ', round(train_score[0], 4)) 
print('Val MAE: ', round(valid_score[1], 4), ', Val Loss: ', round(valid_score[0], 4))

def plot_hist(h, xsize=6, ysize=10):
    # Prepare plotting
    fig_size = plt.rcParams["figure.figsize"]
    plt.rcParams["figure.figsize"] = [xsize, ysize]
    fig, axes = plt.subplots(nrows=4, ncols=4, sharex=True)
    
    # summarize history for MAE
    plt.subplot(211)
    plt.plot(h['mean_absolute_error'])
    plt.plot(h['val_mean_absolute_error'])
    plt.title('Training vs Validation MAE')
    plt.ylabel('MAE')
    plt.xlabel('Epoch')
    plt.legend(['Train', 'Validation'], loc='upper left')
    
    # summarize history for loss
    plt.subplot(212)
    plt.plot(h['loss'])
    plt.plot(h['val_loss'])
    plt.title('Training vs Validation Loss')
    plt.ylabel('Loss')
    plt.xlabel('Epoch')
    plt.legend(['Train', 'Validation'], loc='upper left')

plot_hist(history.history, xsize=8, ysize=12)

t_model.predict(X_test)

print(Y_test)