{"cells":[{"metadata":{},"cell_type":"markdown","source":"**Imports**","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import re\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nprint(tf.__version__)\nAUTO = tf.data.experimental.AUTOTUNE\nGCS_PATH=KaggleDatasets().get_gcs_path('512x512-melanoma-tfrecords-70k-images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"try:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is set.\n    # On Kaggle this is always the case.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Hyper parameters**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH_SIZE = 16 * strategy.num_replicas_in_sync\n            \nIMAGE_SIZE = [512 , 512]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH+'/train*')\n\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH+'/test*')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Preparing the dataset","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_augument_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.bfloat16) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    return image\n\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.bfloat16) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), \n        \"age_approx\": tf.io.FixedLenFeature([], tf.int64),  \n        \"sex\": tf.io.FixedLenFeature([], tf.int64), \n        \"anatom_site_general_challenge\" : tf.io.FixedLenFeature([] , tf.int64),\n        \"target\": tf.io.FixedLenFeature([], tf.int64),  \n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_augument_image(example['image'])\n    age = tf.cast(example['age_approx'], tf.bfloat16)\n    sex = tf.cast(example['sex'], tf.bfloat16)\n    asg = tf.cast(example['anatom_site_general_challenge'] , tf.bfloat16)\n    target = tf.cast(example['target'], tf.int32)\n    return image,target\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"age_approx\": tf.io.FixedLenFeature([], tf.int64),  \n        \"sex\": tf.io.FixedLenFeature([], tf.int64), \n        \"anatom_site_general_challenge\" : tf.io.FixedLenFeature([] , tf.int64),\n        \"image_name\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    age = tf.cast(example['age_approx'], tf.bfloat16)\n    sex = tf.cast(example['sex'], tf.bfloat16)\n    asg = tf.cast(example['anatom_site_general_challenge'] , tf.bfloat16)\n    idnum = example['image_name']\n    return image,idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES,labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=True):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n#VALIDATION_STEPS = NUM_VALID_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images ,{} unlabeled test images'.format(NUM_TRAINING_IMAGES,NUM_TEST_IMAGES))\nprint(\"STEPS_PER_EPOCH are {}\".format(STEPS_PER_EPOCH))\n#print(\"validation Steps are {}\".format(VALIDATION_STEPS))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_ds=get_training_dataset()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import *\nfrom tensorflow.keras.layers import *\nfrom efficientnet.tfkeras import *","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Model Architectures**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model():\n    base_model=EfficientNetB7(include_top=False,input_shape=(*IMAGE_SIZE,3))\n    base_model.trainable=False\n    inp1=Input(shape=(*IMAGE_SIZE,3))\n    #inp2=Input(shape=(3,))\n    X=base_model(inp1,training=False)\n    X=GlobalAveragePooling2D()(X)\n    '''Z=Dense(256,activation='relu')(inp2)\n    Z=BatchNormalization()(Z)\n    Z=Dropout(0.4)(Z)\n    Z=Dense(256,activation='relu')(Z)\n    Z=BatchNormalization()(Z)\n    Z=Dropout(0.4)(Z)\n    X=Concatenate()([X,Z])'''\n    X=Dense(512,activation='relu')(X)\n    X=BatchNormalization()(X)\n    X=Dropout(0.2)(X)\n    X=Dense(1024,activation='relu')(X)\n    X=BatchNormalization()(X)\n    X=Dropout(0.4)(X)\n    Y=Dense(1,activation='sigmoid')(X)\n    return Model(inputs=inp1,outputs=Y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model2():\n    base_model=EfficientNetB7(include_top=False,input_shape=(*IMAGE_SIZE,3))\n    base_model.trainable=False\n    inp1=Input(shape=(*IMAGE_SIZE,3))\n    #inp2=Input(shape=(3,))\n    X=base_model(inp1,training=False)\n    X=GlobalAveragePooling2D()(X)\n    '''Z=Dense(256,activation='relu')(inp2)\n    Z=BatchNormalization()(Z)\n    Z=Dropout(0.4)(Z)\n    Z=Dense(256,activation='relu')(Z)\n    Z=BatchNormalization()(Z)\n    Z=Dropout(0.4)(Z)\n    X=Concatenate()([X,Z])'''\n    X=Dense(256,activation='relu')(X)\n    X=Dropout(0.4)(X)\n    X=BatchNormalization()(X)\n    X=Dense(1024,activation='relu')(X)\n    X=BatchNormalization()(X)\n    X=Dropout(0.4)(X)\n    Y=Dense(1,activation='sigmoid')(X)\n    return Model(inputs=inp1,outputs=Y)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model1","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model = create_model()\n    \n    model.compile(optimizer='rmsprop',\n                  loss='binary_crossentropy',\n                  metrics=[tf.keras.metrics.BinaryCrossentropy(),'accuracy'])\n    \n    model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.keras.utils.plot_model(model,show_shapes=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Learning rate schedule for TPU, GPU and CPU.\n# Using an LR ramp up because fine-tuning a pre-trained model.\n# Starting with a high LR would break the pre-trained weights.\n\nLR_START = 0.000001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 4\nLR_SUSTAIN_EPOCHS = 4\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)\n\nes=tf.keras.callbacks.EarlyStopping(monitor='loss',mode='min',patience=4,verbose=1)\n\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='loss', factor=0.2,patience=4,mode='min', min_lr=0.001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train_ds,\n          epochs=20,\n          steps_per_epoch=STEPS_PER_EPOCH,\n          callbacks=[es,lr_callback,reduce_lr]\n         )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"def display_training_curves(training, validation, title, subplot):\n    #Source: https://www.kaggle.com/mgornergoogle/getting-started-with-100-flowers-on-tpu\n    \n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import h5py\n\nmodel_json = model.to_json()\nwith open(\"model.json\", \"w\") as json_file:\n    json_file.write(model_json)\n\nmodel.save_weights(\"mo.h5\")\nprint(\"Saved model to disk\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predictions","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def predictions():\n    test_ds=get_test_dataset(ordered=True)\n\n    test_ds_features=test_ds.map(lambda img,idnum: img) #Getting the features of the Test_ds\n\n    preds=model.predict(test_ds_features) #predicting with the model\n\n    test_ids_ds = test_ds.map(lambda img,imname: imname).unbatch()\n\n    test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n    prediction_df=pd.DataFrame({'image_name':test_ids ,'target':np.concatenate(preds)}) #writing to Dataframs\n\n    prediction_df.to_csv(\"submission.csv\",index=False) #Generating CSV file\n    \npredictions()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model2","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"with strategy.scope():\n    model2=create_model2()\n    \n    model2.compile(optimizer='adam',\n                  loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),\n                  metrics=[tf.keras.metrics.BinaryCrossentropy(),'accuracy'])\n    model2.summary()\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.keras.utils.plot_model(model2,show_shapes=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model2.fit(get_training_dataset(),\n           epochs=10,\n           steps_per_epoch=STEPS_PER_EPOCH//2,\n           callbacks=[es,lr_callback,reduce_lr]\n          )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def predictions():\n    test_ds=get_test_dataset(ordered=True)\n\n    test_ds_features=test_ds.map(lambda img,idnum: img) #Getting the features of the Test_ds\n\n    preds=model2.predict(test_ds_features) #predicting with the model\n\n    test_ids_ds = test_ds.map(lambda img,imname: imname).unbatch()\n\n    test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n    prediction_df=pd.DataFrame({'image_name':test_ids ,'target':np.concatenate(preds)}) #writing to Dataframs\n\n    prediction_df.to_csv(\"submission(1).csv\",index=False) #Generating CSV file\n    \npredictions()\n#not well","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}