Kaggle competition: TReNDS Neuroimaging
<SOS> metric: WMAE Kaggle data source: trends-neuroimaging<import_modules>
import numpy as np
import pandas as pd
from sklearn.multioutput import MultiOutputRegressor
from sklearn.linear_model import BayesianRidge
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold
print("Currently using Tensorflow version " + tf.__version__ )<choose_model_class>
DATA_PATH = '/kaggle/input/trends-assessment-prediction/'
DEVICE = 'TPU'
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>
loading = pd.read_csv(DATA_PATH + 'loading.csv')
 loading.head()
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started' )<define_variables>
fnc = pd.read_csv(DATA_PATH + 'fnc.csv')
 fnc.head()
SEED = 34
IMAGE_SIZE = [512, 512]
BATCH_SIZE = 32 * REPLICAS
AUG_BATCH = BATCH_SIZE
FOLDS = 4
VERBOSE = 2
FIRST_FOLD_ONLY = False
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]]<categorify>
dataset = loading.merge(fnc, on='Id')
 dataset.head()
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>
y_train = pd.read_csv(DATA_PATH + 'train_scores.csv')
 print('Number of training samples: {}'.format(len(y_train)))
 y_train.head()
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_unlabeled_tfrecord(example, return_image_name):
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 if return_image_name else 0
def data_augment(img, label, flip_only = True):
if flip_only:
img = tf.image.random_flip_left_right(img)
 else:
img = tf.image.random_flip_left_right(img)
 img = tf.image.random_hue(img, 0.01)
 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)
 return img, label
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1))
for filename in filenames]
return np.sum(n )<define_variables>
y_train = y_train.fillna(y_train.mean())
 y_train.head()
AUTO = tf.data.experimental.AUTOTUNE
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')+ tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 NUM_TRAINING_IMAGES = int(count_data_items(TRAINING_FILENAMES)*(FOLDS-1.) /FOLDS)
 NUM_VALIDATION_IMAGES = int(count_data_items(TRAINING_FILENAMES)*(1./FOLDS))
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))<create_dataframe>
x_train = dataset.loc[dataset['Id'].isin(y_train['Id'])]
x_train.head()
def get_dataset(files, course_drop = False, grid_mask = False, mat_aug = False, cutmixup = False, one_hot = False,
all_aug = False, shuffle = False, repeat = False, labeled = True, return_image_names = True,
batch_size = BATCH_SIZE, dim = IMAGE_SIZE[0]):
ds = tf.data.TFRecordDataset(files, num_parallel_reads=AUTO)
 if repeat:
ds = ds.repeat()
if shuffle:
ds = ds.shuffle(2048)
 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)
 if course_drop:
ds = ds.map(data_augment, num_parallel_calls = AUTO)
 ds = ds.map(lambda img, label:(dropout(img), label), num_parallel_calls = AUTO)
 if grid_mask:
ds = ds.map(data_augment, num_parallel_calls = AUTO)
 ds = ds.map(apply_grid_mask, num_parallel_calls = AUTO)
 if mat_aug:
ds = ds.map(data_augment, num_parallel_calls = AUTO)
 ds = ds.map(transform, num_parallel_calls = AUTO)
 if all_aug:
ds = ds.map(data_augment, num_parallel_calls = AUTO)
 ds = ds.map(apply_all_aug, num_parallel_calls = AUTO)
 if cutmixup:
ds = ds.batch(AUG_BATCH)
 ds = ds.map(cut_and_mix, num_parallel_calls = AUTO)
 ds = ds.unbatch()
ds = ds.shuffle(2048)
 if one_hot:
ds = ds.map(onehot, num_parallel_calls = AUTO)
 ds = ds.batch(batch_size)
 ds = ds.prefetch(AUTO)
 return ds<define_variables>
x_test = dataset.loc[~dataset['Id'].isin(y_train['Id'])]
test_ids = x_test['Id']
print('Number of test samples: {}'.format(len(x_test)))
 x_test.head()
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>
x_train = x_train.drop('Id', axis=1 ).values
x_test = x_test.drop('Id', axis=1 ).values
y_train = y_train.drop('Id', axis=1 ).values
np.set_printoptions(threshold=15, linewidth=80)
 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()<define_variables>
model = MultiOutputRegressor(BayesianRidge(normalize=True), n_jobs=-1 )
training_dataset = get_dataset(TRAINING_FILENAMES, labeled = True, course_drop = False, all_aug = False,
grid_mask = False, mat_aug = False, cutmixup = False, shuffle = True, repeat = True)
 training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<create_dataframe>
def score(y_pred, y_true):
return sum(list(map(lambda w, s: w * s, [.3,.175,.175,.175,.175], np.sum(np.abs(y_true - y_pred), axis=0)/np.sum(y_true, axis=0))))
test_dataset = get_dataset(TEST_FILENAMES, labeled = False, course_drop = False, grid_mask = False,
mat_aug = False, all_aug = False, shuffle = True, repeat = False)
 test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
n = 7
y_test = np.zeros(( len(x_test), 5, n))
scores = np.zeros(n)
 for i,(train_indexes, valid_indexes)in enumerate(KFold(n, shuffle=True, random_state=0 ).split(x_train)) :
print('Fold {} of {}...'.format(i + 1, n))
x_train_f, x_valid = x_train[train_indexes], x_train[valid_indexes]
y_train_f, y_valid = y_train[train_indexes], y_train[valid_indexes]
model.fit(x_train_f, y_train_f)
 y_pred = model.predict(x_valid)
 scores[i] = score(y_pred, y_valid)
 print('Score = {}'.format(scores[i]))
y_test[:,:,i] = model.predict(x_test )
display_batch_of_images(next(train_batch)) 
<define_variables>
print('Average score = {}'.format(scores.mean()))
display_batch_of_images(next(test_batch)) 
<normalization>
y_test = y_test.mean(axis=2)
 print(y_test )
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear / 180.
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 one = tf.constant([1],dtype='float32')
 zero = tf.constant([0],dtype='float32')
 rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])
 zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3])
 shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])
 return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))<categorify>
outputs = ['age', 'domain1_var1', 'domain1_var2', 'domain2_var1', 'domain2_var2']
ids = ['{}_{}'.format(int(id_), output)for id_ in test_ids for output in outputs]
predicted = y_test.reshape(5 * len(y_test))
assert len(predicted)== 29385
submission = pd.DataFrame({'Id': ids, 'Predicted': predicted})
 submission.head(10 )
<prepare_x_and_y><EOS> 
submission.to_csv('submission.csv', index = False)
 !head submission.csv