<jupyter_start><jupyter_text>Forecasting The Number Of People Infected With Coronavirus in the WorldSource: https://www.kaggle.com/kiranbhonsle/forecasting-covid-19-infected-people-in-world Importing necessary libraries<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.metrics import mean_absolute_error,mean_squared_error
from statsmodels.graphics.tsaplots import plot_acf,plot_pacf
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.tsa.ar_model import AR
from datetime import datetime
from statsmodels.tsa.holtwinters import ExponentialSmoothing
import math
from statsmodels.tsa.statespace.sarimax import SARIMAX
from keras.preprocessing.sequence import TimeseriesGenerator
from statsmodels.tsa.seasonal import seasonal_decompose
#Cloning data from GitHub.
!git clone https://github.com/CSSEGISandData/COVID-19.git
cor_inf = pd.read_csv('COVID-19/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')
cor_inf.head(5)<jupyter_output><empty_output><jupyter_text>Data Preprocessing for the covid-19 dataset The valuable features what we are hunting for is Country names.Count of    infected people Dates At which they were affected in the country.    As we are not focused on predicting on indiviual country as it might be     bias on some country as a result the prediction might be very large or too small    which may be act as outlier.<jupyter_code>#drop lat long and province/state columns
cor_inf.columns<jupyter_output><empty_output><jupyter_text>Drop the Province/State, Latitude and  Longitude columns  as they make the data to narrow and data for those column might be missing for some countries<jupyter_code>cor_inf.drop(labels = ['Province/State','Lat', 'Long'],axis = 1, inplace= True)
cor_inf.head(100)<jupyter_output><empty_output><jupyter_text>Reshaping the data to proceed with Forecasting Now we want to reshape the data as per the requirement i.e make index as dates,and columnname as country names<jupyter_code>cor_inf.shape
new = cor_inf['Country/Region']
new<jupyter_output><empty_output><jupyter_text>To get the total infected people per day in the world we sum the count of infected people from all the countries and group them as per datesBut before we saw that in the country/Region column we have duplicated data as a resultwe need to first sum all the country and then get the count of all the people infected<jupyter_code>#group by data based upon country since the countries name are repeated more than once 
cor_inf = cor_inf.groupby(['Country/Region']).sum()
cor_inf
#reshape the data as per the time series analysis
cor_inf_re = pd.DataFrame()
for i in range(0,len(cor_inf)):
    cor_inf_re[cor_inf.index[i]] = cor_inf.iloc[i].values
    
type(cor_inf.index[0])
cor_inf_re.index = cor_inf.columns[:]
cor_inf_re.head(5)

def total_infected_sum():
    count = []
    for i in range(0,len(cor_inf_re)):
        count.append(sum(cor_inf_re.iloc[i].values))
    return count
cor_inf_re['Total infected'] = total_infected_sum()
cor_inf_re.tail(5)
total = cor_inf_re.loc[:, :]
total.head()
daily = total.diff()
daily.fillna(0, inplace = True)
daily.head()
total.fillna(0, inplace = True)
total.head()<jupyter_output><empty_output><jupyter_text>Now only we need to convert index datatype i.e object to datetime<jupyter_code>def parser(date):
    date = datetime.strptime(date,'%m/%d/%y')
    date  = str(date.day) + '-' + str(date.month) + '-' + str(date.year)
    print(date)
    return datetime.strptime(date,'%d-%m-%Y')
#convert str to datetime in index 
timestamp = []
for i in range(0,len(cor_inf_re)):
    timestamp.append(parser(cor_inf_re.index[i]))
cor_inf_re.index = timestamp<jupyter_output>22-1-2020
23-1-2020
24-1-2020
25-1-2020
26-1-2020
27-1-2020
28-1-2020
29-1-2020
30-1-2020
31-1-2020
1-2-2020
2-2-2020
3-2-2020
4-2-2020
5-2-2020
6-2-2020
7-2-2020
8-2-2020
9-2-2020
10-2-2020
11-2-2020
12-2-2020
13-2-2020
14-2-2020
15-2-2020
16-2-2020
17-2-2020
18-2-2020
19-2-2020
20-2-2020
21-2-2020
22-2-2020
23-2-2020
24-2-2020
25-2-2020
26-2-2020
27-2-2020
28-2-2020
29-2-2020
1-3-2020
2-3-2020
3-3-2020
4-3-2020
5-3-2020
6-3-2020
7-3-2020
8-3-2020
9-3-2020
10-3-2020
11-3-2020
12-3-2020
13-3-2020
14-3-2020
15-3-2020
16-3-2020
17-3-2020
18-3-2020
19-3-2020
20-3-2020
21-3-2020
22-3-2020
23-3-2020
24-3-2020
25-3-2020
26-3-2020
27-3-2020
28-3-2020
29-3-2020
30-3-2020<jupyter_text>Sum all the count of infected people of each country to get the total infected people per date<jupyter_code>cor_inf_re.to_csv('covid_19_confirmed.csv')
#preparing for time series
infected_people = cor_inf_re['Total infected']
#column for infected per day
diff = []
diff.append(cor_inf_re['Total infected'][0])
for i in range(0,len(cor_inf_re['Total infected']) - 1):
    diff.append(cor_inf_re['Total infected'][i+1] - cor_inf_re['Total infected'][i])

cor_inf_re['Infected_per_Day'] = diff<jupyter_output><empty_output><jupyter_text>Visualization of dataset<jupyter_code>infected_people
#check the statistical part of the data
infected_people.describe()

#to check if there is an trend or seasonality
from statsmodels.tsa.seasonal import seasonal_decompose
result = seasonal_decompose(infected_people)
result.trend.plot(figsize=(20,8))
train = infected_people.iloc[:]
test = infected_people.iloc[:]
#train.replace(0,1, inplace = True)
train.tail()<jupyter_output><empty_output><jupyter_text>Exponential Smoothing Single, Double and Triple Exponential Smoothing can be implemented in Python using the ExponentialSmoothing Statsmodels class.First, an instance of the ExponentialSmoothing class must be instantiated, specifying both the training data and some configuration for the model.Specifically, you must specify the following configuration parameters:trend: The type of trend component, as either “add” for additive or “mul” for multiplicative. Modeling the trend can be disabled by setting it to None.damped: Whether or not the trend component should be damped, either True or False.seasonal: The type of seasonal component, as either “add” for additive or “mul” for multiplicative. Modeling the seasonal component can be disabled by setting it to None.seasonal_periods: The number of time steps in a seasonal period, e.g. 12 for 12 months in a yearly seasonal structure (more here).The model can then be fit on the training data by calling the fit() function.This function allows you to either specify the smoothing coefficients of the exponential smoothing model or have them optimized. By default, they are optimized (e.g. optimized=True). These coefficients include:smoothing_level (alpha): the smoothing coefficient for the level.smoothing_slope (beta): the smoothing coefficient for the trend.smoothing_seasonal (gamma): the smoothing coefficient for the seasonal component.damping_slope (phi): the coefficient for the damped trend.<jupyter_code>model1 = ExponentialSmoothing(train,trend = "mul",seasonal_periods=2,seasonal="add").fit()
predictions1 = model1.predict(start = 65 ,end= 80 )
pd.options.display.float_format = '{:,.0f}'.format
predictions1
plt.figure(figsize = (24,10))
predictions1.plot(c ='r',linestyle='--', label =  "Predicted")
test.plot(linestyle='-', label = "Actual")
plt.legend(loc = "upper left")<jupyter_output><empty_output><jupyter_text>SARIMAX model<jupyter_code>model2 = SARIMAX(train,order = (4,2,1),trend='t',seasonal_order=(2, 2, 1, 12))
model_fit = model2.fit()
predictions2 = model_fit.predict(start = 65,end=80)
pd.options.display.float_format = '{:,.0f}'.format
predictions2
plt.figure(figsize = (24,10))
predictions2.plot(c ='r',linestyle='--', label =  "Predicted")
test.plot(linestyle='-', label = "Actual")
plt.legend(loc = 'upper left')
plt.figure(figsize = (24,10))
plt.plot(predictions1,'r',marker = 'o', label = "ExponentialSmoothing Model")
plt.plot(predictions2,'b',marker = 'o', label = "SARIMAX Model")
plt.legend()<jupyter_output><empty_output><jupyter_text>Thus Exponential model is better than the SARIMAX Model.As per the result it might be that after one week from now, it will affect around **1.5 Million People** all over the World!<jupyter_code><jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10591404432472144, 'fraction_numerical': 0.06758907799681646, 'mean_word_length': 5.5817888799355355, 'pattern_counts': {'":': 0, '<': 44, '<?xml version=': 0, '>': 44, 'https://': 2, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '252815', 'license': 'MIT', 'n_tokens_mistral': 3125, 'n_tokens_neox': 2743, 'n_words': 802, 'path': 'Predicting Covid-19 Infected people in the World.ipynb', 'repo_name': 'MauryaRitesh/Covid-19-Worldwide-Prediction', 'size': '8167'}