Kaggle competition: OpenVaccine: COVID-19 mRNA Vaccine Degradation Prediction
<SOS> metric: MWCRMSE Kaggle data source: stanford-covid-vaccine<define_variables>
import os
import random
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
import torch.optim.lr_scheduler as lr
from sklearn.model_selection import KFold, GroupKFold
from torch.utils.data import DataLoader, Dataset
from tqdm.notebook import tqdm
import itertools
from sklearn.cluster import KMeans
feat = ['confirmedcases','fatalities','cf_1', 'ft_1', 'cf_2', 'ft_2', 'cf_3', 'ft_3',
'cf_4', 'ft_4', 'cf_5', 'ft_5', 'cf_6', 'ft_6', 'cf_7', 'ft_7', 'cf_8', 'ft_8',
'cf_9', 'ft_9', 'cf_10', 'ft_10', 'cf_11', 'ft_11', 'cf_12', 'ft_12', 'cf_13', 'ft_13',
'cf_14', 'ft_14']
c_feat = ['cp_le', 'weekofyear','quarter','month','dayofyear','cf_1', 'cf_2', 'cf_3',
'cf_4', 'cf_5', 'cf_6', 'cf_7', 'cf_8', 'cf_9','cf_10', 'cf_11', 'cf_12',
'cf_13', 'cf_14']
f_feat = ['cp_le', 'weekofyear','quarter','month','dayofyear','ft_1', 'ft_2', 'ft_3',
'ft_4', 'ft_5', 'ft_6', 'ft_7', 'ft_8', 'ft_9','ft_10', 'ft_11', 'ft_12',
'ft_13', 'ft_14']
tot_feat = ['cp_le', 'weekofyear','quarter','month','dayofyear','cf_1', 'ft_1', 'cf_2', 'ft_2', 'cf_3', 'ft_3',
'cf_4', 'ft_4', 'cf_5', 'ft_5', 'cf_6', 'ft_6', 'cf_7', 'ft_7', 'cf_8', 'ft_8',
'cf_9', 'ft_9', 'cf_10', 'ft_10', 'cf_11', 'ft_11', 'cf_12', 'ft_12', 'cf_13', 'ft_13',
'cf_14', 'ft_14']
test_new = test_df.copy().join(pd.DataFrame(columns=feat))
test_mask =(test_df['date'] <= train_df['date'].max())
 train_mask =(train_df['date'] >= test_df['date'].min())
 test_new.loc[test_mask,feat] = train_df.loc[train_mask, feat].values
future_df = pd.date_range(start = train_df['date'].max() +pd.Timedelta(days=1),end=test_df['date'].max() , freq='1D')
 def create_add_trend_pred(data, cf, ft):
for d in future_df:
for i in data['cp_le'].drop_duplicates() :
org_mask =(data['date']==d)&(data['cp_le']==i)
 for lag in range(1,15):
mask_loc =(data['date']==(d-pd.Timedelta(days=lag)))&(data['cp_le']==i)
 try:
data.loc[org_mask, 'cf_' + str(lag)]=data.loc[mask_loc,cf].values
data.loc[org_mask, 'ft_' + str(lag)]=data.loc[mask_loc,ft].values
except:
data.loc[org_mask, 'cf_' + str(lag)]=0.0
data.loc[org_mask, 'ft_' + str(lag)]=0.0
test_x = data.loc[org_mask,tot_feat]
test_x_cf = test_x[c_feat]
test_x_cf = test_x_cf.to_numpy().reshape(1,-1)
 test_x_cf_reshape = test_x_cf.reshape(test_x_cf.shape[0],1,test_x_cf.shape[1])
 test_x_ft = test_x[f_feat]
test_x_ft = test_x_ft.to_numpy().reshape(1,-1)
 test_x_ft_reshape = test_x_ft.reshape(test_x_ft.shape[0],1,test_x_ft.shape[1])
 data.loc[org_mask, cf] = model_cf.predict(test_x_cf_reshape)
 data.loc[org_mask, ft] = model_ft.predict(test_x_ft_reshape)
 create_add_trend_pred(test_new, 'confirmedcases', 'fatalities' )<save_to_csv>
def seed_everything(seed):
random.seed(seed)
 os.environ["PYTHONHASHSEED"] = str(seed)
 np.random.seed(seed)
 torch.manual_seed(seed)
 torch.cuda.manual_seed(seed)
 torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
sub_pred = pd.DataFrame({'ForecastId': test_id, 'ConfirmedCases':test_new['confirmedcases'],'Fatalities':test_new['fatalities']})
 sub_pred.to_csv('submission.csv', index=False )<load_from_csv>
token2int = {x: i for i, x in enumerate("().AGUCSMIBHEX ")}
dirname = '/kaggle/input/covid19-global-forecasting-week-4/'
trainname = 'train.csv'
trainpath = dirname + trainname
traindata_raw = pd.read_csv(trainpath)
 traindata = collections.defaultdict(lambda :collections.defaultdict(list))
traindata_country = collections.defaultdict(lambda :collections.defaultdict(lambda :[0,0]))
traindata_state = collections.defaultdict(lambda :collections.defaultdict(lambda :[0,0]))
traindata_country_onlymainland = collections.defaultdict(lambda :collections.defaultdict(lambda :[0,0]))
for i in range(len(traindata_raw)) :
country = traindata_raw['Country_Region'][i]
state = traindata_raw['Province_State'][i]
date = traindata_raw['Date'][i]
cases = traindata_raw['ConfirmedCases'][i]
fata = traindata_raw['Fatalities'][i]
traindata[country][date].append(( state, cases, fata))
traindata_country[country][date][0] += cases
traindata_country[country][date][1] += fata
if state != state:
traindata_country_onlymainland[country][date][0] += cases
traindata_country_onlymainland[country][date][1] += fata
state_ = country + ':' + state if state == state else country + ':'
traindata_state[state_][date][0] += cases
traindata_state[state_][date][1] += fata 
<define_variables>
train = pd.read_json(".. /input/stanford-covid-vaccine/train.json", lines=True)
 test = pd.read_json(".. /input/stanford-covid-vaccine/test.json", lines=True )
predictdata_state = collections.defaultdict(lambda :[[],[]])
 for state in traindata_state:
state_history = [[],[]]
for date in traindata_state[state]:
state_history[0].append(traindata_state[state][date][0])
 state_history[1].append(traindata_state[state][date][1])
 i = 0
for perspective in state_history:
perspective_train = [i for i in perspective[:] if i!=0]
perspective = [i for i in perspective if i!=0]
x_all = np.array(range(1, len(perspective)+ 31))
x = x_all[:len(perspective_train)]
y = np.array(perspective_train)
 if len(perspective_train)< 3:
if not perspective_train:
predict_y = np.zeros(len(x_all[len(perspective_train):]))
else:
predict_y = np.array([perspective_train[-1]]*(len(x_all[len(perspective_train):])))
 predictdata_state[state][i] = predict_y
i =(i+1)% 2
continue
if True:
def funmi(x, a, b, c):
return(x/a)**b + c
def funexp(x,a,b,c):
return(a**(x + b)) * c
def funline(x, a):
return a*x
def funsigmoid(x, a, b, c):
s = a /(1 + np.exp(-(x - b)/ c))
return s
p0 = [max(perspective_train)*2, max(x), 5]
if y[-1] > 10:
popt, pcov = curve_fit(funsigmoid, x, y, maxfev = 50000, p0=p0)
 else:
popt, pcov = curve_fit(funline, x, y, maxfev = 50000)
 predict_x = x_all[len(perspective_train):]
if y[-1] > 10:
severe_coefficient = 1.1 if 'China' not in state else 1.0
predict_y = [funsigmoid(i, *popt)* severe_coefficient for i in predict_x]
else:
predict_y = [funline(i, *popt)for i in predict_x]
if predict_y[0] < perspective_train[-1]:
predict_y = [i +(perspective_train[-1] - predict_y[0])for i in predict_y]
predict_y = [round(i)for i in predict_y]
predictdata_state[state][i] = predict_y
i =(i+1)% 2 
<load_from_csv>
temp = np.array(train["sequence"].apply(lambda seq: [token2int[x] for x in seq] ).values.tolist())
 kmeans = KMeans(n_clusters=200, random_state=42 ).fit(temp)
 train["cluster"] = kmeans.labels_
testname = 'test.csv'
testpath = dirname + testname
testdata = pd.read_csv(testpath)
 submname = 'submission.csv'
submpath = dirname + submname
submdata = pd.read_csv(submpath)
 res = []
ind = 0
found = False
for i in range(len(testdata)) :
forecastid = testdata['ForecastId'][i]
state = testdata['Province_State'][i]
country = testdata['Country_Region'][i]
date = testdata['Date'][i]
state_ = country + ':' + state if state == state else country + ':'
if date == '2020-04-02':
found = True
if date == '2020-04-15':
found = False
ind = 0
if found:
res.append(traindata_state[state_][date])
 else:
res.append([int(predictdata_state[state_][0][ind]), int(predictdata_state[state_][1][ind])])
 ind += 1
subm_cases = [i[0] for i in res]
subm_fata = [i[1] for i in res]
submdata['ConfirmedCases'] = subm_cases
submdata['Fatalities'] = subm_fata
submdata.to_csv('submission.csv', index = False )<set_options>
def read_bpps_sum(df):
bpps_arr = []
for mol_id in df.id.to_list() :
bpps_arr.append(np.load(f".. /input/stanford-covid-vaccine/bpps/{mol_id}.npy" ).max(axis=1))
return bpps_arr
def read_bpps_max(df):
bpps_arr = []
for mol_id in df.id.to_list() :
bpps_arr.append(np.load(f".. /input/stanford-covid-vaccine/bpps/{mol_id}.npy" ).sum(axis=1))
return bpps_arr
def read_bpps_nb(df):
bpps_nb_mean = 0.077522
bpps_nb_std = 0.08914
bpps_arr = []
for mol_id in df.id.to_list() :
bpps = np.load(f".. /input/stanford-covid-vaccine/bpps/{mol_id}.npy")
 bpps_nb =(bpps > 0 ).sum(axis=0)/ bpps.shape[0]
bpps_nb =(bpps_nb - bpps_nb_mean)/ bpps_nb_std
bpps_arr.append(bpps_nb)
 return bpps_arr
train["bpps_sum"] = read_bpps_sum(train)
 train["bpps_max"] = read_bpps_max(train)
 train["bpps_nb"] = read_bpps_nb(train)
 test["bpps_sum"] = read_bpps_sum(test)
 test["bpps_max"] = read_bpps_max(test)
 test["bpps_nb"] = read_bpps_nb(test )
pd.options.display.max_rows = 500
pd.options.display.max_columns = 500
%matplotlib inline
def rmse(yt, yp):
return np.sqrt(np.mean(( yt-yp)**2))
class CovidModel:
def __init__(self):
pass
def predict_first_day(self, date):
return None
def predict_next_day(self, yesterday_pred_df):
return None
class CovidModelAhmet(CovidModel):
def preprocess(self, df, meta_df):
df["Date"] = pd.to_datetime(df['Date'])
 df = df.merge(meta_df, on=self.loc_group, how="left")
 df["lat"] =(df["lat"] // 30 ).astype(np.float32 ).fillna(0)
 df["lon"] =(df["lon"] // 60 ).astype(np.float32 ).fillna(0)
 df["population"] = np.log1p(df["population"] ).fillna(-1)
 df["area"] = np.log1p(df["area"] ).fillna(-1)
 for col in self.loc_group:
df[col].fillna("", inplace=True)
 df['day'] = df.Date.dt.dayofyear
df['geo'] = ['_'.join(x)for x in zip(df['Country_Region'], df['Province_State'])]
return df
def get_model(self):
def nn_block(input_layer, size, dropout_rate, activation):
out_layer = KL.Dense(size, activation=None )(input_layer)
 out_layer = KL.Activation(activation )(out_layer)
 out_layer = KL.Dropout(dropout_rate )(out_layer)
 return out_layer
ts_inp = KL.Input(shape=(len(self.ts_features),))
global_inp = KL.Input(shape=(len(self.global_features),))
inp = KL.concatenate([global_inp, ts_inp])
 hidden_layer = nn_block(inp, 64, 0.0, "relu")
 gate_layer = nn_block(hidden_layer, 32, 0.0, "sigmoid")
 hidden_layer = nn_block(hidden_layer, 32, 0.0, "relu")
 hidden_layer = KL.multiply([hidden_layer, gate_layer])
 out = KL.Dense(len(self.TARGETS), activation="linear" )(hidden_layer)
 model = tf.keras.models.Model(inputs=[global_inp, ts_inp], outputs=out)
 return model
def get_input(self, df):
return [df[self.global_features], df[self.ts_features]]
def train_models(self, df, num_models=20, save=False):
def custom_loss(y_true, y_pred):
return K.sum(K.sqrt(K.sum(K.square(y_true - y_pred), axis=0, keepdims=True)))/len(self.TARGETS)
 models = []
for i in range(num_models):
model = self.get_model()
model.compile(loss=custom_loss, optimizer=Nadam(lr=1e-4))
hist = model.fit(self.get_input(df), df[self.TARGETS],
batch_size=2048, epochs=200, verbose=0, shuffle=True)
 if save:
model.save_weights("model{}.h5".format(i))
models.append(model)
 return models
def predict_one(self, df):
pred = np.zeros(( df.shape[0], 2))
for model in self.models:
pred += model.predict(self.get_input(df)) /len(self.models)
 pred = np.maximum(pred, df[self.prev_targets].values)
 pred[:, 0] = np.log1p(np.expm1(pred[:, 0])+ 0.1)
 pred[:, 1] = np.log1p(np.expm1(pred[:, 1])+ 0.01)
 return np.clip(pred, None, 15)
 def __init__(self):
df = pd.read_csv(".. /input/covid19-global-forecasting-week-4/train.csv")
 sub_df = pd.read_csv(".. /input/covid19-global-forecasting-week-4/test.csv")
 meta_df = pd.read_csv(".. /input/covid19-forecasting-metadata/region_metadata.csv")
 self.loc_group = ["Province_State", "Country_Region"]
df = self.preprocess(df, meta_df)
 sub_df = self.preprocess(sub_df, meta_df)
 df = df.merge(sub_df[["ForecastId", "Date", "geo"]], how="left", on=["Date", "geo"])
 df = df.append(sub_df[sub_df["Date"] > df["Date"].max() ], sort=False)
 df["day"] = df["day"] - df["day"].min()
self.TARGETS = ["ConfirmedCases", "Fatalities"]
self.prev_targets = ['prev_ConfirmedCases_1', 'prev_Fatalities_1']
for col in self.TARGETS:
df[col] = np.log1p(df[col])
 self.NUM_SHIFT = 7
self.global_features = ["lat", "lon", "population", "area"]
self.ts_features = []
for s in range(1, self.NUM_SHIFT+1):
for col in self.TARGETS:
df["prev_{}_{}".format(col, s)] = df.groupby(self.loc_group)[col].shift(s)
 self.ts_features.append("prev_{}_{}".format(col, s))
self.df = df[df["Date"] >= df["Date"].min() + timedelta(days=self.NUM_SHIFT)].copy()
def predict_first_day(self, day):
self.models = self.train_models(self.df[self.df["day"] < day])
 temp_df = self.df.loc[self.df["day"] == day].copy()
y_pred = self.predict_one(temp_df)
 self.y_prevs = [None]*self.NUM_SHIFT
for i in range(1, self.NUM_SHIFT):
self.y_prevs[i] = temp_df[['prev_ConfirmedCases_{}'.format(i), 'prev_Fatalities_{}'.format(i)]].values
temp_df[self.TARGETS] = y_pred
self.day = day
return temp_df[["geo", "day"] + self.TARGETS]
def predict_next_day(self, yesterday_pred_df):
self.day = self.day + 1
temp_df = self.df.loc[self.df["day"] == self.day].copy()
yesterday_pred_df = temp_df[["geo"]].merge(yesterday_pred_df[["geo"] + self.TARGETS], on="geo", how="left")
 temp_df[self.prev_targets] = yesterday_pred_df[self.TARGETS].values
for i in range(2, self.NUM_SHIFT+1):
temp_df[['prev_ConfirmedCases_{}'.format(i), 'prev_Fatalities_{}'.format(i)]] = self.y_prevs[i-1]
y_pred, self.y_prevs = self.predict_one(temp_df), [None, temp_df[self.prev_targets].values] + self.y_prevs[1:-1]
temp_df[self.TARGETS] = y_pred
return temp_df[["geo", "day"] + self.TARGETS] 
<load_from_csv>
targets = ["reactivity", "deg_Mg_pH10", "deg_pH10", "deg_Mg_50C", "deg_50C"]
class CovidModel:
def __init__(self):
pass
def predict_first_day(self, date):
return None
def predict_next_day(self, yesterday_pred_df):
return None
class CovidModelGIBA(CovidModel):
def __init__(self, lag=1, seed=1):
self.lag = lag
self.seed = seed
print('Lag:', lag, 'Seed:', seed)
 train = pd.read_csv('.. /input/covid19-global-forecasting-week-4/train.csv')
 train['Date'] = pd.to_datetime(train['Date'])
 self.maxdate = str(train['Date'].max())[:10]
self.testdate = str(train['Date'].max() + pd.Timedelta(days=1)) [:10]
print('Last Date in Train:',self.maxdate, 'Test first Date:',self.testdate)
 train['Province_State'].fillna('', inplace=True)
 train['day'] = train.Date.dt.dayofyear
self.day_min = train['day'].min()
train['day'] -= self.day_min
train['geo'] = ['_'.join(x)for x in zip(train['Country_Region'], train['Province_State'])]
test = pd.read_csv('.. /input/covid19-global-forecasting-week-4/test.csv')
 test['Date'] = pd.to_datetime(test['Date'])
 test['Province_State'].fillna('', inplace=True)
 test['day'] = test.Date.dt.dayofyear
test['day'] -= self.day_min
test['geo'] = ['_'.join(x)for x in zip(test['Country_Region'], test['Province_State'])]
test['Id'] = -1
test['ConfirmedCases'] = 0
test['Fatalities'] = 0
self.trainmaxday = train['day'].max()
self.testday1 = train['day'].max() + 1
self.testdayN = test['day'].max()
publictest = test.loc[ test.Date > train.Date.max() ].copy()
train = pd.concat(( train, publictest), sort=False)
 train.sort_values(['Country_Region','Province_State','Date'], inplace=True)
 train = train.reset_index(drop=True)
 train['ForecastId'] = pd.merge(train, test, on=['Country_Region','Province_State','Date'], how='left')['ForecastId_y'].values
train['cid'] = train['Country_Region'] + '_' + train['Province_State']
train['log0'] = np.log1p(train['ConfirmedCases'])
 train['log1'] = np.log1p(train['Fatalities'])
 train = train.loc[(train.log0 > 0)|(train.ForecastId.notnull())|(train.Date >= '2020-03-17')].copy()
train = train.reset_index(drop=True)
 train['days_since_1case'] = train.groupby('cid')['Id'].cumcount()
dt = pd.read_csv('.. /input/covid19-lockdown-dates-by-country/countryLockdowndates.csv')
 dt.columns = ['Country_Region','Province_State','Date','Type','Reference']
dt = dt.loc[ dt.Date == dt.Date ]
dt['Province_State'] = dt['Province_State'].fillna('')
 dt['Date'] = pd.to_datetime(dt['Date'])
 dt['Date'] = dt['Date'] + pd.Timedelta(days=8)
 dt['Type'] = pd.factorize(dt['Type'])[0]
dt['cid'] = dt['Country_Region'] + '_' + dt['Province_State']
del dt['Reference'], dt['Country_Region'], dt['Province_State']
train = pd.merge(train, dt, on=['cid','Date'], how='left')
 train['Type'] = train.groupby('cid')['Type'].fillna(method='ffill')
 train['target0'] = np.log1p(train['ConfirmedCases'])
 train['target1'] = np.log1p(train['Fatalities'])
 self.train = train.copy()
def create_features(self, df, valid_day):
df = df.loc[ df.day>=(valid_day-50)].copy()
df['lag0_1'] = df.groupby('cid')['target0'].shift(self.lag)
 df['lag0_1'] = df.groupby('cid')['lag0_1'].fillna(method='bfill')
 df['lag0_8'] = df.groupby('cid')['target0'].shift(8)
 df['lag0_8'] = df.groupby('cid')['lag0_8'].fillna(method='bfill')
 df['lag1_1'] = df.groupby('cid')['target1'].shift(self.lag)
 df['lag1_1'] = df.groupby('cid')['lag1_1'].fillna(method='bfill')
 df['m0'] = df.groupby('cid')['lag0_1'].rolling(2 ).mean().values
df['m1'] = df.groupby('cid')['lag0_1'].rolling(3 ).mean().values
df['m2'] = df.groupby('cid')['lag0_1'].rolling(4 ).mean().values
df['m3'] = df.groupby('cid')['lag0_1'].rolling(5 ).mean().values
df['m4'] = df.groupby('cid')['lag0_1'].rolling(7 ).mean().values
df['m5'] = df.groupby('cid')['lag0_1'].rolling(10 ).mean().values
df['m6'] = df.groupby('cid')['lag0_1'].rolling(12 ).mean().values
df['m7'] = df.groupby('cid')['lag0_1'].rolling(16 ).mean().values
df['m8'] = df.groupby('cid')['lag0_1'].rolling(20 ).mean().values
df['m9'] = df.groupby('cid')['lag0_1'].rolling(25 ).mean().values
df['n0'] = df.groupby('cid')['lag1_1'].rolling(2 ).mean().values
df['n1'] = df.groupby('cid')['lag1_1'].rolling(3 ).mean().values
df['n2'] = df.groupby('cid')['lag1_1'].rolling(4 ).mean().values
df['n3'] = df.groupby('cid')['lag1_1'].rolling(5 ).mean().values
df['n4'] = df.groupby('cid')['lag1_1'].rolling(7 ).mean().values
df['n5'] = df.groupby('cid')['lag1_1'].rolling(10 ).mean().values
df['n6'] = df.groupby('cid')['lag1_1'].rolling(12 ).mean().values
df['n7'] = df.groupby('cid')['lag1_1'].rolling(16 ).mean().values
df['n8'] = df.groupby('cid')['lag1_1'].rolling(20 ).mean().values
df['m0'] = df.groupby('cid')['m0'].fillna(method='bfill')
 df['m1'] = df.groupby('cid')['m1'].fillna(method='bfill')
 df['m2'] = df.groupby('cid')['m2'].fillna(method='bfill')
 df['m3'] = df.groupby('cid')['m3'].fillna(method='bfill')
 df['m4'] = df.groupby('cid')['m4'].fillna(method='bfill')
 df['m5'] = df.groupby('cid')['m5'].fillna(method='bfill')
 df['m6'] = df.groupby('cid')['m6'].fillna(method='bfill')
 df['m7'] = df.groupby('cid')['m7'].fillna(method='bfill')
 df['m8'] = df.groupby('cid')['m8'].fillna(method='bfill')
 df['m9'] = df.groupby('cid')['m9'].fillna(method='bfill')
 df['n0'] = df.groupby('cid')['n0'].fillna(method='bfill')
 df['n1'] = df.groupby('cid')['n1'].fillna(method='bfill')
 df['n2'] = df.groupby('cid')['n2'].fillna(method='bfill')
 df['n3'] = df.groupby('cid')['n3'].fillna(method='bfill')
 df['n4'] = df.groupby('cid')['n4'].fillna(method='bfill')
 df['n5'] = df.groupby('cid')['n5'].fillna(method='bfill')
 df['n6'] = df.groupby('cid')['n6'].fillna(method='bfill')
 df['n7'] = df.groupby('cid')['n7'].fillna(method='bfill')
 df['n8'] = df.groupby('cid')['n8'].fillna(method='bfill')
 df['flag_China'] = 1*(df['Country_Region'] == 'China')
 df['flag_US'] = 1*(df['Country_Region'] == 'US')
 df['flag_Kosovo_'] = 1*(df['cid'] == 'Kosovo_')
 df['flag_Korea'] = 1*(df['cid'] == 'Korea, South_')
 df['flag_Nepal_'] = 1*(df['cid'] == 'Nepal_')
 df['flag_Holy See_'] = 1*(df['cid'] == 'Holy See_')
 df['flag_Suriname_'] = 1*(df['cid'] == 'Suriname_')
 df['flag_Ghana_'] = 1*(df['cid'] == 'Ghana_')
 df['flag_Togo_'] = 1*(df['cid'] == 'Togo_')
 df['flag_Malaysia_'] = 1*(df['cid'] == 'Malaysia_')
 df['flag_US_Rhode'] = 1*(df['cid'] == 'US_Rhode Island')
 df['flag_Bolivia_'] = 1*(df['cid'] == 'Bolivia_')
 df['flag_China_Tib'] = 1*(df['cid'] == 'China_Tibet')
 df['flag_Bahrain_'] = 1*(df['cid'] == 'Bahrain_')
 df['flag_Honduras_'] = 1*(df['cid'] == 'Honduras_')
 df['flag_Bangladesh']= 1*(df['cid'] == 'Bangladesh_')
 df['flag_Paraguay_'] = 1*(df['cid'] == 'Paraguay_')
 tr = df.loc[ df.day < valid_day ].copy()
vl = df.loc[ df.day == valid_day ].copy()
tr = tr.loc[ tr.lag0_1 > 0 ].copy()
maptarget0 = tr.groupby('cid')['target0'].agg(log0_max='max' ).reset_index()
maptarget1 = tr.groupby('cid')['target1'].agg(log1_max='max' ).reset_index()
vl['log0_max'] = pd.merge(vl, maptarget0, on='cid' , how='left')['log0_max'].values
vl['log1_max'] = pd.merge(vl, maptarget1, on='cid' , how='left')['log1_max'].values
vl['log0_max'] = vl['log0_max'].fillna(0)
 vl['log1_max'] = vl['log1_max'].fillna(0)
 return tr, vl
def train_models(self, valid_day = 10):
train = self.train.copy()
train.loc[(train.cid=='China_Guizhou')&(train.Date=='2020-03-17'), 'target0' ] = np.log1p(146)
 train.loc[(train.cid=='Guyana_')&(train.Date>='2020-03-22')&(train.Date<='2020-03-30'), 'target0' ] = np.log1p(12)
 train.loc[(train.cid=='US_Virgin Islands')&(train.Date>='2020-03-29')&(train.Date<='2020-03-29'), 'target0' ] = np.log1p(24)
 train.loc[(train.cid=='US_Virgin Islands')&(train.Date>='2020-03-30')&(train.Date<='2020-03-30'), 'target0' ] = np.log1p(27)
 train.loc[(train.cid=='Iceland_')&(train.Date>='2020-03-15')&(train.Date<='2020-03-15'), 'target1' ] = np.log1p(0)
 train.loc[(train.cid=='Kazakhstan_')&(train.Date>='2020-03-20')&(train.Date<='2020-03-20'), 'target1' ] = np.log1p(0)
 train.loc[(train.cid=='Serbia_')&(train.Date>='2020-03-26')&(train.Date<='2020-03-26'), 'target1' ] = np.log1p(5)
 train.loc[(train.cid=='Serbia_')&(train.Date>='2020-03-27')&(train.Date<='2020-03-27'), 'target1' ] = np.log1p(6)
 train.loc[(train.cid=='Slovakia_')&(train.Date>='2020-03-22')&(train.Date<='2020-03-31'), 'target1' ] = np.log1p(1)
 train.loc[(train.cid=='US_Hawaii')&(train.Date>='2020-03-25')&(train.Date<='2020-03-31'), 'target1' ] = np.log1p(1)
 param = {
'subsample': 1.000,
'colsample_bytree': 0.85,
'max_depth': 5,
'gamma': 0.000,
'learning_rate': 0.010,
'min_child_weight': 6.00,
'reg_alpha': 0.000,
'reg_lambda': 0.400,
'silent':1,
'objective':'reg:squarederror',
'nthread': 12,
'seed': self.seed
}
tr, vl = self.create_features(train.copy() , valid_day)
 features = [f for f in tr.columns if f not in [
'lag0_8',
'Id','ConfirmedCases','Fatalities','log0','log1','target0','target1','ypred0','ypred1','Province_State','Country_Region','Date','ForecastId','cid','geo','day',
'GDP_region','TRUE POPULATION','pct_in_largest_city',' TFR ',' Avg_age ','latitude','longitude','abs_latitude','temperature', 'humidity',
'Personality_pdi','Personality_idv','Personality_mas','Personality_uai','Personality_ltowvs','Personality_assertive','personality_perform','personality_agreeableness',
'murder','High_rises','max_high_rises','AIR_CITIES','AIR_AVG','continent_gdp_pc','continent_happiness','continent_generosity','continent_corruption','continent_Life_expectancy'
] ]
self.features0 = features
features = [f for f in tr.columns if f not in [
'm0','m1','m2','m3',
'Id','ConfirmedCases','Fatalities','log0','log1','target0','target1','ypred0','ypred1','Province_State','Country_Region','Date','ForecastId','cid','geo','day',
'GDP_region','TRUE POPULATION','pct_in_largest_city',' TFR ',' Avg_age ','latitude','longitude','abs_latitude','temperature', 'humidity',
'Personality_pdi','Personality_idv','Personality_mas','Personality_uai','Personality_ltowvs','Personality_assertive','personality_perform','personality_agreeableness',
'murder','High_rises','max_high_rises','AIR_CITIES','AIR_AVG','continent_gdp_pc','continent_happiness','continent_generosity','continent_corruption','continent_Life_expectancy'
] ]
self.features1 = features
nrounds0 = 680
nrounds1 = 630
dtrain = xgb.DMatrix(tr[self.features0], tr['target0'])
 param['seed'] = self.seed
self.model0 = xgb.train(param, dtrain, nrounds0, verbose_eval=0)
 param['seed'] = self.seed+1
self.model1 = xgb.train(param, dtrain, nrounds0, verbose_eval=0)
 dtrain = xgb.DMatrix(tr[self.features1], tr['target1'])
 param['seed'] = self.seed
self.model2 = xgb.train(param, dtrain, nrounds1, verbose_eval=0)
 param['seed'] = self.seed+1
self.model3 = xgb.train(param, dtrain, nrounds1, verbose_eval=0)
 self.vl = vl
return 1
def predict_first_day(self, day):
self.day = day
self.train_models(day)
 dvalid = xgb.DMatrix(self.vl[self.features0])
 ypred0 =(self.model0.predict(dvalid)+ self.model1.predict(dvalid)) / 2
dvalid = xgb.DMatrix(self.vl[self.features1])
 ypred1 =(self.model2.predict(dvalid)+ self.model3.predict(dvalid)) / 2
self.vl['ypred0'] = ypred0
self.vl['ypred1'] = ypred1
self.vl.loc[ self.vl.ypred0<self.vl.log0_max, 'ypred0'] = self.vl.loc[ self.vl.ypred0<self.vl.log0_max, 'log0_max']
self.vl.loc[ self.vl.ypred1<self.vl.log1_max, 'ypred1'] = self.vl.loc[ self.vl.ypred1<self.vl.log1_max, 'log1_max']
VALID = self.vl[["geo", "day", 'ypred0', 'ypred1']].copy()
VALID.columns = ["geo", "day", 'ConfirmedCases', 'Fatalities']
return VALID.reset_index(drop=True)
 def predict_next_day(self, yesterday):
self.day += 1
feats = ['geo','day']
self.train[ 'ypred0' ] = pd.merge(self.train[feats], yesterday[feats+['ConfirmedCases']], on=feats, how='left')['ConfirmedCases'].values
self.train.loc[ self.train.ypred0.notnull() , 'target0'] = self.train.loc[ self.train.ypred0.notnull() , 'ypred0']
self.train[ 'ypred1' ] = pd.merge(self.train[feats], yesterday[feats+['Fatalities']], on=feats, how='left')['Fatalities'].values
self.train.loc[ self.train.ypred1.notnull() , 'target1'] = self.train.loc[ self.train.ypred1.notnull() , 'ypred1']
del self.train['ypred0'], self.train['ypred1']
tr, vl = self.create_features(self.train.copy() , self.day)
 dvalid = xgb.DMatrix(vl[self.features0])
 ypred0 =(self.model0.predict(dvalid)+ self.model1.predict(dvalid)) /2
dvalid = xgb.DMatrix(vl[self.features1])
 ypred1 =(self.model2.predict(dvalid)+ self.model3.predict(dvalid)) /2
vl['ypred0'] = ypred0
vl['ypred1'] = ypred1
vl.loc[ vl.ypred0<vl.log0_max, 'ypred0'] = vl.loc[ vl.ypred0<vl.log0_max, 'log0_max']
vl.loc[ vl.ypred1<vl.log1_max, 'ypred1'] = vl.loc[ vl.ypred1<vl.log1_max, 'log1_max']
self.vl = vl
VALID = vl[["geo", "day", 'ypred0', 'ypred1']].copy()
VALID.columns = ["geo", "day", 'ConfirmedCases', 'Fatalities']
return VALID.reset_index(drop=True )<load_from_csv>
train["seq_masked_1"] = train.apply(lambda x: "".join([y if x.structure[i] == "." else " " for i, y in enumerate(x.sequence)]), axis=1)
 train["seq_masked_2"] = train.apply(lambda x: "".join([y if x.structure[i] == "(" else " " for i, y in enumerate(x.sequence)]), axis=1)
 train["seq_masked_3"] = train.apply(lambda x: "".join([y if x.structure[i] == ")" else " " for i, y in enumerate(x.sequence)]), axis=1)
 test["seq_masked_1"] = test.apply(lambda x: "".join([y if x.structure[i] == "." else " " for i, y in enumerate(x.sequence)]), axis=1)
 test["seq_masked_2"] = test.apply(lambda x: "".join([y if x.structure[i] == "(" else " " for i, y in enumerate(x.sequence)]), axis=1)
 test["seq_masked_3"] = test.apply(lambda x: "".join([y if x.structure[i] == ")" else " " for i, y in enumerate(x.sequence)]), axis=1 )
TARGETS = ["ConfirmedCases", "Fatalities"]
def rmse(y_true, y_pred):
return np.sqrt(mean_squared_error(y_true, y_pred))
df = pd.read_csv(".. /input/covid19-global-forecasting-week-4/train.csv")
 df[TARGETS] = np.log1p(df[TARGETS].values)
 sub_df = pd.read_csv(".. /input/covid19-global-forecasting-week-4/test.csv")
 def preprocess(df):
for col in ["Country_Region", "Province_State"]:
df[col].fillna("", inplace=True)
 df["Date"] = pd.to_datetime(df['Date'])
 df['day'] = df.Date.dt.dayofyear
df['geo'] = ['_'.join(x)for x in zip(df['Country_Region'], df['Province_State'])]
return df
df = preprocess(df)
 sub_df = preprocess(sub_df)
 sub_df["day"] -= df["day"].min()
df["day"] -= df["day"].min()<merge>
class MyDataset(Dataset):
def __init__(self, df, mode="train"):
self.df = df.reset_index(drop=True)
 self.mode = mode
def __len__(self):
return len(self.df)
 def __getitem__(self, idx):
x1 = np.array(self.df.loc[idx, ["sequence", "structure", "predicted_loop_type", "seq_masked_1", "seq_masked_2", "seq_masked_3"]].apply(lambda seq: [token2int[x] for x in seq] ).values.tolist() ).transpose(1, 0)
 x2 = np.array(self.df.loc[idx, ["bpps_sum", "bpps_max", "bpps_nb"]].values.tolist() ).transpose(1, 0)
 if self.mode == "train":
return x1, x2, np.array(self.df.loc[idx, targets].values.tolist() ).transpose(1, 0)
 elif self.mode == "test":
return x1, x2
else:
return None
print(sub_df.shape)
 sub_df = sub_df.merge(df.append(eval_df, sort=False), on=["geo", "day"], how="left")
 print(sub_df.shape)
 print(sub_df[TARGETS].isnull().mean() )<define_variables>
class MyModel(nn.Module):
def __init__(self, args):
super().__init__()
self.embedding = nn.Embedding(num_embeddings=args["num_embeddings"], embedding_dim=args["embedding_dim"])
 self.lstm = nn.LSTM(input_size=args["in_features"] * args["embedding_dim"] + 3, hidden_size=args["lstm_hidden"], num_layers=args["lstm_layers"], bias=True, batch_first=True, dropout=args["lstm_dropout"], bidirectional=True)
 self.fc = nn.Linear(2 * args["lstm_hidden"], args["out_features"])
 def forward(self, x1, x2):
x1 = self.embedding(x1.long() ).view(x1.shape[0], x1.shape[1], -1)
 x = torch.cat(( x1, x2), dim=2)
 x = self.lstm(x)[0][:, :x1.shape[1]]
x = self.fc(x)
 return x
def count_parameters(self):
return sum(p.numel() for p in self.parameters() if p.requires_grad )
flat = [
'China_Anhui',
'China_Beijing',
'China_Chongqing',
'China_Fujian',
'China_Gansu',
'China_Guangdong',
'China_Guangxi',
'China_Guizhou',
'China_Hainan',
'China_Hebei',
'China_Heilongjiang',
'China_Henan',
'China_Hubei',
'China_Hunan',
'China_Jiangsu',
'China_Jiangxi',
'China_Jilin',
'China_Liaoning',
'China_Ningxia',
'China_Qinghai',
'China_Shaanxi',
'China_Shandong',
'China_Shanxi',
'China_Sichuan',
'China_Tibet',
'China_Xinjiang',
'China_Yunnan',
'China_Zhejiang',
'Diamond Princess_',
'Holy See_',
]<feature_engineering>
def get_lr(optimizer):
for p in optimizer.param_groups:
return p["lr"]
dt = sub_df.loc[ sub_df.Date_x == "2020-04-13" ].copy()
dt = dt.loc[ dt.geo.isin(flat)].copy()
dt = dt[['geo','Date_x','day','ConfirmedCases','Fatalities']].copy()
dt = dt.reset_index(drop=True)
 dt<merge>
def MCRMSE(y_pred, y_true):
colwise_mse = torch.mean(( y_pred - y_true)**2, axis=1)
 return torch.mean(torch.sqrt(colwise_mse))
sub_df['ow0'] = pd.merge(sub_df, dt, on='geo', how='left')['ConfirmedCases_y'].values
sub_df['ow1'] = pd.merge(sub_df, dt, on='geo', how='left')['Fatalities_y'].values
sub_df.tail(60 )<filter>
TRAIN_MODE = False
args = {
"batch_size": 228,
"device": torch.device("cuda"),
"dtype": torch.float,
"embedding_dim": 41,
"epochs": 100,
"factor": 0.40876664932540246,
"folds": 5,
"in_features": 6,
"lr": 0.000514670300651814,
"lstm_dropout": 0.3,
"lstm_hidden": 765,
"lstm_layers": 2,
"min_lr": 1e-8,
"num_embeddings": len(token2int),
"out_features": 5,
"patience": 10,
"seed": 42,
"weight_decay": 0.23884714200145296,
}
sub_df.loc[ sub_df.geo.isin(flat)]<filter>
if TRAIN_MODE:
seed_everything(args["seed"])
 kfold = GroupKFold(n_splits=args["folds"])
 for fold,(train_idx, dev_idx)in enumerate(kfold.split(train, groups=train["cluster"])) :
train_loader = DataLoader(MyDataset(train.iloc[train_idx]), batch_size=args["batch_size"], shuffle=True, num_workers=3, pin_memory=True)
 dev_loader = DataLoader(MyDataset(train.iloc[dev_idx]), batch_size=args["batch_size"], shuffle=False, num_workers=3, pin_memory=True)
 model = MyModel(args ).to(device=args["device"], dtype=args["dtype"])
 optimizer = optim.AdamW(model.parameters() , lr=args["lr"], weight_decay=args["weight_decay"])
 scheduler = lr.ReduceLROnPlateau(optimizer, mode="min", factor=args["factor"], patience=args["patience"])
 pbar = tqdm(range(args["epochs"]))
best_loss = np.inf
for epoch in pbar:
model.train()
for x1, x2, y in train_loader:
x1 = x1.to(device=args["device"], dtype=torch.long)
 x2 = x2.to(device=args["device"], dtype=args["dtype"])
 y = y.to(device=args["device"], dtype=args["dtype"])
 y_pred = model(x1, x2)[:, :y.shape[1]]
loss = MCRMSE(y_pred, y)
 optimizer.zero_grad()
loss.backward()
optimizer.step()
model.eval()
train_loss = 0
dev_loss = 0
with torch.no_grad() :
for batch,(x1, x2, y)in enumerate(train_loader):
x1 = x1.to(device=args["device"], dtype=torch.long)
 x2 = x2.to(device=args["device"], dtype=args["dtype"])
 y = y.to(device=args["device"], dtype=args["dtype"])
 y_pred = model(x1, x2)[:, :y.shape[1]]
loss = MCRMSE(y_pred, y)
 train_loss =(batch * train_loss + loss.item())/(batch + 1)
 for batch,(x1, x2, y)in enumerate(dev_loader):
x1 = x1.to(device=args["device"], dtype=torch.long)
 x2 = x2.to(device=args["device"], dtype=args["dtype"])
 y = y.to(device=args["device"], dtype=args["dtype"])
 y_pred = model(x1, x2)[:, :y.shape[1]]
loss = MCRMSE(y_pred, y)
 dev_loss =(batch * dev_loss + loss.item())/(batch + 1)
 scheduler.step(dev_loss)
 pbar.set_description("train: {:.5f} dev: {:.5f}".format(train_loss, dev_loss))
if dev_loss < best_loss:
best_loss = dev_loss
torch.save(model.state_dict() , "model_fold_{}.pth".format(fold))
if get_lr(optimizer)< args["min_lr"]:
break
print(best_loss )
sub_df.loc[ sub_df.ow0.notnull() &(sub_df.Date_x >= '2020-04-14'), 'ConfirmedCases' ] = sub_df.loc[ sub_df.ow0.notnull() &(sub_df.Date_x >= '2020-04-14'), 'ow0' ]
sub_df.loc[ sub_df.ow1.notnull() &(sub_df.Date_x >= '2020-04-14'), 'Fatalities' ] = sub_df.loc[ sub_df.ow1.notnull() &(sub_df.Date_x >= '2020-04-14'), 'ow1' ]<filter>
public_test = test[test["seq_length"] == 107].copy()
private_test = test[test["seq_length"] == 130].copy()
sub_df.loc[ sub_df.geo.isin(flat)]<save_to_csv>
public_preds = np.zeros(( len(public_test), 107, len(targets)))
 private_preds = np.zeros(( len(private_test), 130, len(targets)))
 for fold in range(args["folds"]):
model = MyModel(args ).to(device=args["device"], dtype=args["dtype"])
 if TRAIN_MODE:
model.load_state_dict(torch.load("model_fold_{}.pth".format(fold)))
 else:
model.load_state_dict(torch.load(".. /input/openvaccine-trained/model_fold_{}.pth".format(fold)))
 model = model.eval()
public_test_loader = DataLoader(MyDataset(public_test, mode="test"), batch_size=args["batch_size"], shuffle=False, num_workers=3, pin_memory=True)
 private_test_loader = DataLoader(MyDataset(private_test, mode="test"), batch_size=args["batch_size"], shuffle=False, num_workers=3, pin_memory=True)
 with torch.no_grad() :
public_fold_preds = []
for batch,(x1, x2)in enumerate(public_test_loader):
x1 = x1.to(device=args["device"], dtype=torch.long)
 x2 = x2.to(device=args["device"], dtype=torch.long)
 y_pred = model(x1, x2 ).cpu().detach().numpy()
public_fold_preds.extend(y_pred)
 public_preds += np.array(public_fold_preds)/ args["folds"]
private_fold_preds = []
for batch,(x1, x2)in enumerate(private_test_loader):
x1 = x1.to(device=args["device"], dtype=torch.long)
 x2 = x2.to(device=args["device"], dtype=torch.long)
 y_pred = model(x1, x2 ).cpu().detach().numpy()
private_fold_preds.extend(y_pred)
 private_preds += np.array(private_fold_preds)/ args["folds"]
sub_df[TARGETS] = np.expm1(sub_df[TARGETS].values)
 sub_df.to_csv("submission.csv", index=False, columns=["ForecastId"] + TARGETS)
 sub_df.head()<set_options>
preds = []
for df, p in [(public_test, public_preds),(private_test, private_preds)]:
for i, uid in enumerate(df.id):
single_pred = p[i]
single_df = pd.DataFrame(single_pred, columns=targets)
 single_df["id_seqpos"] = [f"{uid}_{x}" for x in range(single_df.shape[0])]
preds.append(single_df)
 preds = pd.concat(preds )
pd.options.display.max_rows = 500
pd.options.display.max_columns = 500
%matplotlib inline
warnings.filterwarnings("ignore")
 def rmse(yt, yp):
return np.sqrt(np.mean(( yt-yp)**2))
class CovidModel:
def __init__(self):
pass
def predict_first_day(self, date):
return None
def predict_next_day(self, yesterday_pred_df):
return None
class CovidModelAhmet(CovidModel):
def preprocess(self, df, meta_df):
df["Date"] = pd.to_datetime(df['Date'])
 df = df.merge(meta_df, on=self.loc_group, how="left")
 df["lat"] =(df["lat"] // 30 ).astype(np.float32 ).fillna(0)
 df["lon"] =(df["lon"] // 60 ).astype(np.float32 ).fillna(0)
 df["population"] = np.log1p(df["population"] ).fillna(-1)
 df["area"] = np.log1p(df["area"] ).fillna(-1)
 for col in self.loc_group:
df[col].fillna("", inplace=True)
 df['day'] = df.Date.dt.dayofyear
df['geo'] = ['_'.join(x)for x in zip(df['Country_Region'], df['Province_State'])]
return df
def get_model(self):
def nn_block(input_layer, size, dropout_rate, activation):
out_layer = KL.Dense(size, activation=None )(input_layer)
 out_layer = KL.Activation(activation )(out_layer)
 out_layer = KL.Dropout(dropout_rate )(out_layer)
 return out_layer
ts_inp = KL.Input(shape=(len(self.ts_features),))
global_inp = KL.Input(shape=(len(self.global_features),))
inp = KL.concatenate([global_inp, ts_inp])
 hidden_layer = nn_block(inp, 64, 0.0, "relu")
 gate_layer = nn_block(hidden_layer, 32, 0.0, "sigmoid")
 hidden_layer = nn_block(hidden_layer, 32, 0.0, "relu")
 hidden_layer = KL.multiply([hidden_layer, gate_layer])
 out = KL.Dense(len(self.TARGETS), activation="linear" )(hidden_layer)
 model = tf.keras.models.Model(inputs=[global_inp, ts_inp], outputs=out)
 return model
def get_input(self, df):
return [df[self.global_features], df[self.ts_features]]
def train_models(self, df, num_models=20, save=False):
def custom_loss(y_true, y_pred):
return K.sum(K.sqrt(K.sum(K.square(y_true - y_pred), axis=0, keepdims=True)))/len(self.TARGETS)
 models = []
for i in range(num_models):
model = self.get_model()
model.compile(loss=custom_loss, optimizer=Nadam(lr=1e-4))
hist = model.fit(self.get_input(df), df[self.TARGETS],
batch_size=2048, epochs=200, verbose=0, shuffle=True)
 if save:
model.save_weights("model{}.h5".format(i))
models.append(model)
 return models
def predict_one(self, df):
pred = np.zeros(( df.shape[0], 2))
for model in self.models:
pred += model.predict(self.get_input(df)) /len(self.models)
 pred = np.maximum(pred, df[self.prev_targets].values)
 pred[:, 0] = np.log1p(np.expm1(pred[:, 0])+ 0.1)
 pred[:, 1] = np.log1p(np.expm1(pred[:, 1])+ 0.01)
 return np.clip(pred, None, 15)
 def __init__(self):
df = pd.read_csv(".. /input/covid19-global-forecasting-week-4/train.csv")
 sub_df = pd.read_csv(".. /input/covid19-global-forecasting-week-4/test.csv")
 meta_df = pd.read_csv(".. /input/covid19-forecasting-metadata/region_metadata.csv")
 self.loc_group = ["Province_State", "Country_Region"]
df = self.preprocess(df, meta_df)
 sub_df = self.preprocess(sub_df, meta_df)
 df = df.merge(sub_df[["ForecastId", "Date", "geo"]], how="left", on=["Date", "geo"])
 df = df.append(sub_df[sub_df["Date"] > df["Date"].max() ], sort=False)
 df["day"] = df["day"] - df["day"].min()
self.TARGETS = ["ConfirmedCases", "Fatalities"]
self.prev_targets = ['prev_ConfirmedCases_1', 'prev_Fatalities_1']
for col in self.TARGETS:
df[col] = np.log1p(df[col])
 self.NUM_SHIFT = 7
self.global_features = ["lat", "lon", "population", "area"]
self.ts_features = []
for s in range(1, self.NUM_SHIFT+1):
for col in self.TARGETS:
df["prev_{}_{}".format(col, s)] = df.groupby(self.loc_group)[col].shift(s)
 self.ts_features.append("prev_{}_{}".format(col, s))
self.df = df[df["Date"] >= df["Date"].min() + timedelta(days=self.NUM_SHIFT)].copy()
def predict_first_day(self, day):
self.models = self.train_models(self.df[self.df["day"] < day])
 temp_df = self.df.loc[self.df["day"] == day].copy()
y_pred = self.predict_one(temp_df)
 self.y_prevs = [None]*self.NUM_SHIFT
for i in range(1, self.NUM_SHIFT):
self.y_prevs[i] = temp_df[['prev_ConfirmedCases_{}'.format(i), 'prev_Fatalities_{}'.format(i)]].values
temp_df[self.TARGETS] = y_pred
self.day = day
return temp_df[["geo", "day"] + self.TARGETS]
def predict_next_day(self, yesterday_pred_df):
self.day = self.day + 1
temp_df = self.df.loc[self.df["day"] == self.day].copy()
yesterday_pred_df = temp_df[["geo"]].merge(yesterday_pred_df[["geo"] + self.TARGETS], on="geo", how="left")
 temp_df[self.prev_targets] = yesterday_pred_df[self.TARGETS].values
for i in range(2, self.NUM_SHIFT+1):
temp_df[['prev_ConfirmedCases_{}'.format(i), 'prev_Fatalities_{}'.format(i)]] = self.y_prevs[i-1]
y_pred, self.y_prevs = self.predict_one(temp_df), [None, temp_df[self.prev_targets].values] + self.y_prevs[1:-1]
temp_df[self.TARGETS] = y_pred
return temp_df[["geo", "day"] + self.TARGETS] 
<load_from_csv>
preds[["id_seqpos"] + targets].to_csv("submission.csv", index=False )