<jupyter_start><jupyter_text>Importing Libraries<jupyter_code>import pandas as pd
import numpy as np
import tensorflow as tf
keras = tf.keras
from sklearn.preprocessing import RobustScaler
import plotly.graph_objects as go
physical_devices = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_devices[0], True)<jupyter_output><empty_output><jupyter_text>Importing Data<jupyter_code>confirmed_df = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv')<jupyter_output><empty_output><jupyter_text>Date Pre-Processing<jupyter_code>confirmed_df = confirmed_df.groupby("Country/Region").sum().reset_index()
Country_confirmed =  confirmed_df['Country/Region'].values
confirmed_df = confirmed_df.drop(['Lat','Long','Country/Region'], axis=1)
confirmed_df = confirmed_df[confirmed_df.columns].T
confirmed_df.columns = Country_confirmed
Date_index = confirmed_df.index
confirmed_df = confirmed_df.diff().fillna(0)
confirmed_df = confirmed_df.abs()
confirmed_df.head()<jupyter_output><empty_output><jupyter_text>Scalling the data<jupyter_code>sc = RobustScaler()
confirmed_df_scaled = sc.fit_transform(confirmed_df)
confirmed_df_scaled = pd.DataFrame(confirmed_df_scaled)<jupyter_output><empty_output><jupyter_text>Enter the number of days you want to predict<jupyter_code>DAYS_TO_PREDICT = int(input('Enter Number Of Days You Want to Predict : '))
predict_confirm_index = pd.date_range(start=Date_index[-1],periods=DAYS_TO_PREDICT + 1,closed='right')
predict_confirm_index = predict_confirm_index.strftime('%Y/%m/%d')<jupyter_output><empty_output><jupyter_text>Creating class for building model<jupyter_code>class Corona_Confirmed_model():
    def create_dataset(self, dataset, time_steps=1, column = 0):
        dataX, dataY = [], []
        for i in range(len(dataset)-time_steps-1):
          a = dataset[i:(i+time_steps), column]
          dataX.append(a)
          dataY.append(dataset[i + time_steps, column])
        return np.array(dataX), np.array(dataY)

    def Model(self,dframe,column):
        df = dframe.values
        df = df.astype('float32')
        
        time_steps = 1
        trainX, trainY = self.create_dataset(df, time_steps, column)
        trainX = np.reshape(trainX, (trainX.shape[0],1,trainX.shape[1]))
        
        
        keras.backend.clear_session()
        tf.random.set_seed(42)
        np.random.seed(42)
        confirm_model = keras.models.Sequential([
            keras.layers.InputLayer(input_shape=[None, 1]),
            keras.layers.Conv1D(filters=16, kernel_size=2,
                      strides=1, padding="causal",
                      activation="relu",
                      ),
            keras.layers.LSTM(30,kernel_initializer = 'he_normal',
                              return_sequences = True),
            keras.layers.LSTM(30,kernel_initializer = 'he_normal',
                              return_sequences = True),
            keras.layers.Dense(15,kernel_initializer = 'he_normal',
                                             activation = 'relu'),
            keras.layers.Dense(15,kernel_initializer = 'he_normal',
                                             activation = 'relu'),
            keras.layers.Dense(1,activation = 'linear',kernel_initializer = 'he_normal'),
            keras.layers.Lambda(lambda x: x * 200)
             ])
        
        optimizer = keras.optimizers.Adadelta(lr=0.001)
        
        confirm_model.compile(loss=['mae'],optimizer=optimizer)   
                
        confirm_model.fit(trainX, trainY, epochs=100,
                          batch_size = 10,verbose = 0)
        

        confirm_test_seq  = trainX[-1:]
        confirm_test_seq = confirm_test_seq
        confirm_test_seq = confirm_test_seq.reshape(len(confirm_test_seq), time_steps, 1)
        confirm_preds = []
        
        for _ in range (DAYS_TO_PREDICT):
            confirm_pred = confirm_model.predict(confirm_test_seq)
            confirm_preds.append(confirm_pred)
            confirm_new_seq = confirm_pred
            confirm_test_seq = confirm_new_seq
            confirm_test_seq = confirm_test_seq.reshape(len(confirm_test_seq ), time_steps, 1)

        

        return confirm_preds<jupyter_output><empty_output><jupyter_text>Calling the class and predicting the cases for every individual country<jupyter_code>NN = Corona_Confirmed_model()
confirm_predictions = []
for i in range(len(Country_confirmed)):
    result = NN.Model(confirmed_df_scaled,i) 
    confirm_predictions.append(result)<jupyter_output><empty_output><jupyter_text>Processing the predicted data<jupyter_code>confirm_predictions = (np.array(confirm_predictions).transpose())
confirm_predictions = confirm_predictions.reshape(((DAYS_TO_PREDICT),len(Country_confirmed)))
confirm_predictions = sc.inverse_transform(confirm_predictions)
confirm_predictions = pd.DataFrame(confirm_predictions)
confirm_predictions = confirm_predictions.abs()
confirm_predictions['Dates'] = predict_confirm_index
confirm_predictions.set_index('Dates', inplace = True)
confirm_predictions.columns = Country_confirmed
confirm_predictions.head()<jupyter_output><empty_output><jupyter_text>Visualizing The Confirmed Cases For A Country As Per The User's Choice  List of Infected Countries<jupyter_code>Infected_Countries = pd.DataFrame(Country_confirmed)
Infected_Countries.columns = ['Countries']
pd.set_option("max_rows", None)
Infected_Countries<jupyter_output><empty_output><jupyter_text>Select The Country<jupyter_code>Country =input('Enter the name of the country from above list you would like to see the daily cases till now : ')<jupyter_output><empty_output><jupyter_text>Till Date Confirm Cases on daily basis of coronavirus<jupyter_code>fig = go.Figure()
fig.update_layout(template='plotly_dark',title={'text': 'Confirmed Daily Cases','y':0.9,'x':0.5,'xanchor': 'center',
                                                'yanchor': 'top'},
                    xaxis_title = "Dates",
                    yaxis_title="Number Of Cases",
                     )
fig.add_trace(go.Scatter(x=confirmed_df.index, 
                         y=confirmed_df[Country],
                         mode='lines+markers',
                         line=dict(color='blue', width=2)))<jupyter_output><empty_output><jupyter_text>Predictions of confirmed cases of coronavirus<jupyter_code>fig = go.Figure()
fig.update_layout(template='plotly_dark',title={'text': 'Confirmed Cases Predictions','y':0.9,'x':0.5,'xanchor': 'center',
                                                'yanchor': 'top'},
    xaxis_title = "Dates",
    yaxis_title="Number Of Cases")
fig.update_xaxes(tickangle=90, showticklabels = True, type = 'category')
fig.add_trace(go.Scatter(x=confirm_predictions.index, 
                         y=confirm_predictions[Country],
                         mode='lines+markers',
                         line=dict(color='yellow', width=2)))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10759852565920046, 'fraction_numerical': 0.009781684150836405, 'mean_word_length': 3.4993622448979593, 'pattern_counts': {'":': 0, '<': 49, '<?xml version=': 0, '>': 49, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 8, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '279569', 'license': 'Apache-2.0', 'n_tokens_mistral': 2256, 'n_tokens_neox': 2147, 'n_words': 324, 'path': 'Country Wise Confirmed COVID-19 Cases.ipynb', 'repo_name': 'rv20197/COVID-19-Analysis-and-Prediction-Using-AI', 'size': '7054'}