Kaggle competition: TReNDS Neuroimaging
<SOS> metric: WMAE Kaggle data source: trends-neuroimaging<predict_on_test>
import numpy as np
import pandas as pd
from pathlib import Path
from matplotlib import pyplot as plt
import seaborn as sns
from sklearn.model_selection import KFold, StratifiedKFold
from fastai.tabular import *
from fastai import *
import os, shutil
import sys
test_ds = get_test_dataset(ordered=True)
 print('Вычисляем предсказания...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 print('Создание файла submission.csv...')
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='' )<import_modules>
logging.getLogger().setLevel(logging.NOTSET)
import random, re, math, os
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import tensorflow_addons as tfa
from kaggle_datasets import KaggleDatasets
from tensorflow.keras.mixed_precision import experimental as mixed_precision
from tensorflow.keras.applications import DenseNet201
import tensorflow.keras.backend as K
from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix
import datetime
import tqdm
import json
from collections import Counter
import gc<define_variables>
kaggle_path = Path('.')
 kaggle_input_path = Path('/kaggle/input/trends-assessment-prediction')
 cluster_input_path = Path('/kaggle/input/trends-cluster-sfnc-groups')
 av_input_path = Path('/kaggle/input/trends-av-probs-of-test-and-s2')
 img_53000_path = Path('/kaggle/input/fork-of-trends-image-features-53-100')
IMAGE_SIZE = [512, 512]
EPOCHS = 16
SEED = 100
BATCH_SIZE = 16 * strategy.num_replicas_in_sync<define_variables>
INCLUDE_FNC_DATA = True
INCLUDE_FNC_CLUSTERS = False
INCLUDE_FNC_DIST_CCENTER = False
INCLUDE_FNC_CLUSTERS_2 = True
INCLUDE_FNC_DIST_CCENTER_2 = True
INCLUDE_IMG_53000 = False
INCLUDE_AV_DATA = False
IMPUTATION_STRAT = 'IGNORE_ON_TRAIN'
LOSS_WEIGHTS = [0.3, 0.175, 0.175, 0.175, 0.175]
BS = 128
DEP_VAR = ['age','domain1_var1','domain1_var2', 'domain2_var1', 'domain2_var2']
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec' )<set_options>
l_data = pd.read_csv(kaggle_input_path/'loading.csv' ).drop('IC_20',axis=1)
 if INCLUDE_FNC_DATA:
f_data = pd.read_csv(kaggle_input_path/'fnc.csv')
 l_data = l_data.merge(f_data, on='Id', how = 'inner')
 if INCLUDE_FNC_CLUSTERS:
c_data = pd.read_csv(cluster_input_path/'sfnc_group_clusters.csv')
 l_data = l_data.merge(c_data, on='Id', how = 'inner')
 if INCLUDE_FNC_DIST_CCENTER:
cc_data = pd.read_csv(cluster_input_path/'sfnc_dist_to_cluster_center.csv')
 l_data = l_data.merge(cc_data, on='Id', how = 'inner')
 if INCLUDE_FNC_CLUSTERS_2:
c2_data = pd.read_csv(cluster_input_path/'sfnc_group_clusters_2c.csv')
 temp_col = []
for c in c2_data.columns:
if c != 'Id':
temp_col += [c+'_2']
else:
temp_col += [c]
c2_data.columns = temp_col
l_data = l_data.merge(c2_data, on='Id', how = 'inner')
 if INCLUDE_FNC_DIST_CCENTER_2:
cc2_data = pd.read_csv(cluster_input_path/'sfnc_dist_to_cluster_center_2c.csv')
 temp_col = []
for c in cc2_data.columns:
if c != 'Id':
temp_col += [c+'_2']
else:
temp_col += [c]
cc2_data.columns = temp_col
l_data = l_data.merge(cc2_data, on='Id', how = 'inner')
 if INCLUDE_IMG_53000:
i_data = pd.read_csv(img_53000_path/'train_features.csv')
 i_data = i_data.append(pd.read_csv(img_53000_path/'test_features.csv'))
l_data = l_data.merge(i_data, on='Id', how = 'inner')
 if INCLUDE_AV_DATA:
av_data = pd.read_csv(av_input_path/'test_s2_probs.csv')
 l_data = l_data.merge(av_data, on='Id', how = 'inner')
 y_data = pd.read_csv(kaggle_input_path/'train_scores.csv')
 idx_site2 = pd.read_csv(kaggle_input_path/'reveal_ID_site2.csv')
MIXED_PRECISION = False
XLA_ACCELERATE = False
if MIXED_PRECISION:
if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')
 else: policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')
 mixed_precision.set_policy(policy)
 print('Mixed precision enabled')
 if XLA_ACCELERATE:
tf.config.optimizer.set_jit(True)
 print('Accelerated Linear Algebra enabled' )<define_variables>
if IMPUTATION_STRAT == 'IGNORE_ON_TRAIN':
y_data = y_data.fillna(0)
 else:
y_data = y_data.fillna(y_data.mean())
 y_data
CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']<categorify>
train_df = l_data.merge(y_data, on='Id', how='inner' ).sort_values(by='Id' ).reset_index(drop = True)
 idx_train = train_df.pop('Id')
 train_df
def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.dtype == object:
numpy_labels = [None for _ in enumerate(numpy_images)]
return numpy_images, numpy_labels
def title_from_label_and_target_(label, correct_label):
if correct_label is None:
return CLASSES[label], True
correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], 'OK' if correct else 'NO', u"\u2192" if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower(image, title, subplot, red = False, titlesize = 16):
plt.subplot(*subplot)
 plt.axis('off')
 plt.imshow(image)
 if len(title)> 0:
plt.title(title, fontsize = int(titlesize)if not red else int(titlesize / 1.2), color = 'red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))
return(subplot[0], subplot[1], subplot[2] + 1)
 def display_batch_of_images(databatch, predictions = None):
images, labels = batch_to_numpy_images_and_labels(databatch)
 if labels is None:
labels = [None for _ in enumerate(images)]
rows = int(math.sqrt(len(images)))
 cols = len(images)// rows
FIGSIZE = 13.0
SPACING = 0.1
subplot =(rows,cols,1)
 if rows < cols:
plt.figure(figsize =(FIGSIZE, FIGSIZE / cols*rows))
else:
plt.figure(figsize =(FIGSIZE / rows * cols,FIGSIZE))
for i,(image, label)in enumerate(zip(images[:rows*cols], labels[:rows*cols])) :
title = '' if label is None else CLASSES[label]
correct = True
if predictions is not None:
title, correct = title_from_label_and_target_(predictions[i], label)
 dynamic_titlesize = FIGSIZE * SPACING / max(rows,cols)* 40 + 3
subplot = display_one_flower(image, title, subplot, not correct, titlesize = dynamic_titlesize)
 plt.tight_layout()
if label is None and predictions is None:
plt.subplots_adjust(wspace = 0, hspace = 0)
 else:
plt.subplots_adjust(wspace = SPACING, hspace = SPACING)
 plt.show()
def dataset_to_numpy_util(dataset, N):
dataset = dataset.unbatch().batch(N)
 for images, labels in dataset:
numpy_images = images.numpy()
numpy_labels = labels.numpy()
break;
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
label = np.argmax(label, axis = -1)
 correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], str(correct), ', should be ' if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower_eval(image, title, subplot, red = False):
plt.subplot(subplot)
 plt.axis('off')
 plt.imshow(image)
 plt.title(title, fontsize = 14, color = 'red' if red else 'black')
 return subplot + 1
def display_9_images_with_predictions(images, predictions, labels):
subplot = 331
plt.figure(figsize =(13,13))
for i, image in enumerate(images):
title, correct = title_from_label_and_target(predictions[i], labels[i])
 subplot = display_one_flower_eval(image, title, subplot, not correct)
 if i >= 8:
break;
plt.tight_layout()
plt.subplots_adjust(wspace = 0.1, hspace = 0.1)
 plt.show()<categorify>
test = l_data.merge(y_data, on='Id', how='outer', indicator = True)
 test = test[test['_merge'] == 'left_only'].drop(['age',
'domain1_var1',
'domain1_var2',
'domain2_var1',
'domain2_var2',
'_merge'], axis = 1 ).sort_values(by='Id' ).reset_index(drop = True)
 idx_test = test.pop('Id')
 test
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels = 3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image<categorify>
for d in DEP_VAR:
y_data['bin_'+d] = pd.qcut(y_data[d].rank(method='first'), q=4, labels=False)
 y_data['bin_all'] =(y_data['bin_age']+
y_data['bin_domain1_var1']*10+
y_data['bin_domain1_var2']*100+
y_data['bin_domain2_var1']*1000+
y_data['bin_domain2_var2']*10000)
 y_data['bin_age_10'] = pd.qcut(y_data['age'].rank(method='first'), q=10, labels=False)
 y_data['bin_age_7'] = pd.qcut(y_data['age'].rank(method='first'), q=7, labels=False)
 if INCLUDE_AV_DATA:
y_data = y_data.merge(av_data[['Id','is_test_prob']])
 y_data['bin_test_7'] = pd.qcut(y_data['is_test_prob'].rank(method='first'), q=7, labels=False)
 y_data
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_labeled_id_tfrecord(example):
LABELED_ID_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, LABELED_ID_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 idnum = example['id']
return image, label, idnum<prepare_x_and_y>
def norm_absolute_error(preds, targs):
"Normalized absolute error between `pred` and `targ`."
sg=targs.sign()
y=targs*sg
pred, targ = flatten_check(preds*sg, y)
 return torch.abs(targ - pred ).sum() / targ.sum()
def weighted_nae(preds, targs, details = False):
if IMPUTATION_STRAT == 'IGNORE_ON_TRAIN':
sg = targs.float().sign()
x0 = preds[:,0].float() *sg[:,0]
x1 = preds[:,1].float() *sg[:,1]
x2 = preds[:,2].float() *sg[:,2]
x3 = preds[:,3].float() *sg[:,3]
x4 = preds[:,4].float() *sg[:,4]
else:
sg = 1
x0 = preds[:,0].float()
x1 = preds[:,1].float()
x2 = preds[:,2].float()
x3 = preds[:,3].float()
x4 = preds[:,4].float()
y = targs.float() *sg
return norm_absolute_error(x0,y[:,0]), \
norm_absolute_error(x1,y[:,1]), \
norm_absolute_error(x2,y[:,2]), \
norm_absolute_error(x3,y[:,3]), \
norm_absolute_error(x4,y[:,4]), \
0.3 * norm_absolute_error(x0,y[:,0])+ \
0.175 * norm_absolute_error(x1,y[:,1])+ \
0.175 * norm_absolute_error(x2,y[:,2])+ \
0.175 * norm_absolute_error(x3,y[:,3])+ \
0.175 * norm_absolute_error(x4,y[:,4])
 def plot_diff(y, y_truth):
y_df = pd.DataFrame(y.numpy())
 y_df.columns = DEP_VAR
y_df = y_df.melt()
y_df['Id'] = y_df.index
y_truth_df = pd.DataFrame(y_truth.numpy())
 y_truth_df.columns = DEP_VAR
y_truth_df = y_truth_df.melt()
y_truth_df['Id'] = y_truth_df.index
plot_df = y_truth_df.merge(y_df, on=['variable', 'Id'], how='inner' ).drop('Id', axis = 1)
 plot_df.columns = ['Category', 'Target', 'Prediction']
g = sns.relplot(x="Target", y="Prediction",
col="Category", hue="Category", style="Category",
kind="scatter", data=plot_df)
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum<create_dataframe>
class Metric_idx(Callback):
def __init__(self, idx):
super().__init__()
self.idx = idx
def on_epoch_begin(self, **kwargs):
self.targs, self.preds = Tensor([]), Tensor([])
 def on_batch_end(self, last_output:Tensor, last_target:Tensor, **kwargs):
last_output = last_output[self.idx]
last_target = last_target[self.idx]
self.preds = torch.cat(( self.preds, last_output.float().cpu()))
self.targs = torch.cat(( self.targs, last_target.float().cpu()))
def _norm_absolute_error(self):
return norm_absolute_error(self.preds, self.targs)
 def on_epoch_end(self, last_metrics, **kwargs):
return add_metrics(last_metrics, self._norm_absolute_error())
 Metric_age = partial(Metric_idx,0)
 Metric_domain1_var1 = partial(Metric_idx,1)
 Metric_domain1_var2 = partial(Metric_idx,2)
 Metric_domain2_var1 = partial(Metric_idx,3)
 Metric_domain2_var2 = partial(Metric_idx,4)
 class Metric_total(Callback):
def __init__(self):
super().__init__()
self.age = Metric_idx(0)
 self.domain1_var1 = Metric_idx(1)
 self.domain1_var2 = Metric_idx(2)
 self.domain2_var1 = Metric_idx(3)
 self.domain2_var2 = Metric_idx(4)
 def on_epoch_begin(self, **kwargs):
self.age.on_epoch_begin(**kwargs)
 self.domain1_var1.on_epoch_begin(**kwargs)
 self.domain1_var2.on_epoch_begin(**kwargs)
 self.domain2_var1.on_epoch_begin(**kwargs)
 self.domain2_var2.on_epoch_begin(**kwargs)
 def on_batch_end(self, last_output:Tensor, last_target:Tensor, **kwargs):
self.age.on_batch_end(last_output, last_target, **kwargs)
 self.domain1_var1.on_batch_end(last_output, last_target, **kwargs)
 self.domain1_var2.on_batch_end(last_output, last_target, **kwargs)
 self.domain2_var1.on_batch_end(last_output, last_target, **kwargs)
 self.domain2_var2.on_batch_end(last_output, last_target, **kwargs)
 def on_epoch_end(self, last_metrics, **kwargs):
return add_metrics(last_metrics,
0.3 * self.age._norm_absolute_error() +
0.175*self.domain1_var1._norm_absolute_error() +
0.175*self.domain1_var2._norm_absolute_error() +
0.175*self.domain2_var1._norm_absolute_error() +
0.175*self.domain2_var2._norm_absolute_error()
)
def load_dataset(filenames, labeled = True, ordered = False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_id_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset<create_dataframe>
class Loss_combine(nn.Module):
def __init__(self, loss_weights = [0.4,0.15,0.15,0.15,0.15], loss_base = 'MSE'):
super().__init__()
self.loss_base = loss_base
self.loss_weights = loss_weights
self.fw = Tensor(LOSS_WEIGHTS ).cuda()
def forward(self, input, target,reduction='mean'):
x0,x1,x2,x3,x4 = input.T
if IMPUTATION_STRAT == 'IGNORE_ON_TRAIN':
sg = target.float().sign()
x0,x1,x2,x3,x4 = x0.float() *sg[:,0],x1.float() *sg[:,1],x2.float() *sg[:,2],x3.float() *sg[:,3],x4.float() *sg[:,4]
else:
sg = 1
x0,x1,x2,x3,x4 = x0.float() ,x1.float() ,x2.float() ,x3.float() ,x4.float()
y = target.float() *sg
loss1 = 0
loss2 = 0
if self.loss_base in('MSE','MIX'):
loss_func = F.mse_loss
loss1 =(self.fw*(F.mse_loss(input*sg,y,reduction='none' ).sum(dim=0)) /(( y**2.5 ).sum(dim=0)))*3
loss1 = loss1.sum()
if self.loss_base in('L1','MIX'):
loss_func = F.l1_loss
reduction = 'sum'
loss2 = self.fw[0]*loss_func(x0,y[:,0],reduction=reduction)/sum(y[:,0])+ \
self.fw[1]*loss_func(x1,y[:,1],reduction=reduction)/sum(y[:,1])+ \
self.fw[2]*loss_func(x2,y[:,2],reduction=reduction)/sum(y[:,2])+ \
self.fw[3]*loss_func(x3,y[:,3],reduction=reduction)/sum(y[:,3])+ \
self.fw[4]*loss_func(x4,y[:,4],reduction=reduction)/sum(y[:,4])
 loss2 = loss2/4
return loss1 + loss2
def get_training_dataset() :
train = load_dataset(TRAINING_FILENAMES, labeled = True)
 train = train.map(lambda image, label, idnum: [image, label])
 train = train.repeat()
train = train.shuffle(2048)
 train = train.batch(BATCH_SIZE)
 train = train.prefetch(AUTO)
 return train
def get_training_dataset_preview(ordered = True):
train = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = ordered)
 train = train.batch(BATCH_SIZE)
 train = train.cache()
train = train.prefetch(AUTO)
 return train<create_dataframe>
class TailBlock(nn.Module):
def __init__(self, bs):
super(TailBlock, self ).__init__()
self.bs = bs
self.lstm = nn.GRU(input_size = 53, hidden_size = 20, num_layers = 64, bidirectional=False, dropout = 0.3)
 self.linear = nn.Linear(40, 8)
 self.hidden_cell = torch.zeros(128,bs, 20 ).cuda()
def forward(self,x_cont):
print(x_cont.size())
 x_non_lstm_feat = x_cont[:,:-5300]
x53 = x_cont[:,-5300:].view(-1, 100, 53)
 print('x53',x53.shape)
 lstm_out, self.hidden_cell = self.lstm(x53.view(100, self.bs, -1), self.hidden_cell)
 print('lout',lstm_out.shape)
 x_lstm_out = self.linear(torch.cat([x_non_lstm_feat.view(1,-1), x_lstm_out.view(1,-1)], dim=1))
return x_lstm_out
def get_validation_dataset(ordered = False):
validation = load_dataset(VALIDATION_FILENAMES, labeled = True, ordered = ordered)
 validation = validation.map(lambda image, label, idnum: [image, label])
 validation = validation.batch(BATCH_SIZE)
 validation = validation.cache()
validation = validation.prefetch(AUTO)
 return validation<create_dataframe>
class NeckBlock(nn.Module):
def __init__(self, nf, ps=0.3):
super(NeckBlock,self ).__init__()
self.sa = SelfAttention(256)
 self.bn1 = nn.BatchNorm1d(nf)
 self.d1 = nn.Dropout(ps)
 self.l1 = nn.Linear(nf, 1)
 self.act1 = nn.LeakyReLU(0.1, inplace=True)
 self.bn2 = nn.BatchNorm1d(nf)
 self.d2 = nn.Dropout(ps)
 self.l2 = nn.Linear(nf, 4)
 self.act2 = nn.LeakyReLU(0.1, inplace=True)
 def forward(self, x):
ident = x
x0 = self.sa(x)
 x1 = self.bn1(x0)
 x1 = self.d1(x1)
 x1 = self.l1(x1)
 x1 = self.act1(x1+ident)
 x2 = self.bn2(x0)
 x2 = self.d2(x2)
 x2 = self.l2(x2)
 x2 = self.act2(x2+ident)
 return x1, xn
def get_test_dataset(ordered = False):
test = load_dataset(TEST_FILENAMES, labeled = False, ordered = ordered)
 test = test.batch(BATCH_SIZE)
 test = test.prefetch(AUTO)
 return test<groupby>
def prep_data(bs=128, valid_idx=range(200, 400), train_df = train_df):
procs = [FillMissing, Categorify, Normalize]
cat_names = []
if INCLUDE_FNC_CLUSTERS:
cat_names = cat_names + list(set(c_data.columns)-set(['Id']))
if INCLUDE_FNC_CLUSTERS_2:
cat_names = cat_names + list(set(c2_data.columns)-set(['Id']))
cont_names = list(set(train_df.columns)- set(cat_names)- set(['age','domain1_var1','domain1_var2', 'domain2_var1', 'domain2_var2'])-set(DEP_VAR))
tlist =(TabularList.from_df(train_df,
path=kaggle_path,
cat_names=cat_names,
cont_names=cont_names,
procs=procs))
if valid_idx == None:
tlist = tlist.split_none()
else:
tlist = tlist.split_by_idx(valid_idx)
 data =(tlist.label_from_df(cols=DEP_VAR)
.add_test(TabularList.from_df(test,
cat_names=cat_names,
cont_names=cont_names,
procs = procs)) 
.databunch(path = kaggle_path, bs = bs))
return data
def prep_learn(data, loss_base = 'MSE'):
learn = tabular_learner(data,
layers = [8],
ps = 0.3,
loss_func = Loss_combine(loss_weights = LOSS_WEIGHTS, loss_base= loss_base),
metrics=[Metric_age() ,
Metric_domain1_var1() ,
Metric_domain1_var2() ,
Metric_domain2_var1() ,
Metric_domain2_var2() ,
Metric_total() ],
y_range=(Tensor([12,12,0,0,0] ).cuda() ,Tensor([90,90,100,100,100] ).cuda())
)
 learn.clip_grad = 1.0
learn.model.layers[4].add_module('NeckBlock', NeckBlock(5, 0.4))
return learn
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
 NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<define_variables>
bs=128
valid_idx=range(200, 400)
 data = prep_data(bs, valid_idx, train_df=train_df)
 learn = prep_learn(data )
train_dataset_aug = get_training_dataset()
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))<define_variables>
lr = 2e-2
reduceLR = callbacks.ReduceLROnPlateauCallback(learn=learn, monitor = 'valid_loss', mode = 'auto', patience = 2, factor = 0.2, min_delta = 0)
 learn.fit_one_cycle(10, lr, callbacks=[reduceLR] )
validation_dataset_aug = get_validation_dataset()
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))<define_variables>
print(f'Weighted normalized absolute error(Train): {weighted_nae(yt,yt_truth)[-1]}')
 for i, dv in enumerate(DEP_VAR):
print(f'NAE {dv}(Train): {weighted_nae(yt,yt_truth)[i]}')
 plot_diff(yt, yt_truth )
test_dataset_aug = get_test_dataset()
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))<choose_model_class>
LOSS_WEIGHTS = [.3,.175,.175,.175,.175]
kf_split = 7
kf = StratifiedKFold(n_splits=kf_split, shuffle=True, random_state=2020)
 y_oof = None
y_truth_oof = None
y_oof_g = None
y_truth_oof_g = None
val_ids = []
for i,(train_id, val_id)in enumerate(kf.split(train_df,y_data['bin_age_7'].values)) :
print('Fold
data = prep_data(BS, val_id.tolist())
 learn = prep_learn(data, loss_base = 'MSE')
 lr = 4e-2
reduceLR = callbacks.ReduceLROnPlateauCallback(learn=learn, monitor = 'valid_loss', mode = 'auto', patience = 2, factor = 0.2, min_delta = 0)
 learn.fit_one_cycle(10, lr, callbacks=[reduceLR])
 val_ids = val_ids+val_id.tolist()
yv, yv_truth= learn.get_preds(ds_type=DatasetType.Valid)
 if y_oof == None:
y_oof = yv
y_truth_oof = yv_truth
else:
y_oof=torch.cat(( y_oof,yv),0)
 y_truth_oof=torch.cat(( y_truth_oof,yv_truth),0)
 print(f'
print(f'Weighted normalized absolute error(Valid): {weighted_nae(y_oof,y_truth_oof)[-1]}')
 for i, dv in enumerate(DEP_VAR):
print(f'NAE {dv}(Valid): {weighted_nae(y_oof,y_truth_oof)[i]}')
 plot_diff(y_oof, y_truth_oof )
def lrfn(epoch):
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY **(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 rng = [i for i in range(25 if EPOCHS<25 else EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<choose_model_class>
offset=torch.tensor([.3,.3,.8,.8,.8])
 print(f'
print(f'Weighted normalized absolute error(Valid): {weighted_nae(y_oof+offset,y_truth_oof)[-1]}')
 for i, dv in enumerate(DEP_VAR):
print(f'NAE {dv}(Valid): {weighted_nae(y_oof+offset,y_truth_oof)[i]}')
 plot_diff(y_oof+offset, y_truth_oof )
with strategy.scope() :
rnet = DenseNet201(
 input_shape =(512, 512, 3),
weights = 'imagenet',
include_top = False 
)
 rnet.trainable = True
model = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics = ['sparse_categorical_accuracy'] 
)
 model.summary()
model.save('ML_finalproject.h5' )<create_dataframe>
def gather_preds(learn, ignore_vars=[], offset = torch.ones(5)) :
preds = learn.get_preds(ds_type=DatasetType.Test)[0]
preds = preds + offset
submission=None
rec_flatt = pd.DataFrame(idx_test)
 rec_flatt.columns=['Id']
for t, tcol in enumerate(DEP_VAR):
if tcol not in ignore_vars:
rec = pd.DataFrame(idx_test)
 rec['Id'] = rec['Id'].astype(str)+'_'+tcol
rec['Predicted'] = preds[:,t]
if isinstance(submission, pd.DataFrame):
submission = submission.append(rec)
 else:
submission = rec
rec_flatt[tcol] = preds[:,t]
return submission, rec_flatt
def make_submission(gathered_preds, filename = ''):
submission = gathered_preds.groupby('Id' ).mean().sort_values('Id' ).reset_index(drop=False)
 print('Shape of submission:', submission.shape)
 display(submission.head(10))
submission.to_csv(filename, index=False )
gc.enable()
def get_training_dataset_raw() :
dataset = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = False)
 return dataset
raw_training_dataset = get_training_dataset_raw()
label_counter = Counter()
for images, labels, id in raw_training_dataset:
label_counter.update([labels.numpy() ])
 del raw_training_dataset
TARGET_NUM_PER_CLASS = 122
def get_weight_for_class(class_id):
counting = label_counter[class_id]
weight = TARGET_NUM_PER_CLASS / counting
return weight
weight_per_class = {class_id: get_weight_for_class(class_id)for class_id in range(104)}<train_model>
data = prep_data(BS, valid_idx = None)
 learn = prep_learn(data)
 lr = 4e-2
learn.fit_one_cycle(10, lr )
history = model.fit(
 get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = EPOCHS,
callbacks = [lr_callback],
validation_data = get_validation_dataset() ,
class_weight = weight_per_class
)<predict_on_test>
gath_pred_no_split, _ = gather_preds(learn)
 make_submission(gath_pred_no_split, filename = 'submission_wo_split.csv' )
cmdataset = get_validation_dataset(ordered = True)
 images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_probabilities = model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis = -1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions )<compute_train_metric>
LOSS_WEIGHTS = [.3,.175,.175,.175,.175]
kf_split = 10
kf = StratifiedKFold(n_splits=kf_split, shuffle=True, random_state=2020)
 y_oof = None
y_truth_oof = None
val_ids = []
gathered_preds = None
gathered_preds_flat = None
for i,(train_id, val_id)in enumerate(kf.split(train_df,y_data['bin_age_7'].values)) :
print('Fold
data = prep_data(BS, val_id.tolist())
 learn = prep_learn(data, loss_base = 'MIX')
 lr = 4e-2
reduceLR = callbacks.ReduceLROnPlateauCallback(learn=learn, monitor = 'valid_loss', mode = 'auto', patience = 2, factor = 0.2, min_delta = 0)
 learn.fit_one_cycle(10, lr, callbacks=[reduceLR])
 val_ids = val_ids+val_id.tolist()
yv, yv_truth= learn.get_preds(ds_type=DatasetType.Valid)
 if y_oof == None:
y_oof = yv
y_truth_oof = yv_truth
else:
y_oof=torch.cat(( y_oof,yv),0)
 y_truth_oof=torch.cat(( y_truth_oof,yv_truth),0)
 g_preds, g_preds_flat = gather_preds(learn)
 if isinstance(gathered_preds, pd.DataFrame):
gathered_preds = gathered_preds.append(g_preds)
 gathered_preds_flat = gathered_preds_flat.append(g_preds_flat)
 else:
gathered_preds = g_preds
gathered_preds_flat = g_preds_flat
y_oof_1 = y_oof
y_truth_oof_1 = y_oof
val_ids_1 = val_ids
print(f'K-Fold:',kf_split)
 print(f'Weighted normalized absolute error(Valid): {weighted_nae(y_oof,y_truth_oof)[-1]}')
 for i, dv in enumerate(DEP_VAR):
print(f'NAE {dv}(Valid): {weighted_nae(y_oof,y_truth_oof)[i]}')
 plot_diff(y_oof, y_truth_oof)
 gathered_preds_1 = gathered_preds
gathered_preds_flat_1 = gathered_preds_flat
make_submission(gathered_preds_1.sort_values('Id' ).reset_index(drop=True), filename = 'submission_10fold_MIX.csv')
 make_submission(gathered_preds_flat_1.sort_values('Id' ).reset_index(drop=True), filename = 'mix_test_preds_out.csv' )
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels = range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_predictions, labels = range(len(CLASSES)) , average = 'macro')
 precision = precision_score(cm_correct_labels, cm_predictions, labels = range(len(CLASSES)) , average = 'macro')
 recall = recall_score(cm_correct_labels, cm_predictions, labels = range(len(CLASSES)) , average = 'macro')
 cmat =(cmat.T / cmat.sum(axis = 1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<save_to_csv>
train_preds_out = pd.DataFrame(y_oof_1.numpy() , index=val_ids_1 ).sort_index()
train_preds_out.columns = DEP_VAR
train_preds_out['Id'] = idx_train
train_preds_out.to_csv('mix_train_preds_out.csv', index = False)
 train_preds_out1 = train_preds_out.copy()
train_preds_out1
test_ds = get_test_dataset(ordered = True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis = -1)
 print(predictions)
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 test = pd.DataFrame({"id": test_ids, "label": predictions})
 print(test.head)
 test.to_csv("submission.csv",index = False )<install_modules>
LOSS_WEIGHTS = [.3,.175,.175,.175,.175]
offset=torch.tensor([.3,.3,.8,.8,.8])
 kf_split = 10
kf = StratifiedKFold(n_splits=kf_split, shuffle=True, random_state=2020)
 y_oof = None
y_truth_oof = None
val_ids = []
gathered_preds = None
gathered_preds_flat = None
for i,(train_id, val_id)in enumerate(kf.split(train_df,y_data['bin_age_7'].values)) :
print('Fold
data = prep_data(BS, val_id.tolist())
 learn = prep_learn(data, loss_base = 'MSE')
 lr = 4e-2
reduceLR = callbacks.ReduceLROnPlateauCallback(learn=learn, monitor = 'valid_loss', mode = 'auto', patience = 2, factor = 0.2, min_delta = 0)
 learn.fit_one_cycle(10, lr, callbacks=[reduceLR])
 val_ids = val_ids+val_id.tolist()
yv, yv_truth= learn.get_preds(ds_type=DatasetType.Valid)
 if y_oof == None:
y_oof = yv
y_truth_oof = yv_truth
else:
y_oof=torch.cat(( y_oof,yv),0)
 y_truth_oof=torch.cat(( y_truth_oof,yv_truth),0)
 g_preds, g_preds_flat = gather_preds(learn, offset = offset)
 if isinstance(gathered_preds, pd.DataFrame):
gathered_preds_flat = gathered_preds_flat.append(g_preds_flat)
 gathered_preds = gathered_preds.append(g_preds)
 else:
gathered_preds = g_preds
gathered_preds_flat = g_preds_flat
y_oof_2 = y_oof
y_truth_oof_2 = y_oof
val_ids_2 = val_ids
print(f'K-Fold with offset:',kf_split)
 print(f'Weighted normalized absolute error(Valid): {weighted_nae(y_oof,y_truth_oof)[-1]}')
 for i, dv in enumerate(DEP_VAR):
print(f'NAE {dv}(Valid): {weighted_nae(y_oof,y_truth_oof)[i]}')
 plot_diff(y_oof, y_truth_oof)
 gathered_preds_2 = gathered_preds
gathered_preds_flat_2 = gathered_preds_flat
make_submission(gathered_preds_2.sort_values('Id' ).reset_index(drop=True), filename = 'submission_10fold_MSE_offset.csv')
 make_submission(gathered_preds_flat_2.sort_values('Id' ).reset_index(drop=True), filename = 'mse_test_preds_out.csv' )
<set_options><EOS> 
train_preds_out = pd.DataFrame(y_oof_2.numpy() , index=val_ids_2 ).sort_index()
train_preds_out.columns = DEP_VAR
train_preds_out['Id'] = idx_train
train_preds_out.to_csv('mse_train_preds_out.csv', index = False)
 train_preds_out2 = train_preds_out.copy()
train_preds_out2