Kaggle competition: TReNDS Neuroimaging
<SOS> metric: WMAE Kaggle data source: trends-neuroimaging<choose_model_class>
import numpy as np
import pandas as pd
from sklearn.svm import SVR
from sklearn.multioutput import MultiOutputRegressor, RegressorChain
from sklearn.linear_model import BayesianRidge
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import KFold
def get_model(use_model):
base_model = use_model(weights='imagenet',
include_top=False, pooling='avg',
input_shape=(*IMAGE_SIZE, 3))
x = base_model.output
predictions = Dense(104, activation='softmax' )(x)
 model = Model(inputs=base_model.input, outputs=predictions)
 model.compile(
 optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
with strategy.scope() :
model2 = get_model(NASNetLarge)
 model2.load_weights("/kaggle/input/more-data-with-nasnetlarge/my_ef_net_b7.h5" )<predict_on_test>
DATA_PATH = '/kaggle/input/trends-assessment-prediction/'
test_ds = get_test_dataset(ordered=True)
 best_alpha = 0.6
print('Вычисляем предсказания...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities1 = model1.predict(test_images_ds)
 probabilities2 = model2.predict(test_images_ds)
 probabilities = best_alpha * probabilities1 +(1 - best_alpha)* probabilities2
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>
loading = pd.read_csv(DATA_PATH + 'loading.csv')
 loading.head()
! pip install -q -U efficientnet 
<define_variables>
fnc = pd.read_csv(DATA_PATH + 'fnc.csv')
 fnc[fnc.columns[1:]] /= 600
fnc.head()
GCS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')+ '/tfrecords-jpeg-512x512'
print(GCS_PATH )<define_variables>
dataset = loading.merge(fnc, on='Id')
 dataset.head()
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
IMG_SIZE = [512, 512]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 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']<groupby>
y_train = pd.read_csv(DATA_PATH + 'train_scores.csv')
 print('Number of training samples: {}'.format(len(y_train)))
 y_train.head()
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)
 print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<categorify>
y_train = y_train.fillna(y_train.mean())
 y_train.head()
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image =(tf.cast(image, tf.float32)/ 127.5)- 1
image = tf.reshape(image, [*IMG_SIZE, 3])
 return image
def read_labeled_tfrec(example):
FORMAT = {
'image': tf.io.FixedLenFeature([], tf.string),
'class': tf.io.FixedLenFeature([], tf.int64)
 }
example = tf.io.parse_single_example(example, FORMAT)
 return decode_image(example['image']), tf.cast(example['class'], tf.int32)
 def read_unlabeled_tfrec(example):
FORMAT = {
'image': tf.io.FixedLenFeature([], tf.string),
'id': tf.io.FixedLenFeature([], tf.string)
 }
example = tf.io.parse_single_example(example, FORMAT)
 return decode_image(example['image']), example['id']<create_dataframe>
x_train = dataset.loc[dataset['Id'].isin(y_train['Id'])]
x_train.head()
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=tf.data.experimental.AUTOTUNE ).with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrec if labeled else read_unlabeled_tfrec, num_parallel_calls=tf.data.experimental.AUTOTUNE)
 return dataset<normalization>
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()
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 image = tf.image.random_flip_up_down(image)
 return image, label<create_dataframe>
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
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES ).map(data_augment, num_parallel_calls=tf.data.experimental.AUTOTUNE)
 dataset = dataset.shuffle(2048 ).batch(BATCH_SIZE ).prefetch(tf.data.experimental.AUTOTUNE)
 return dataset
def get_validation_dataset(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES, ordered=ordered ).batch(BATCH_SIZE ).cache().prefetch(tf.data.experimental.AUTOTUNE)
 return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered ).batch(BATCH_SIZE ).cache().prefetch(tf.data.experimental.AUTOTUNE)
 return dataset<train_model>
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
 x_test = scaler.transform(x_test )
ds_train = get_training_dataset()
ds_valid = get_validation_dataset()
ds_test = get_test_dataset()
print("Training:", ds_train)
 print("Validation:", ds_valid)
 print("Test:", ds_test )<choose_model_class>
model = RegressorChain(BayesianRidge(alpha_init=1e-4))
with strategy.scope() :
pretrained_model = DenseNet121(
 include_top=False,
weights='imagenet',
input_shape=[*IMG_SIZE, 3] 
)
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ] )<choose_model_class>
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))))
with strategy.scope() :
pretrained_model = efn.EfficientNetB7(include_top=False,
weights='imagenet',
input_shape=[*IMG_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ] )<choose_model_class>
n = 10
y_test = np.zeros(( len(x_test), 5, n))
scores = np.zeros(n)
 for i,(train_indexes, valid_indexes)in enumerate(KFold(n ).split(x_train)) :
print('Split {} of {}...'.format(i + 1, n))
x, x_valid = x_train[train_indexes], x_train[valid_indexes]
y, y_valid = y_train[train_indexes], y_train[valid_indexes]
model.fit(x, y)
 y_pred = model.predict(x_valid)
 scores[i] = score(y_pred, y_valid)
 print('Score = {}'.format(scores[i]))
print('Predicted : {}'.format(y_pred[0]))
print('Expected : {}
'.format(y_valid[0]))
y_test[:,:,i] = model.predict(x_test )
model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'],
)<choose_model_class>
print('Average score = {}'.format(scores.mean()))
def exponential_lr(epoch,
start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.00005,
rampup_epochs = 10, sustain_epochs = 0,
exp_decay = 0.8):
if epoch < rampup_epochs:
lr =(( max_lr - start_lr)/ rampup_epochs * epoch + start_lr)
 elif epoch < rampup_epochs + sustain_epochs:
lr = max_lr
else:
lr =(( max_lr - min_lr)*
exp_decay**(epoch - rampup_epochs - sustain_epochs)+ min_lr)
 return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True )<train_model>
y_test = y_test.mean(axis=2)
 print(y_test )
EPOCHS = 20
history = model.fit(
 ds_train,
validation_data=ds_valid,
epochs=EPOCHS,
callbacks=[lr_callback]
)<predict_on_test>
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 )
<compute_train_metric><EOS> 
submission.to_csv('submission.csv', index = False)
 !head submission.csv