Kaggle competition: SIIM-ISIC Melanoma Classification
<SOS> metric: MCAUC Kaggle data source: siim-isic-melanoma-classification<create_dataframe>
DEVICE = "TPU"
BASEPATH = ".. /input/siim-isic-melanoma-classification"
rdf_test = pd.DataFrame(pred_info_test ).apply(return_result, axis=1)
 rdf_test<feature_engineering>
!pip install -q efficientnet
pred_df["label"]=rdf_test
pred_df<save_to_csv>
random.seed(a=128)
pred_df.to_csv('submission.csv', index=False )<load_from_csv>
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')))
 print("REPLICAS: ", strategy.num_replicas_in_sync)
 AUTO = tf.data.experimental.AUTOTUNE
path = '/kaggle/input/titanic/'
traindf = pd.read_csv(path + 'train.csv')
 testdf = pd.read_csv(path + 'test.csv')
 submission = pd.read_csv(path + 'gender_submission.csv' )<import_modules>
EPOCHS = 6
BATCH_SIZE = 8 * strategy.num_replicas_in_sync
IMAGE_SIZE = [384, 384]
import catboost
from catboost import CatBoostClassifier, Pool
from sklearn.model_selection import train_test_split<feature_engineering>
df_train = pd.read_csv(os.path.join(BASEPATH, 'train.csv'))
df_test = pd.read_csv(os.path.join(BASEPATH, 'test.csv'))
sub = pd.read_csv(os.path.join(BASEPATH, 'sample_submission.csv'))
GCS_PATH = KaggleDatasets().get_gcs_path('melanoma-384x384')
 TRAINING_FILENAMES = np.array(tf.io.gfile.glob(GCS_PATH + '/train*.tfrec'))
TEST_FILENAMES = np.array(tf.io.gfile.glob(GCS_PATH + '/test*.tfrec'))
CLASSES = [0,1]
testdf['Title'] = testdf.Name.apply(lambda name: name.split(',')[1].split('.')[0].strip())
 traindf['Title'] = traindf.Name.apply(lambda name: name.split(',')[1].split('.')[0].strip())
<count_values>
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
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"target": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['target'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"image_name": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['image_name']
return image, idnum
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_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 image = tf.image.random_flip_up_down(image)
 image = tf.image.random_hue(image, 0.01)
 image = tf.image.random_saturation(image, 0.7, 1.3)
 image = tf.image.random_contrast(image, 0.8, 1.2)
 image = tf.image.random_brightness(image, 0.1)
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
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_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_TEST_IMAGES))
testdf['Title'].value_counts()<drop_column>
def lrfn(epoch):
LR_START = 0.000005
LR_MAX = 0.000020 * strategy.num_replicas_in_sync
LR_MIN = 0.000001
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
traindf = traindf[['PassengerId', 'Title', 'Pclass','Sex', 'Fare', 'Age', 'Survived']]
testdf = testdf[['PassengerId', 'Title', 'Pclass','Sex', 'Age', 'Fare']]<prepare_x_and_y>
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, BatchNormalization, Activation, Dropout
from tensorflow.keras.regularizers import l2
X = traindf.drop('Survived', axis = 1)
 y = traindf['Survived'] 
<define_variables>
with strategy.scope() :
model7 = tf.keras.Sequential([
efn.EfficientNetB7(
 input_shape=(*IMAGE_SIZE, 3),
weights='imagenet',
include_top=False 
),
GlobalAveragePooling2D() ,
Dense(1, activation='sigmoid')
 ])
 model7.compile(
 optimizer='adam',
loss = 'binary_crossentropy',
metrics=['accuracy'] 
)
 with strategy.scope() :
modelRN = tf.keras.Sequential([
tf.keras.applications.ResNet152V2(
 input_shape=(331, 331, 3),
weights='imagenet',
include_top=False 
),
GlobalAveragePooling2D() ,
Dense(1, activation='sigmoid')
 ])
 modelRN.compile(
 optimizer='adam',
loss = 'binary_crossentropy',
metrics=['accuracy'] 
)
 with strategy.scope() :
modelIV3 = tf.keras.Sequential([
tf.keras.applications.InceptionV3(
 input_shape=(*IMAGE_SIZE, 3),
weights='imagenet',
include_top=False 
),
GlobalAveragePooling2D() ,
Dense(1, activation='sigmoid')
 ])
 modelIV3.compile(
 optimizer='adam',
loss = 'binary_crossentropy',
metrics=['accuracy']
)
cat_features_index = np.where(X.dtypes != float)[0]<split>
lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)
 history7 = model7.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_schedule])
 historyRN = modelRN.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_schedule])
 historyIV3 = modelIV3.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, callbacks=[lr_schedule] )
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size =.25, random_state = 42 )<choose_model_class>
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilitiesRN = modelRN.predict(test_images_ds)
 probabilities7 = model7.predict(test_images_ds)
 probabilitiesV3 = modelIV3.predict(test_images_ds )
model = CatBoostClassifier(
 iterations = 50000,
task_type = 'GPU',
learning_rate =.001,
early_stopping_rounds = 1000,
depth = 10,
loss_function = 'CrossEntropy',
eval_metric = 'BalancedAccuracy' )<train_model>
print('Generating submission.csv files...')
 print('Generating submission.csv file...')
 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' )
model.fit(X_train, y_train, cat_features = cat_features_index, eval_set =(X_val, y_val), plot = True )<save_to_csv>
pred_dfRN = pd.DataFrame({'image_name': test_ids, 'target': np.concatenate(probabilitiesRN)})
 pred_df7 = pd.DataFrame({'image_name': test_ids, 'target': np.concatenate(probabilities7)})
 pred_dfV3 = pd.DataFrame({'image_name': test_ids, 'target': np.concatenate(probabilitiesV3)})
 pred_df7.head()
submission['PassengerId'] = testdf['PassengerId']
submission['Survived'] = model.predict(testdf, prediction_type='Class')
 submission['Survived'] = submission['Survived'].astype(int)
 submission.to_csv('submission.csv', index = False )<predict_on_test>
subRN = sub.copy()
sub7 = sub.copy()
subV3 = sub.copy()
subRN.head()
model.predict(testdf )<set_options>
del subRN['target']
subRN = subRN.merge(pred_dfRN, on='image_name')
 subRN.to_csv('submissionRN.csv', index=False)
 del subV3['target']
subV3 = subV3.merge(pred_dfV3, on='image_name')
 subV3.to_csv('submissionV3.csv', index=False)
 del sub7['target']
sub7 = sub7.merge(pred_df7, on='image_name')
 sub7.to_csv('submission7.csv', index=False)
 subRN.head()
<define_variables><EOS> 
ensemble1 =(subRN['target'] + sub7['target']+ subV3['target'])/3
ensemble_img1 = subRN['image_name']
ensemble_sub1 = pd.concat([ensemble_img1, ensemble1], axis = 1)
 ensemble_sub1.to_csv('submissionV3.csv', index=False)
 ensemble_sub1.head()