Kaggle competition: COVID19 Global Forecasting (Week 4)
<SOS> metric: MCRMSLE Kaggle data source: covid19-global-forecasting-(week-4)<define_search_space>
warnings.filterwarnings("ignore")
 train = pd.read_csv("/kaggle/input/covid19-global-forecasting-week-4/train.csv")
 test = pd.read_csv("/kaggle/input/covid19-global-forecasting-week-4/test.csv" )
DEVICE = "TPU"
SEED = 42
FOLDS = 5
IMG_SIZES = [512]*FOLDS
INC2019 = [1]*FOLDS
INC2018 = [1,1,1,1,1]
M1 = [1]*5
M2 = [1]*5
M3 = [1]*5
M4 = [1]*5
MS = [1]*5
BATCH_SIZES = [32]*FOLDS
EPOCHS = [0]*FOLDS
EFF_NETS = [6,6,6,6,6]
WGTS = [1/FOLDS]*FOLDS
TTA = 11<choose_model_class>
train["Province_State"] = train["Province_State"].fillna('')
 test["Province_State"] = test["Province_State"].fillna('')
 train["Month"], train["Day"] = 0, 0
for i in range(len(train)) :
train["Month"][i] =(train["Date"][i] ).split("-")[1]
train["Day"][i] =(train["Date"][i] ).split("-")[2]
test["Month"], test["Day"] = 0, 0
for i in range(len(test)) :
test["Month"][i] =(test["Date"][i] ).split("-")[1]
test["Day"][i] =(test["Date"][i] ).split("-")[2]
if DEVICE == "TPU":
print("connecting to TPU...")
 try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
 except ValueError:
print("Could not connect to TPU")
 tpu = None
if tpu:
try:
print("initializing TPU...")
 tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu)
 print("TPU initialized")
 except _:
print("failed to initialize TPU")
 else:
DEVICE = "GPU"
if DEVICE != "TPU":
print("Using default strategy for CPU and single GPU")
 strategy = tf.distribute.get_strategy()
if DEVICE == "GPU":
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
 AUTO = tf.data.experimental.AUTOTUNE
REPLICAS = strategy.num_replicas_in_sync
print(f'REPLICAS: {REPLICAS}' )<define_variables>
for i in range(len(train)) :
if train["Province_State"][i] != '':
train["Country_Region"][i] = train["Province_State"][i] + "(" + str(train["Country_Region"][i])+ ")"
for i in range(len(test)) :
if test["Province_State"][i] != '':
test["Country_Region"][i] = test["Province_State"][i] + "(" + str(test["Country_Region"][i])+ ")"
train.drop(columns = "Province_State", inplace=True)
 test.drop(columns = "Province_State", inplace=True)
 train.rename(columns = {"Country_Region" : "Country/State"}, inplace=True)
 test.rename(columns = {"Country_Region" : "Country/State"}, inplace=True)
GCS_PATH = [None]*FOLDS; GCS_PATH2 = [None]*FOLDS; GCS_PATH3 = [None]*FOLDS; GCS_PATH4 = [None]*FOLDS
for i,k in enumerate(IMG_SIZES[:FOLDS]):
GCS_PATH[i] = KaggleDatasets().get_gcs_path('melanoma-%ix%i'%(k,k))
GCS_PATH2[i] = KaggleDatasets().get_gcs_path('isic2019-%ix%i'%(k,k))
GCS_PATH3[i] = KaggleDatasets().get_gcs_path('malignant-v2-%ix%i'%(k,k))
for i,k in enumerate(IMG_SIZES[:FOLDS]):
GCS_PATH4[i] = KaggleDatasets().get_gcs_path('unknowndatas')
 files_train = np.sort(np.array(tf.io.gfile.glob(GCS_PATH[0] + '/train*.tfrec')))
 files_test = np.sort(np.array(tf.io.gfile.glob(GCS_PATH[0] + '/test*.tfrec')) )<define_variables>
i = 0
for value in train["Country/State"].unique() :
if i < len(train):
j = 1
while(train["Country/State"][i] == value):
train["Day"][i] = j
j += 1; i += 1
if i == len(train):
break
i = 0
for value in test["Country/State"].unique() :
if i < len(test):
j = 72
while(test["Country/State"][i] == value):
test["Day"][i] = j
j += 1; i += 1
if i == len(test):
break
train.rename(columns = {"Day" : "No.of days"}, inplace = True)
 test.rename(columns = {"Day" : "No.of days"}, inplace = True )
ROT_ = 180.0
SHR_ = 2.0
HZOOM_ = 8.0
WZOOM_ = 8.0
HSHIFT_ = 8.0
WSHIFT_ = 8.0<normalization>
train["Country/State"].loc[train["Country/State"] == "Taiwan*"] = "Taiwan"
test["Country/State"].loc[test["Country/State"] == "Taiwan*"] = "Taiwan"
train = train.drop(columns = ["Date"])
 test = test.drop(columns = ["Date"])
 countriesorstates = train["Country/State"].unique()
print(countriesorstates )
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear / 180.
 def get_3x3_mat(lst):
return tf.reshape(tf.concat([lst],axis=0), [3,3])
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 one = tf.constant([1],dtype='float32')
 zero = tf.constant([0],dtype='float32')
 rotation_matrix = get_3x3_mat([c1, s1, zero,
-s1, c1, zero,
zero, zero, one])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix = get_3x3_mat([one, s2, zero,
zero, c2, zero,
zero, zero, one])
 zoom_matrix = get_3x3_mat([one/height_zoom, zero, zero,
zero, one/width_zoom, zero,
zero, zero, one])
 shift_matrix = get_3x3_mat([one, zero, height_shift,
zero, one, width_shift,
zero, zero, one])
 return K.dot(K.dot(rotation_matrix, shear_matrix),
K.dot(zoom_matrix, shift_matrix))
def transform(image, DIM=256):
XDIM = DIM%2
rot = ROT_ * tf.random.normal([1], dtype='float32')
 shr = SHR_ * tf.random.normal([1], dtype='float32')
 h_zoom = 1.0 + tf.random.normal([1], dtype='float32')/ HZOOM_
w_zoom = 1.0 + tf.random.normal([1], dtype='float32')/ WZOOM_
h_shift = HSHIFT_ * tf.random.normal([1], dtype='float32')
 w_shift = WSHIFT_ * tf.random.normal([1], dtype='float32')
 m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift)
 x = tf.repeat(tf.range(DIM//2, -DIM//2,-1), DIM)
 y = tf.tile(tf.range(-DIM//2, DIM//2), [DIM])
 z = tf.ones([DIM*DIM], dtype='int32')
 idx = tf.stack([x,y,z])
 idx2 = K.dot(m, tf.cast(idx, dtype='float32'))
idx2 = K.cast(idx2, dtype='int32')
 idx2 = K.clip(idx2, -DIM//2+XDIM+1, DIM//2)
 idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])
 d = tf.gather_nd(image, tf.transpose(idx3))
return tf.reshape(d,[DIM, DIM,3] )<prepare_x_and_y>
random_picks = random.choices(countriesorstates, k = 9)
 for value in random_picks:
train_temp = train.loc[train["Country/State"] == value]
test_temp = test.loc[test["Country/State"] == value]
train_temp_cc = train_temp["ConfirmedCases"].loc[train["Country/State"] == value]
train_temp_ft = train_temp["Fatalities"].loc[train["Country/State"] == value]
train_temp_X = train_temp.iloc[:, 5]
test_temp_X = test_temp.iloc[:, 3]
x = train_temp_X.to_numpy(dtype = float)
 y_1 = train_temp_cc.to_numpy(dtype = float)
 y_2= train_temp_ft.to_numpy(dtype = float)
 x = x.reshape(-1,)
 plt.plot(x, y_1, color ='red', label = value)
 plt.xlabel("No.of days")
 plt.ylabel('Confirmed cases')
 plt.legend()
plt.title("Place: " + value)
 plt.show()
plt.plot(x, y_2, color ='black', label = value)
 plt.xlabel("No.of days")
 plt.ylabel('Fatalities')
 plt.legend()
plt.title("Place: " + value)
 plt.show()
def read_labeled_tfrecord(example):
tfrec_format = {
'image' : tf.io.FixedLenFeature([], tf.string),
'image_name' : tf.io.FixedLenFeature([], tf.string),
'patient_id' : tf.io.FixedLenFeature([], tf.int64),
'sex' : tf.io.FixedLenFeature([], tf.int64),
'age_approx' : tf.io.FixedLenFeature([], tf.int64),
'anatom_site_general_challenge': tf.io.FixedLenFeature([], tf.int64),
'target' : tf.io.FixedLenFeature([], tf.int64)
 }
example = tf.io.parse_single_example(example, tfrec_format)
 return example['image'], example['target']
def read_unlabeled_tfrecord(example, return_image_name):
tfrec_format = {
'image' : tf.io.FixedLenFeature([], tf.string),
'image_name' : tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, tfrec_format)
 return example['image'], example['image_name'] if return_image_name else 0
def prepare_image(img, augment=True, dim=256):
img = tf.image.decode_jpeg(img, channels=3)
 img = tf.cast(img, tf.float32)/ 255.0
if augment:
img = transform(img,DIM=dim)
 img = tf.image.random_flip_left_right(img)
 img = tf.image.random_saturation(img, 0.7, 1.3)
 img = tf.image.random_contrast(img, 0.8, 1.2)
 img = tf.image.random_brightness(img, 0.1)
 img = tf.reshape(img, [dim,dim, 3])
 return img
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1))
for filename in filenames]
return np.sum(n )<create_dataframe>
poly_reg_cc = PolynomialFeatures(degree = 4)
 poly_reg_ft = PolynomialFeatures(degree = 4)
 reg_cc = LinearRegression()
reg_ft = LinearRegression()
sub = pd.DataFrame({'ForecastId': [], 'ConfirmedCases': [], 'Fatalities': []})
 for value in countriesorstates:
train_temp = train.loc[train["Country/State"] == value]
test_temp = test.loc[test["Country/State"] == value]
train_temp_cc = train_temp["ConfirmedCases"].loc[train["Country/State"] == value].to_frame()
train_temp_ft = train_temp["Fatalities"].loc[train["Country/State"] == value].to_frame()
train_temp_X = train_temp.iloc[:, 4:6]
test_temp_X = test_temp.iloc[:, 2:4]
sc1 = StandardScaler()
train_temp_X = sc1.fit_transform(train_temp_X)
 test_temp_X = sc1.transform(test_temp_X)
 sc_cc = StandardScaler()
sc_ft = StandardScaler()
train_temp_cc = sc_cc.fit_transform(train_temp_cc)
 train_temp_ft = sc_ft.fit_transform(train_temp_ft)
 X_poly = poly_reg_cc.fit_transform(train_temp_X)
 reg_cc.fit(X_poly, train_temp_cc)
 test_cc = sc_cc.inverse_transform(reg_cc.predict(poly_reg_cc.fit_transform(test_temp_X)))
 X_poly = poly_reg_ft.fit_transform(train_temp_X)
 reg_ft.fit(X_poly, train_temp_ft)
 test_ft = sc_ft.inverse_transform(reg_ft.predict(poly_reg_ft.fit_transform(test_temp_X)))
 a = int(train["No.of days"].loc[train["Country/State"] == "India"].max())
 b = int(a - test_temp["No.of days"].min())
 test_cc[0:b+1] = sc_cc.inverse_transform(train_temp_cc)[(a-b-1):(a)]
test_ft[0:b+1] = sc_ft.inverse_transform(train_temp_ft)[(a-b-1):(a)]
test_cc = test_cc.flatten()
test_ft = test_ft.flatten()
sub_temp = pd.DataFrame({'ForecastId': test_temp["ForecastId"].loc[test["Country/State"] == value],
'ConfirmedCases': test_cc, 'Fatalities': test_ft})
 sub = pd.concat([sub, sub_temp], axis = 0 )
def get_dataset(files, augment = False, shuffle = False, repeat = False,
labeled=True, return_image_names=True, batch_size=16, dim=256):
ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)
 ds = ds.cache()
if repeat:
ds = ds.repeat()
if shuffle:
ds = ds.shuffle(1024*8)
 opt = tf.data.Options()
opt.experimental_deterministic = False
ds = ds.with_options(opt)
 if labeled:
ds = ds.map(read_labeled_tfrecord, num_parallel_calls=AUTO)
 else:
ds = ds.map(lambda example: read_unlabeled_tfrecord(example, return_image_names),
num_parallel_calls=AUTO)
 ds = ds.map(lambda img, imgname_or_label:(prepare_image(img, augment=augment, dim=dim),
imgname_or_label),
num_parallel_calls=AUTO)
 ds = ds.batch(batch_size * REPLICAS)
 ds = ds.prefetch(AUTO)
 return ds<train_model>
sub.ForecastId = sub.ForecastId.astype('int')
 for i in range(len(sub)) :
sub["ConfirmedCases"][i] = int(round(sub["ConfirmedCases"][i]))
sub["Fatalities"][i] = int(round(sub["Fatalities"][i]))
sub.to_csv("submission.csv", index = False )